var __getOwnPropNames = Object.getOwnPropertyNames;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};

// node_modules/shevchenko/dist/cjs/word-declension/rules/artifacts/declension-rules.json.js
var require_declension_rules_json = __commonJS({
  "node_modules/shevchenko/dist/cjs/word-declension/rules/artifacts/declension-rules.json.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var declensionRules = [
      {
        description: "\u0436\u0456\u043D\u043E\u0447\u0435 \u0456\u043C'\u044F \u043B\u044E\u0431\u043E\u0432",
        examples: [
          "\u043B\u044E\u0431\u043E\u0432"
        ],
        wordClass: "noun",
        gender: [
          "feminine"
        ],
        priority: 6,
        applicationType: [
          "givenName"
        ],
        pattern: {
          find: "^\u043B\u044E\u0431\u043E\u0432$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          accusative: [],
          ablative: [
            {
              "0": {
                action: "append",
                value: "'\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0456 \u0456\u043C\u0435\u043D\u0430 \u0444\u0435\u0434\u0456\u0440, \u0441\u0438\u0434\u0456\u0440",
        examples: [
          "\u0444\u0435\u0434\u0456\u0440",
          "\u0441\u0438\u0434\u0456\u0440"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 6,
        applicationType: [
          "givenName"
        ],
        pattern: {
          find: "^(\u0444\u0435\u0434\u0456\u0440|\u0441\u0438\u0434\u0456\u0440)$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0441\u043B\u043E\u0432\u043E \u0441\u0443\u0434\u0434\u044F",
        examples: [
          "\u0441\u0443\u0434\u0434\u044F"
        ],
        wordClass: "noun",
        gender: [
          "masculine",
          "feminine"
        ],
        priority: 6,
        applicationType: [
          "familyName"
        ],
        pattern: {
          find: "^\u0441\u0443\u0434\u0434\u044F$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0435\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0441\u043B\u043E\u0432\u043E \u0440\u0456\u043B\u043B\u044F",
        examples: [
          "\u0440\u0456\u043B\u043B\u044F"
        ],
        wordClass: "noun",
        gender: [
          "masculine",
          "feminine"
        ],
        priority: 6,
        applicationType: [
          "familyName"
        ],
        pattern: {
          find: "^\u0440\u0456\u043B\u043B\u044F$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0435\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)\u0432\u0435\u043D\u044C",
        examples: [
          "\u043F\u0456\u0432\u0435\u043D\u044C"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 6,
        applicationType: [],
        pattern: {
          find: "[\u0430\u0435\u0454\u0438\u0456\u0457\u043E\u0443\u044E\u044F]\u0432\u0435\u043D\u044C$",
          modify: "(.{1})(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "2": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: ""
              },
              "2": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "2": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "2": {
                action: "replace",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "2": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: ""
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)\u043B\u0435\u0446\u044C",
        examples: [
          "\u0441\u0442\u0440\u0456\u043B\u0435\u0446\u044C",
          "\u0431\u0456\u043B\u0435\u0446\u044C"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 6,
        applicationType: [],
        pattern: {
          find: "[\u0430\u0435\u0454\u0438\u0456\u0457\u043E\u0443\u044E\u044F]\u043B\u0435\u0446\u044C$",
          modify: "(.{1})(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u044C"
              },
              "2": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u044C"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u044C"
              },
              "2": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044C"
              },
              "2": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u044C"
              },
              "2": {
                action: "replace",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u044C"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u044C"
              },
              "2": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u044C"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u043A|\u043F|\u043A\u0440|\u043F\u043B|\u0434\u0440|\u0436\u0438\u0432)\u0456\u0442",
        examples: [
          "\u043A\u0456\u0442",
          "\u043A\u0440\u0456\u0442"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 6,
        applicationType: [],
        pattern: {
          find: "(\u043A|\u043F|\u043A\u0440|\u043F\u043B|\u0434\u0440|\u0436\u0438\u0432)\u0456\u0442$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0433\u0440\u0456\u043C",
        examples: [
          "\u0433\u0440\u0456\u043C"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 6,
        applicationType: [],
        pattern: {
          find: "\u0433\u0440\u0456\u043C$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u0434\u0437\u0432\u0456\u043D|\u0445\u0440\u0456\u043D)",
        examples: [
          "\u0434\u0437\u0432\u0456\u043D"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 6,
        applicationType: [],
        pattern: {
          find: "(\u0434\u0437\u0432\u0456\u043D|\u0445\u0440\u0456\u043D)$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0431\u0430\u0442\u0456\u0433",
        examples: [
          "\u0431\u0430\u0442\u0456\u0433"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 6,
        applicationType: [],
        pattern: {
          find: "\u0431\u0430\u0442\u0456\u0433$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "replace",
                value: "\u0437\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "replace",
                value: "\u0433\u0443"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0441\u043E\u043A\u0456\u043B",
        examples: [
          "\u0441\u043E\u043A\u0456\u043B"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 6,
        applicationType: [],
        pattern: {
          find: "\u0441\u043E\u043A\u0456\u043B$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043A\u0440\u0456\u043B\u044C",
        examples: [
          "\u043A\u0440\u0456\u043B\u044C"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 6,
        applicationType: [],
        pattern: {
          find: "\u043A\u0440\u0456\u043B\u044C$",
          modify: "(.{1})(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0456 \u0456\u043C\u0435\u043D\u0430 \u0456\u0433\u043E\u0440, \u043B\u0430\u0437\u0430\u0440",
        examples: [
          "\u0456\u0433\u043E\u0440",
          "\u043B\u0430\u0437\u0430\u0440"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 5,
        applicationType: [],
        pattern: {
          find: "^(\u0456\u0433\u043E\u0440|\u043B\u0430\u0437\u0430\u0440)$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0441\u043B\u043E\u0432\u043E \u0441\u0456\u043B\u044C",
        examples: [
          "\u0441\u0456\u043B\u044C"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 5,
        applicationType: [
          "familyName"
        ],
        pattern: {
          find: "^\u0441\u0456\u043B\u044C$",
          modify: "(.{1})(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          accusative: [],
          ablative: [
            {
              "2": {
                action: "replace",
                value: "\u043B\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)(\u0442\u0432\u0435\u0440\u0434\u0438\u0439 \u043F\u0440\u0438\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)\u0435(\u0446|\u043D)\u044C",
        examples: [
          "\u043F\u043E\u043B\u043E\u0432\u0435\u0446\u044C"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 5,
        applicationType: [],
        pattern: {
          find: "[\u0430\u0435\u0454\u0438\u0456\u0457\u043E\u0443\u044E\u044F]([\u0431\u0432\u0433\u0491\u0434\u0436\u0437\u043A\u043B\u043C\u043D\u043F\u0440\u0441\u0442\u0444\u0445\u0446\u0447\u0448\u0449]|\u0434\u0437|\u0434\u0436)\u0435(\u0446|\u043D)\u044C$",
          modify: "(.{1})(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "2": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: ""
              },
              "2": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "2": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "2": {
                action: "replace",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: ""
              },
              "2": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u0442\u0432\u0435\u0440\u0434\u0438\u0439 \u043F\u0440\u0438\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)(\u0442\u0432\u0435\u0440\u0434\u0438\u0439 \u043F\u0440\u0438\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)\u0435(\u0446|\u043D)\u044C",
        examples: [
          "\u0436\u043D\u0435\u0446\u044C"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 5,
        applicationType: [],
        pattern: {
          find: "([\u0431\u0432\u0433\u0491\u0434\u0436\u0437\u043A\u043B\u043C\u043D\u043F\u0440\u0441\u0442\u0444\u0445\u0446\u0447\u0448\u0449]|\u0434\u0437|\u0434\u0436)([\u0431\u0432\u0433\u0491\u0434\u0436\u0437\u043A\u043B\u043C\u043D\u043F\u0440\u0441\u0442\u0444\u0445\u0446\u0447\u0448\u0449]|\u0434\u0437|\u0434\u0436)\u0435(\u0446|\u043D)\u044C$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u0440\u0456\u0434|\u043F\u043B\u0456\u0434)",
        examples: [
          "\u0440\u0456\u0434",
          "\u043F\u043B\u0456\u0434"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 5,
        applicationType: [],
        pattern: {
          find: "(\u0440\u0456\u0434|\u043F\u043B\u0456\u0434)$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0456 \u043F\u0440\u0456\u0437\u0432\u0438\u0449\u0430 \u043D\u0430 -\u043D\u0456\u0441, \u0431\u0435\u0437 \u0447\u0435\u0440\u0433\u0443\u0432\u0430\u043D\u043D\u044F",
        examples: [
          "\u0445\u0430\u043D\u0456\u0441",
          "\u0434\u0435\u043D\u0456\u0441",
          "\u043C\u0430\u043D\u0456\u0441"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 5,
        applicationType: [],
        pattern: {
          find: "^([\u0431\u0432\u0433\u0491\u0434\u0436\u0437\u0439\u043A\u043B\u043C\u043D\u043F\u0440\u0441\u0442\u0444\u0445\u0446\u0447\u0448\u0449]|\u0434\u0437|\u0434\u0436)[\u0430\u0435\u0454\u0438\u0456\u0457\u043E\u0443\u044E\u044F]\u043D\u0456\u0441$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u0437|\u044F\u0432)\u0456\u0440",
        examples: [
          "\u0434\u0438\u0432\u043E\u0437\u0456\u0440",
          "\u044F\u0432\u0456\u0440"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 5,
        applicationType: [],
        pattern: {
          find: "(\u0437|\u044F\u0432|\u0433)\u0456\u0440$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043E\u0440\u0435\u043B",
        examples: [
          "\u043E\u0440\u0435\u043B"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 5,
        applicationType: [],
        pattern: {
          find: "\u043E\u0440\u0435\u043B$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043B"
              },
              "1": {
                action: "replace",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043B"
              },
              "1": {
                action: "replace",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043B"
              },
              "1": {
                action: "replace",
                value: "\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043B"
              },
              "1": {
                action: "replace",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043B"
              },
              "1": {
                action: "replace",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043B"
              },
              "1": {
                action: "replace",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043B"
              },
              "1": {
                action: "replace",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u044F\u043A\u0456\u0440",
        examples: [
          "\u044F\u043A\u0456\u0440"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 5,
        applicationType: [],
        pattern: {
          find: "\u044F\u043A\u0456\u0440$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u044E"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0431\u0456\u0434\u044C",
        examples: [
          "\u043B\u0435\u0431\u0456\u0434\u044C"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 5,
        applicationType: [],
        pattern: {
          find: ".\u0431\u0456\u0434\u044C$",
          modify: "(.{1})(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              },
              "2": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u0435"
              },
              "2": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              },
              "2": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              },
              "2": {
                action: "replace",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u0435"
              },
              "2": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043C\u0456\u043D\u044C",
        examples: [
          "\u043A\u0440\u0435\u043C\u0456\u043D\u044C"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 5,
        applicationType: [],
        pattern: {
          find: ".\u043C\u0456\u043D\u044C$",
          modify: "(.{1})(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              },
              "2": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u0435"
              },
              "2": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              },
              "2": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              },
              "2": {
                action: "replace",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u0435"
              },
              "2": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0441\u0456\u043B\u044C",
        examples: [
          "\u043A\u0438\u0441\u0456\u043B\u044C"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 5,
        applicationType: [],
        pattern: {
          find: "\u0441\u0456\u043B\u044C$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043A\u0456\u043D\u044C",
        examples: [
          "\u043A\u0456\u043D\u044C"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 5,
        applicationType: [],
        pattern: {
          find: "\u043A\u0456\u043D\u044C$",
          modify: "(.{1})(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043A\u0443\u043B\u0456\u0448",
        examples: [
          "\u043A\u0443\u043B\u0456\u0448"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 5,
        applicationType: [],
        pattern: {
          find: "\u043A\u0443\u043B\u0456\u0448$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0436\u0456\u043D\u043E\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043D\u0430 -(\u0442\u0432\u0435\u0440\u0434\u0438\u0439 \u043F\u0440\u0438\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)\u044C\u043A\u0430",
        examples: [
          "\u0456\u043B\u044C\u043D\u0438\u0446\u044C\u043A\u0430",
          "\u0441\u0443\u043C\u0441\u044C\u043A\u0430"
        ],
        wordClass: "adjective",
        gender: [
          "feminine"
        ],
        priority: 4,
        applicationType: [
          "familyName"
        ],
        pattern: {
          find: "([\u0431\u0432\u0433\u0491\u0434\u0436\u0437\u043A\u043B\u043C\u043D\u043F\u0440\u0441\u0442\u0444\u0445\u0446\u0447\u0448\u0449]|\u0434\u0437|\u0434\u0436)\u044C\u043A\u0430$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u0457"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0456\u0439"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u0443"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456\u0439"
              }
            }
          ],
          vocative: []
        }
      },
      {
        description: "\u0436\u0456\u043D\u043E\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043D\u0430 -\u043E\u0432\u0430",
        examples: [
          "\u0456\u0432\u0430\u043D\u043E\u0432\u0430"
        ],
        wordClass: "adjective",
        gender: [
          "feminine"
        ],
        priority: 4,
        applicationType: [
          "familyName"
        ],
        pattern: {
          find: "\u043E\u0432\u0430$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u0457"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0456\u0439"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u0443"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456\u0439"
              }
            }
          ],
          vocative: []
        }
      },
      {
        description: "\u0436\u0456\u043D\u043E\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043D\u0430 -\u0456\u043D\u0430",
        examples: [
          "\u0437\u0435\u043B\u0435\u043D\u043A\u0456\u043D\u0430"
        ],
        wordClass: "adjective",
        gender: [
          "feminine"
        ],
        priority: 4,
        applicationType: [
          "familyName"
        ],
        pattern: {
          find: "\u0456\u043D\u0430$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u0457"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0456\u0439"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u0443"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456\u0439"
              }
            }
          ],
          vocative: []
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)\u0454\u0446\u044C",
        examples: [
          "\u0437\u0430\u0454\u0446\u044C"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 4,
        applicationType: [],
        pattern: {
          find: "[\u0430\u0435\u0454\u0438\u0456\u0457\u043E\u0443\u044E\u044F]\u0454\u0446\u044C$",
          modify: "(.{1})(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u0439"
              },
              "2": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0439"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u0439"
              },
              "2": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u0439"
              },
              "2": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0439"
              },
              "2": {
                action: "replace",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0439"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u0439"
              },
              "2": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u0439"
              },
              "2": {
                action: "replace",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0432\u0456\u0437",
        examples: [
          "\u0443\u0437\u0432\u0456\u0437"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 4,
        applicationType: [],
        pattern: {
          find: "\u0432\u0456\u0437$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043A\u0456\u0432",
        examples: [
          "\u044F\u043A\u0456\u0432"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 4,
        applicationType: [
          "givenName"
        ],
        pattern: {
          find: ".\u043A\u0456\u0432$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u043A|\u0440)\u0456\u043F",
        examples: [
          "\u043F\u0440\u043E\u043A\u0456\u043F"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 4,
        applicationType: [],
        pattern: {
          find: ".(\u043A|\u0440)\u0456\u043F$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043F\u0456\u043F",
        examples: [
          "\u043F\u0440\u043E\u043A\u0456\u043F"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 4,
        applicationType: [],
        pattern: {
          find: "\u043F\u0456\u043F$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043D\u0456\u0441",
        examples: [
          "\u043A\u0440\u0438\u0432\u043E\u043D\u0456\u0441"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 4,
        applicationType: [],
        pattern: {
          find: "\u043D\u0456\u0441$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0432\u0456\u043B",
        examples: [
          "\u0440\u044F\u0431\u043E\u0432\u0456\u043B"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 4,
        applicationType: [],
        pattern: {
          find: "\u0432\u0456\u043B$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0440\u0456\u0433",
        examples: [
          "\u043F\u0438\u0440\u0456\u0433"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 4,
        applicationType: [],
        pattern: {
          find: "\u0440\u0456\u0433$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "replace",
                value: "\u0437\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0445\u0456\u0434",
        examples: [
          "\u043F\u0440\u0438\u0445\u0456\u0434"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 4,
        applicationType: [],
        pattern: {
          find: "\u0445\u0456\u0434$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0436\u0456\u043D\u043E\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)\u043B\u044C",
        examples: [
          "\u043C\u0456\u0448\u0435\u043B\u044C",
          "\u043D\u0456\u043A\u043E\u043B\u044C",
          "c\u0435\u0441\u0456\u043B\u044C"
        ],
        wordClass: "noun",
        gender: [
          "feminine"
        ],
        priority: 4,
        applicationType: [
          "givenName"
        ],
        pattern: {
          find: "[\u0430\u0435\u0454\u0438\u0456\u0457\u043E\u0443\u044E\u044F]\u043B\u044C$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "1": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          dative: [
            {
              "1": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          accusative: [],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043B\u043B"
              },
              "1": {
                action: "replace",
                value: "\u044E"
              }
            }
          ],
          locative: [
            {
              "1": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: []
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0436\u0456\u043D\u043E\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 (\u0433\u0443\u0431\u043D\u0438\u0439_\u043F\u0440\u0438\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)",
        examples: [
          "\u0437\u0435\u0439\u043D\u0430\u0431",
          "\u0440\u0443\u0444"
        ],
        wordClass: "noun",
        gender: [
          "feminine"
        ],
        priority: 4,
        applicationType: [
          "givenName"
        ],
        pattern: {
          find: "[\u0431\u043F\u0432\u043C\u0444]$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0438\u0448\u0438\u043D",
        examples: [
          "\u043A\u043E\u0432\u0430\u043B\u0438\u0448\u0438\u043D"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 4,
        applicationType: [],
        pattern: {
          find: "\u0438\u0448\u0438\u043D$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u0438\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u0430\u0433\u043E|\u043E\u0432\u043E)",
        examples: [
          "\u0436\u0438\u0432\u0430\u0433\u043E"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 4,
        applicationType: [],
        pattern: {
          find: "(\u0430\u0433\u043E|\u043E\u0432\u043E)$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [],
          dative: [],
          accusative: [],
          ablative: [],
          locative: [],
          vocative: []
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0442\u0435\u0440",
        examples: [
          "\u0432\u0456\u0442\u0435\u0440",
          "\u0431\u0443\u0439\u043C\u0438\u0441\u0442\u0435\u0440"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 4,
        applicationType: [],
        pattern: {
          find: "[\u0456\u0441]\u0442\u0435\u0440$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0454\u0433\u0435\u0440",
        examples: [
          "\u0454\u0433\u0435\u0440"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 4,
        applicationType: [],
        pattern: {
          find: "\u0454\u0433\u0435\u0440$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u043F\u0435\u0440\u0448\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0441\u0432\u0456\u0442",
        examples: [
          "\u0441\u0432\u0456\u0442"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 4,
        applicationType: [],
        pattern: {
          find: "\u0441\u0432\u0456\u0442$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0456 \u0456\u043C\u0435\u043D\u0430 / \u043D\u0430 -(\u0432|\u0434)\u0456\u0440",
        examples: [
          "\u0434\u0456\u0440",
          "\u0432\u0456\u0440"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 4,
        applicationType: [],
        pattern: {
          find: "(\u0432|\u0434)\u0456\u0440$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043D\u0430 -\u043A\u0456\u0439 (\u043F\u043E\u043C\u0438\u043B\u043A\u043E\u0432\u0430 \u0442\u0440\u0430\u043D\u0441\u043B\u0456\u0442\u0435\u0440\u0430\u0446\u0456\u044F)",
        examples: [
          "\u0434\u0456\u0434\u043A\u0456\u0432\u0441\u044C\u043A\u0456\u0439"
        ],
        wordClass: "adjective",
        gender: [
          "masculine"
        ],
        priority: 3,
        applicationType: [
          "familyName"
        ],
        pattern: {
          find: "\u043A\u0456\u0439$",
          modify: "(.{2})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u0433\u043E"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u043C\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u0433\u043E"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0438\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u043C\u0443"
              }
            }
          ],
          vocative: []
        }
      },
      {
        description: "\u043C\u043D\u043E\u0436\u0438\u043D\u0430 / \u043D\u0430 -\u0438\u0445",
        examples: [
          "\u0441\u0435\u0434\u0438\u0445"
        ],
        wordClass: "adjective",
        gender: [
          "masculine"
        ],
        priority: 3,
        applicationType: [],
        pattern: {
          find: "\u0438\u0445$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [],
          dative: [],
          accusative: [],
          ablative: [],
          locative: [],
          vocative: []
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0433\u0430",
        examples: [
          "\u043D\u043E\u0433\u0430"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 3,
        applicationType: [],
        pattern: {
          find: "\u0433\u0430$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "1": {
                action: "replace",
                value: "\u0438"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0437"
              },
              "1": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          accusative: [
            {
              "1": {
                action: "replace",
                value: "\u0443"
              }
            }
          ],
          ablative: [
            {
              "1": {
                action: "replace",
                value: "\u043E\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0437"
              },
              "1": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "1": {
                action: "replace",
                value: "\u043E"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0435\u043A\u0430\u0440, -\u0435\u0442\u0430\u0440, -\u0437\u0430\u0440, -\u0443\u0445\u0430\u0440",
        examples: [
          "\u043F\u0435\u043A\u0430\u0440",
          "\u0440\u0435\u0448\u0435\u0442\u0430\u0440",
          "\u043A\u043E\u0436\u0443\u0445\u0430\u0440",
          "\u043A\u043E\u0431\u0437\u0430\u0440"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 3,
        applicationType: [],
        pattern: {
          find: "(\u0435\u043A\u0430\u0440|\u0435\u0442\u0430\u0440|([\u0431\u0432\u0433\u0491\u0434\u0436\u0437\u0439\u043A\u043B\u043C\u043D\u043F\u0440\u0441\u0442\u0444\u0445\u0446\u0447\u0448\u0449]|\u0434\u0437|\u0434\u0436)\u0437\u0430\u0440|\u0443\u0445\u0430\u0440)(?<!\u0433\u0443\u0437\u0430\u0440)$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043A\u0456\u0448",
        examples: [
          "\u0440\u043E\u0437\u043A\u0456\u0448"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 3,
        applicationType: [],
        pattern: {
          find: "\u043A\u0456\u0448$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u044C\u043E",
        examples: [
          "\u0456\u0432\u0430\u043D\u044C\u043E",
          "\u043A\u0443\u0437\u044C\u043E"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 3,
        applicationType: [],
        pattern: {
          find: "\u044C\u043E$",
          modify: "(.{2})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ],
          vocative: []
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0440\u0435\u0434",
        examples: [
          "\u0430\u043B\u044C\u0444\u0440\u0435\u0434"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 3,
        applicationType: [],
        pattern: {
          find: "\u0440\u0435\u0434$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u0431\u0443\u0441\u0435\u043B",
        examples: [
          "\u0431\u0443\u0441\u0435\u043B"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 3,
        applicationType: [],
        pattern: {
          find: "\u0431\u0443\u0441\u0435\u043B$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0435[\u0432\u043C\u043D]",
        examples: [
          "\u0430\u0440\u0442\u0435\u043C",
          "\u0441\u0435\u043C\u0435\u043D",
          "\u043B\u0435\u0432"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 3,
        applicationType: [],
        pattern: {
          find: "\u0435[\u0432\u043C\u043D]$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0435\u0440",
        examples: [
          "\u0440\u0456\u0445\u0442\u0435\u0440"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 3,
        applicationType: [],
        pattern: {
          find: "\u0435\u0440$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043F\u0435\u0441",
        examples: [
          "\u043F\u0435\u0441"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 3,
        applicationType: [],
        pattern: {
          find: "\u043F\u0435\u0441$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043A\u043E",
        examples: [
          "\u043C\u0430\u0440\u043A\u043E"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 3,
        applicationType: [],
        pattern: {
          find: "\u043A\u043E$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u0443"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u0443"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0438\u0439",
        examples: [
          "\u0431\u0430\u0442\u0438\u0439"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 3,
        applicationType: [],
        pattern: {
          find: "\u0438\u0439$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0454\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u0457"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u043F\u0435\u0440\u0448\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0439\u043E",
        examples: [
          "\u0439\u043E\u0439\u043E"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 3,
        applicationType: [],
        pattern: {
          find: "\u0439\u043E$",
          modify: "(.{2})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u0432\u0456"
              }
            }
          ],
          vocative: []
        }
      },
      {
        description: "\u043F\u0435\u0440\u0448\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0431\u043E",
        examples: [
          "\u0433\u043E\u043B\u0435\u043C\u0431\u043E"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 3,
        applicationType: [],
        pattern: {
          find: "\u0431\u043E$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u0438"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u0443"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: []
        }
      },
      {
        description: "\u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043D\u0430 -\u043E\u0439, -\u0438\u0439",
        examples: [
          "\u0442\u043E\u043B\u0441\u0442\u043E\u0439",
          "\u0441\u0443\u0445\u043E\u043C\u043B\u0438\u043D\u0441\u044C\u043A\u0438\u0439"
        ],
        wordClass: "adjective",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [
          "familyName"
        ],
        pattern: {
          find: "(\u043E\u0439|\u0438\u0439)$",
          modify: "(.{2})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u0433\u043E"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u043C\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u0433\u043E"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0438\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u043C\u0443"
              }
            }
          ],
          vocative: []
        }
      },
      {
        description: "\u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043D\u0430 -\u0456\u0439",
        examples: [
          "\u0437\u0430\u0431\u043E\u043B\u043E\u0442\u043D\u0456\u0439"
        ],
        wordClass: "adjective",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [
          "familyName"
        ],
        pattern: {
          find: "\u0456\u0439$",
          modify: "(.{2})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u044C\u043E\u0433\u043E"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u044C\u043E\u043C\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044C\u043E\u0433\u043E"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0456\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u044C\u043E\u043C\u0443"
              }
            }
          ],
          vocative: []
        }
      },
      {
        description: "\u0436\u0456\u043D\u043E\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043D\u0430 -(\u0442\u0432\u0435\u0440\u0434\u0438\u0439 \u043F\u0440\u0438\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)\u0430",
        examples: [
          "\u0437\u0435\u043B\u0435\u043D\u0430"
        ],
        wordClass: "adjective",
        gender: [
          "feminine"
        ],
        priority: 2,
        applicationType: [
          "familyName"
        ],
        pattern: {
          find: "([\u0431\u0432\u0433\u0491\u0434\u0436\u0437\u043A\u043B\u043C\u043D\u043F\u0440\u0441\u0442\u0444\u0445\u0446\u0447\u0448\u0449]|\u0434\u0437|\u0434\u0436)\u0430$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u0457"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0456\u0439"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u0443"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456\u0439"
              }
            }
          ],
          vocative: []
        }
      },
      {
        description: "\u0436\u0456\u043D\u043E\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043D\u0430 -(\u0442\u0432\u0435\u0440\u0434\u0438\u0439 \u043F\u0440\u0438\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)\u044F",
        examples: [
          "\u0437\u0430\u0434\u043E\u0440\u043E\u0436\u043D\u044F"
        ],
        wordClass: "adjective",
        gender: [
          "feminine"
        ],
        priority: 2,
        applicationType: [
          "familyName"
        ],
        pattern: {
          find: "([\u0431\u0432\u0433\u0491\u0434\u0436\u0437\u043A\u043B\u043C\u043D\u043F\u0440\u0441\u0442\u0444\u0445\u0446\u0447\u0448\u0449]|\u0434\u0437|\u0434\u0436)\u044F$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u044C\u043E\u0457"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0456\u0439"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u044C\u043E\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456\u0439"
              }
            }
          ],
          vocative: []
        }
      },
      {
        description: "\u0436\u0456\u043D\u043E\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043D\u0430 -\u0430\u044F",
        examples: [
          "\u0442\u043E\u043B\u0441\u0442\u0430\u044F"
        ],
        wordClass: "adjective",
        gender: [
          "feminine"
        ],
        priority: 2,
        applicationType: [
          "familyName"
        ],
        pattern: {
          find: "\u0430\u044F$",
          modify: "(.{2})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u0457"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0456\u0439"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u0443\u044E"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456\u0439"
              }
            }
          ],
          vocative: []
        }
      },
      {
        description: "\u0436\u0456\u043D\u043E\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043D\u0430 -\u044F\u044F",
        examples: [
          "\u0437\u0430\u0431\u043E\u043B\u043E\u0442\u043D\u044F\u044F"
        ],
        wordClass: "adjective",
        gender: [
          "feminine"
        ],
        priority: 2,
        applicationType: [
          "familyName"
        ],
        pattern: {
          find: "\u044F\u044F$",
          modify: "(.{2})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u044C\u043E\u0457"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0456\u0439"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u044C\u043E\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456\u0439"
              }
            }
          ],
          vocative: []
        }
      },
      {
        description: "\u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0456 \u043F\u043E \u0431\u0430\u0442\u044C\u043A\u043E\u0432\u0456 \u0442\u0430 \u043F\u0440\u0456\u0437\u0432\u0438\u0449\u0430 / \u043D\u0430 -\u0438\u0447",
        examples: [
          "\u0432\u0430\u043B\u0435\u0440\u0456\u0439\u043E\u0432\u0438\u0447",
          "\u0440\u0438\u043D\u0434\u0438\u0447"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [
          "patronymicName",
          "familyName"
        ],
        pattern: {
          find: "\u0438\u0447$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ]
        }
      },
      {
        description: "\u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0456 \u043F\u043E \u0431\u0430\u0442\u044C\u043A\u043E\u0432\u0456 \u0442\u0430 \u043F\u0440\u0456\u0437\u0432\u0438\u0449\u0430 / \u043D\u0430 -\u0456\u0447",
        examples: [
          "\u0456\u043B\u043B\u0456\u0447"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [
          "patronymicName",
          "familyName"
        ],
        pattern: {
          find: "\u0456\u0447$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ]
        }
      },
      {
        description: "\u0436\u0456\u043D\u043E\u0447\u0456 \u043F\u043E \u0431\u0430\u0442\u044C\u043A\u043E\u0432\u0456 / \u043D\u0430 -\u043D\u0430",
        examples: [
          "\u044E\u0440\u0456\u0457\u0432\u043D\u0430"
        ],
        wordClass: "noun",
        gender: [
          "feminine"
        ],
        priority: 2,
        applicationType: [
          "patronymicName"
        ],
        pattern: {
          find: "\u043D\u0430$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u0438"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u0443"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              }
            }
          ]
        }
      },
      {
        description: "\u0436\u0456\u043D\u043E\u0447\u0456 \u0456\u043C\u0435\u043D\u0430 / \u043D\u0430 -(\u0442\u0432\u0435\u0440\u0434\u0438\u0439 \u043F\u0440\u0438\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)\u044F",
        examples: [
          "\u043D\u0435\u043B\u044F"
        ],
        wordClass: "noun",
        gender: [
          "feminine"
        ],
        priority: 2,
        applicationType: [
          "givenName"
        ],
        pattern: {
          find: "([\u0431\u0432\u0433\u0491\u0434\u0436\u0437\u043A\u043B\u043C\u043D\u043F\u0440\u0441\u0442\u0444\u0445\u0446\u0447\u0448\u0449]|\u0434\u0437|\u0434\u0436)\u044F$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0435\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0456 \u0456\u043C\u0435\u043D\u0430 / \u043D\u0430 -\u043D\u044F",
        examples: [
          "\u0436\u0435\u043D\u044F"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [
          "givenName"
        ],
        pattern: {
          find: "\u043D\u044F$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0435\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0443\u0433",
        examples: [
          "\u0442\u043E\u0432\u0441\u0442\u043E\u043B\u0443\u0433"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [
          "familyName"
        ],
        pattern: {
          find: "\u0443\u0433$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043E\u0432, -\u0435\u0432 (-\u0454\u0432), -\u0456\u0432 (-\u0457\u0432), -\u0456\u043D (-\u0457\u043D)",
        examples: [
          "\u043F\u0430\u0432\u043B\u043E\u0432",
          "\u043D\u0456\u043A\u0456\u0442\u0456\u043D"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [
          "familyName"
        ],
        pattern: {
          find: "([\u043E\u0435\u0454]\u0432|[\u0456\u0457]\u0432|[\u0456\u0457]\u043D)$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u0438\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0438\u043D",
        examples: [
          "\u0433\u0430\u0440\u0448\u0438\u043D"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [
          "familyName"
        ],
        pattern: {
          find: "(?<!\u0443\u0441|\u0432|\u043D)\u0438\u043D$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u0438\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u044F\u0440",
        examples: [
          "\u0441\u043A\u043B\u044F\u0440"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "\u044F\u0440$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0436\u0456\u043D\u043E\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430, \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u043E|\u044C|\u0442\u0432\u0435\u0440\u0434\u0438\u0439 \u043F\u0440\u0438\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)",
        examples: [
          "\u0448\u0435\u0432\u0447\u0435\u043D\u043A\u043E"
        ],
        wordClass: "noun",
        gender: [
          "feminine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "(\u043E|\u044C|([\u0431\u0432\u0433\u0491\u0434\u0436\u0437\u043A\u043B\u043C\u043D\u043F\u0440\u0441\u0442\u0444\u0445\u0446\u0447\u0448\u0449]|\u0434\u0437|\u0434\u0436))$",
          modify: "(.{2})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [],
          dative: [],
          accusative: [],
          ablative: [],
          locative: [],
          vocative: []
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043E\u043A",
        examples: [
          "\u0431\u0443\u0440\u044F\u0447\u043E\u043A"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "((?<=[\u0430\u0435\u0454\u0438\u0456\u0457\u043E\u0443\u044E\u044F].*[\u0430\u0435\u0454\u0438\u0456\u0457\u043E\u0443\u044E\u044F].*\u043B)|(?<=[\u0430\u0435\u0454\u0438\u0456\u0457\u043E\u0443\u044E\u044F].*[^\u043B]))\u043E\u043A$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0435(\u0442\u0432\u0435\u0440\u0434\u0430_\u043F\u0440\u0438\u043B\u043E\u0441\u043E\u043D\u0430)",
        examples: [
          "\u043C\u0430\u0440\u0435\u043A"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "\u0435([\u0431\u0432\u0433\u0491\u0434\u0436\u0437\u043A\u043B\u043C\u043D\u043F\u0440\u0441\u0442\u0444\u0445\u0446\u0447\u0448\u0449]|\u0434\u0437|\u0434\u0436)$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u0442\u0432\u0435\u0440\u0434\u0438\u0439 \u043F\u0440\u0438\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)\u044F",
        examples: [
          "\u0433\u043C\u0438\u0440\u044F"
        ],
        wordClass: "noun",
        gender: [
          "masculine",
          "feminine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "([\u0431\u0432\u0433\u0491\u0434\u0436\u0437\u043A\u043B\u043C\u043D\u043F\u0440\u0441\u0442\u0444\u0445\u0446\u0447\u0448\u0449]|\u0434\u0437|\u0434\u0436)\u044F$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0435\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439, \u0436\u0456\u043D\u043E\u0447\u0438\u0439 \u0440\u043E\u0434\u0438 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439|\u044C|\u0439)\u044F",
        examples: [
          "\u044E\u043B\u0456\u044F",
          "\u043C\u0430\u0439\u044F"
        ],
        wordClass: "noun",
        gender: [
          "masculine",
          "feminine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "([\u0430\u0435\u0454\u0438\u0456\u0457\u043E\u0443\u044E\u044F]|\u044C|\u0439)\u044F$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u0457"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0457"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0454\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0457"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u0454"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C\u0456\u0448\u0430\u043D\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u0434\u0436|\u0436|\u0447|\u0448)",
        examples: [
          "\u044F\u043D\u0443\u0448",
          "\u0434\u0436\u043E\u0440\u0434\u0436"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "(\u0434\u0436|\u0436|\u0447|\u0448)$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043D",
        examples: [
          "\u043C\u0456\u0449\u0430\u043D\u0438\u043D"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "\u043D$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / (\u0441\u0432\u0435\u043A\u043E\u0440|\u0446\u0443\u043A\u043E\u0440)",
        examples: [
          "\u0441\u0432\u0435\u043A\u043E\u0440",
          "\u0446\u0443\u043A\u043E\u0440"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "(\u0441\u0432\u0435\u043A\u043E\u0440|\u0446\u0443\u043A\u043E\u0440)$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u0441\u043D\u0456\u0433\u0438\u0440",
        examples: [
          "\u0441\u043D\u0456\u0433\u0438\u0440"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "\u0441\u043D\u0456\u0433\u0438\u0440$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u044E"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u0435\u0432\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u044E"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043A",
        examples: [
          "\u043A\u0443\u0437\u0438\u043A",
          "\u043C\u0438\u0441\u044F\u043A"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "\u043A$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0445",
        examples: [
          "\u043A\u043E\u0436\u0443\u0445"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "\u0445$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u0441\u043E\u043B\u043E\u0432\u0435\u0439",
        examples: [
          "\u0441\u043E\u043B\u043E\u0432\u0435\u0439"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "\u0441\u043E\u043B\u043E\u0432\u0435\u0439$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "replace",
                value: "'\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "replace",
                value: "'\u0454\u0432\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "replace",
                value: "'\u044E"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "replace",
                value: "'\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "replace",
                value: "'\u0454\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "replace",
                value: "'\u0457"
              }
            },
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "replace",
                value: "'\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "replace",
                value: "'\u0454\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: ""
              },
              "1": {
                action: "replace",
                value: "'\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u043F\u0435\u0440\u0448\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439, \u0436\u0456\u043D\u043E\u0447\u0438\u0439 \u0440\u043E\u0434\u0438 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0445\u0430",
        examples: [
          "\u0441\u0442\u0430\u0440\u0443\u0445\u0430"
        ],
        wordClass: "noun",
        gender: [
          "masculine",
          "feminine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "\u0445\u0430$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "1": {
                action: "replace",
                value: "\u0438"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0441"
              },
              "1": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          accusative: [
            {
              "1": {
                action: "replace",
                value: "\u0443"
              }
            }
          ],
          ablative: [
            {
              "1": {
                action: "replace",
                value: "\u043E\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0441"
              },
              "1": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "1": {
                action: "replace",
                value: "\u043E"
              }
            },
            {
              "1": {
                action: "replace",
                value: "\u0430"
              }
            }
          ]
        }
      },
      {
        description: "\u043F\u0435\u0440\u0448\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439, \u0436\u0456\u043D\u043E\u0447\u0438\u0439 \u0440\u043E\u0434\u0438 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043A\u0430",
        examples: [
          "\u043F\u0440\u0438\u043B\u0443\u043A\u0430"
        ],
        wordClass: "noun",
        gender: [
          "masculine",
          "feminine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "\u043A\u0430$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "1": {
                action: "replace",
                value: "\u0438"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0446"
              },
              "1": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          accusative: [
            {
              "1": {
                action: "replace",
                value: "\u0443"
              }
            }
          ],
          ablative: [
            {
              "1": {
                action: "replace",
                value: "\u043E\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0446"
              },
              "1": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "1": {
                action: "replace",
                value: "\u043E"
              }
            },
            {
              "1": {
                action: "replace",
                value: "\u0430"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u0436\u0443\u0440\u0430\u0432\u0435\u043B\u044C",
        examples: [
          "\u0436\u0443\u0440\u0430\u0432\u0435\u043B\u044C"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "\u0436\u0443\u0440\u0430\u0432\u0435\u043B\u044C$",
          modify: "(.{3})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u043B\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u043B\u0435\u0432\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u043B\u044E"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u043B\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043B\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043B\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043B\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u043F\u0435\u0440\u0448\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u0442\u0432\u0435\u0440\u0434\u0438\u0439 \u043F\u0440\u0438\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)\u043E",
        examples: [
          "\u043F\u0435\u0442\u0440\u043E",
          "\u043F\u0430\u0432\u043B\u043E"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "([\u0431\u0432\u0433\u0491\u0434\u0436\u0437\u043A\u043B\u043C\u043D\u043F\u0440\u0441\u0442\u0444\u0445\u0446\u0447\u0448\u0449]|\u0434\u0437|\u0434\u0436)\u043E$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0443"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u043F\u0435\u0440\u0448\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0436\u0456\u043D\u043E\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u0433|\u0491)\u0430",
        examples: [
          "\u043E\u043B\u044C\u0433\u0430"
        ],
        wordClass: "noun",
        gender: [
          "feminine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "(\u0433|\u0491)\u0430$",
          modify: "(.{1})(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "1": {
                action: "replace",
                value: "\u0438"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0437"
              },
              "1": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          accusative: [
            {
              "1": {
                action: "replace",
                value: "\u0443"
              }
            }
          ],
          ablative: [
            {
              "1": {
                action: "replace",
                value: "\u043E\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0437"
              },
              "1": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "1": {
                action: "replace",
                value: "\u043E"
              }
            }
          ]
        }
      },
      {
        description: "\u043F\u0435\u0440\u0448\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u043B\u0435",
        examples: [
          "\u043F\u043E\u043B\u0435"
        ],
        wordClass: "noun",
        gender: [
          "masculine",
          "feminine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "\u043B\u0435$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u0435"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: []
        }
      },
      {
        description: "\u043F\u0435\u0440\u0448\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439, \u0436\u0456\u043D\u043E\u0447\u0438\u0439 \u0440\u043E\u0434\u0438 / \u043C\u0456\u0448\u0430\u043D\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0430",
        examples: [
          "\u043C\u043E\u0439\u0448\u0430"
        ],
        wordClass: "noun",
        gender: [
          "masculine",
          "feminine"
        ],
        priority: 2,
        applicationType: [],
        pattern: {
          find: "(\u0434\u0436|\u0436|\u0447|\u0448|\u0449)\u0430$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u0443"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0435\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -(\u0442\u0432\u0435\u0440\u0434\u0438\u0439 \u043F\u0440\u0438\u0433\u043E\u043B\u043E\u0441\u043D\u0438\u0439)",
        examples: [
          "\u043E\u043B\u0435\u043A\u0441\u0430\u043D\u0434\u0440"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 1,
        applicationType: [],
        pattern: {
          find: "([\u0431\u0432\u0433\u0491\u0434\u0436\u0437\u043A\u043B\u043C\u043D\u043F\u0440\u0441\u0442\u0444\u0445\u0446\u0447\u0448\u0449]|\u0434\u0437|\u0434\u0436)$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "append",
                value: "\u0430"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "append",
                value: "\u043E\u0432\u0456"
              }
            },
            {
              "0": {
                action: "append",
                value: "\u0443"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "append",
                value: "\u0435"
              }
            }
          ]
        }
      },
      {
        description: "\u043F\u0435\u0440\u0448\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439, \u0436\u0456\u043D\u043E\u0447\u0438\u0439 \u0440\u043E\u0434\u0438 / \u0442\u0432\u0435\u0440\u0434\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0430",
        examples: [
          "\u0430\u043D\u043D\u0430"
        ],
        wordClass: "noun",
        gender: [
          "masculine",
          "feminine"
        ],
        priority: 1,
        applicationType: [],
        pattern: {
          find: "\u0430$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u0438"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u0443"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u043E\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u043E"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u0439",
        examples: [
          "\u0432\u0430\u043B\u0435\u0440\u0456\u0439"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 1,
        applicationType: [],
        pattern: {
          find: "\u0439$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u0454\u0432\u0456"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0454\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0454\u0432\u0456"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            },
            {
              "0": {
                action: "replace",
                value: "\u0457"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0434\u0440\u0443\u0433\u0430 \u0432\u0456\u0434\u043C\u0456\u043D\u0430 / \u0447\u043E\u043B\u043E\u0432\u0456\u0447\u0438\u0439 \u0440\u0456\u0434 / \u043C'\u044F\u043A\u0430 \u0433\u0440\u0443\u043F\u0430 / \u043D\u0430 -\u044C",
        examples: [
          "\u043F\u0435\u0442\u0440\u0443\u043D\u044C"
        ],
        wordClass: "noun",
        gender: [
          "masculine"
        ],
        priority: 1,
        applicationType: [],
        pattern: {
          find: "\u044C$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044F"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0435\u043C"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0435\u0432\u0456"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ]
        }
      },
      {
        description: "\u0436\u0456\u043D\u043E\u0447\u0456 \u0456\u043C\u0435\u043D\u0430 / \u043D\u0430 -'\u044F",
        examples: [
          "\u0434\u0430\u0440'\u044F",
          "\u043C\u0430\u0440'\u044F"
        ],
        wordClass: "noun",
        gender: [
          "feminine"
        ],
        priority: 1,
        applicationType: [
          "givenName"
        ],
        pattern: {
          find: "['\u2019\u02BC]\u044F$",
          modify: "(.{1})$"
        },
        grammaticalCases: {
          nominative: [],
          genitive: [
            {
              "0": {
                action: "replace",
                value: "\u0457"
              }
            }
          ],
          dative: [
            {
              "0": {
                action: "replace",
                value: "\u0457"
              }
            }
          ],
          accusative: [
            {
              "0": {
                action: "replace",
                value: "\u044E"
              }
            }
          ],
          ablative: [
            {
              "0": {
                action: "replace",
                value: "\u0454\u044E"
              }
            }
          ],
          locative: [
            {
              "0": {
                action: "replace",
                value: "\u0457"
              }
            }
          ],
          vocative: [
            {
              "0": {
                action: "replace",
                value: "\u0454"
              }
            }
          ]
        }
      }
    ];
    exports2.default = declensionRules;
  }
});

// node_modules/shevchenko/dist/cjs/language/alphabet.js
var require_alphabet = __commonJS({
  "node_modules/shevchenko/dist/cjs/language/alphabet.js"(exports2) {
    "use strict";
    exports2.AlphabetEncoding = void 0;
    (function(AlphabetEncoding) {
      AlphabetEncoding[AlphabetEncoding["\u0430"] = 1] = "\u0430";
      AlphabetEncoding[AlphabetEncoding["\u0431"] = 2] = "\u0431";
      AlphabetEncoding[AlphabetEncoding["\u0432"] = 3] = "\u0432";
      AlphabetEncoding[AlphabetEncoding["\u0433"] = 4] = "\u0433";
      AlphabetEncoding[AlphabetEncoding["\u0491"] = 5] = "\u0491";
      AlphabetEncoding[AlphabetEncoding["\u0434"] = 6] = "\u0434";
      AlphabetEncoding[AlphabetEncoding["\u0435"] = 7] = "\u0435";
      AlphabetEncoding[AlphabetEncoding["\u0454"] = 8] = "\u0454";
      AlphabetEncoding[AlphabetEncoding["\u0436"] = 9] = "\u0436";
      AlphabetEncoding[AlphabetEncoding["\u0437"] = 10] = "\u0437";
      AlphabetEncoding[AlphabetEncoding["\u0438"] = 11] = "\u0438";
      AlphabetEncoding[AlphabetEncoding["\u0456"] = 12] = "\u0456";
      AlphabetEncoding[AlphabetEncoding["\u0457"] = 13] = "\u0457";
      AlphabetEncoding[AlphabetEncoding["\u0439"] = 14] = "\u0439";
      AlphabetEncoding[AlphabetEncoding["\u043A"] = 15] = "\u043A";
      AlphabetEncoding[AlphabetEncoding["\u043B"] = 16] = "\u043B";
      AlphabetEncoding[AlphabetEncoding["\u043C"] = 17] = "\u043C";
      AlphabetEncoding[AlphabetEncoding["\u043D"] = 18] = "\u043D";
      AlphabetEncoding[AlphabetEncoding["\u043E"] = 19] = "\u043E";
      AlphabetEncoding[AlphabetEncoding["\u043F"] = 20] = "\u043F";
      AlphabetEncoding[AlphabetEncoding["\u0440"] = 21] = "\u0440";
      AlphabetEncoding[AlphabetEncoding["\u0441"] = 22] = "\u0441";
      AlphabetEncoding[AlphabetEncoding["\u0442"] = 23] = "\u0442";
      AlphabetEncoding[AlphabetEncoding["\u0443"] = 24] = "\u0443";
      AlphabetEncoding[AlphabetEncoding["\u0444"] = 25] = "\u0444";
      AlphabetEncoding[AlphabetEncoding["\u0445"] = 26] = "\u0445";
      AlphabetEncoding[AlphabetEncoding["\u0446"] = 27] = "\u0446";
      AlphabetEncoding[AlphabetEncoding["\u0447"] = 28] = "\u0447";
      AlphabetEncoding[AlphabetEncoding["\u0448"] = 29] = "\u0448";
      AlphabetEncoding[AlphabetEncoding["\u0449"] = 30] = "\u0449";
      AlphabetEncoding[AlphabetEncoding["\u044C"] = 31] = "\u044C";
      AlphabetEncoding[AlphabetEncoding["\u044E"] = 32] = "\u044E";
      AlphabetEncoding[AlphabetEncoding["\u044F"] = 33] = "\u044F";
    })(exports2.AlphabetEncoding || (exports2.AlphabetEncoding = {}));
    Object.keys(exports2.AlphabetEncoding).length / 2;
  }
});

// node_modules/shevchenko/dist/cjs/language/word-class.js
var require_word_class = __commonJS({
  "node_modules/shevchenko/dist/cjs/language/word-class.js"(exports2) {
    "use strict";
    exports2.WordClass = void 0;
    (function(WordClass) {
      WordClass["NOUN"] = "noun";
      WordClass["ADJECTIVE"] = "adjective";
    })(exports2.WordClass || (exports2.WordClass = {}));
  }
});

// node_modules/shevchenko/dist/cjs/language/grammatical-case.js
var require_grammatical_case = __commonJS({
  "node_modules/shevchenko/dist/cjs/language/grammatical-case.js"(exports2) {
    "use strict";
    exports2.GrammaticalCase = void 0;
    (function(GrammaticalCase) {
      GrammaticalCase["NOMINATIVE"] = "nominative";
      GrammaticalCase["GENITIVE"] = "genitive";
      GrammaticalCase["DATIVE"] = "dative";
      GrammaticalCase["ACCUSATIVE"] = "accusative";
      GrammaticalCase["ABLATIVE"] = "ablative";
      GrammaticalCase["LOCATIVE"] = "locative";
      GrammaticalCase["VOCATIVE"] = "vocative";
    })(exports2.GrammaticalCase || (exports2.GrammaticalCase = {}));
  }
});

// node_modules/shevchenko/dist/cjs/language/grammatical-gender.js
var require_grammatical_gender = __commonJS({
  "node_modules/shevchenko/dist/cjs/language/grammatical-gender.js"(exports2) {
    "use strict";
    exports2.GrammaticalGender = void 0;
    (function(GrammaticalGender) {
      GrammaticalGender["MASCULINE"] = "masculine";
      GrammaticalGender["FEMININE"] = "feminine";
    })(exports2.GrammaticalGender || (exports2.GrammaticalGender = {}));
  }
});

// node_modules/shevchenko/dist/cjs/language/letter-case.js
var require_letter_case = __commonJS({
  "node_modules/shevchenko/dist/cjs/language/letter-case.js"(exports2) {
    "use strict";
    function copyLetterCase(templateWord, targetWord) {
      let resultWord = "";
      for (let index = 0; index < targetWord.length; index += 1) {
        const templateLetter = templateWord[index] || templateWord[templateWord.length - 1];
        const targetLetter = targetWord[index];
        if (inLowerCase(templateLetter)) {
          resultWord += targetLetter.toLowerCase();
        } else if (inUpperCase(templateLetter)) {
          resultWord += targetLetter.toUpperCase();
        } else {
          resultWord += targetLetter;
        }
      }
      return resultWord;
    }
    function inUpperCase(word, index = 0) {
      const letter = word.charAt(index);
      return letter === letter.toUpperCase();
    }
    function inLowerCase(word, index = 0) {
      const letter = word.charAt(index);
      return letter === letter.toLowerCase();
    }
    exports2.copyLetterCase = copyLetterCase;
  }
});

// node_modules/shevchenko/dist/cjs/word-declension/append-command-runner.js
var require_append_command_runner = __commonJS({
  "node_modules/shevchenko/dist/cjs/word-declension/append-command-runner.js"(exports2) {
    "use strict";
    var AppendCommandRunner = class {
      constructor(command) {
        this.command = command;
      }
      /**
       * Appends the command value to the given value.
       * Returns a new value.
       */
      exec(value) {
        return value + this.command.value;
      }
    };
    exports2.AppendCommandRunner = AppendCommandRunner;
  }
});

// node_modules/shevchenko/dist/cjs/word-declension/declension-types.js
var require_declension_types = __commonJS({
  "node_modules/shevchenko/dist/cjs/word-declension/declension-types.js"(exports2) {
    "use strict";
    require_alphabet();
    require_word_class();
    require_grammatical_case();
    require_grammatical_gender();
    exports2.InflectionCommandAction = void 0;
    (function(InflectionCommandAction) {
      InflectionCommandAction["REPLACE"] = "replace";
      InflectionCommandAction["APPEND"] = "append";
    })(exports2.InflectionCommandAction || (exports2.InflectionCommandAction = {}));
  }
});

// node_modules/shevchenko/dist/cjs/word-declension/replace-command-runner.js
var require_replace_command_runner = __commonJS({
  "node_modules/shevchenko/dist/cjs/word-declension/replace-command-runner.js"(exports2) {
    "use strict";
    var ReplaceCommandRunner = class {
      constructor(command) {
        this.command = command;
      }
      /**
       * Replaces the given value with the command value.
       * Returns a new value.
       */
      exec() {
        return this.command.value;
      }
    };
    exports2.ReplaceCommandRunner = ReplaceCommandRunner;
  }
});

// node_modules/shevchenko/dist/cjs/word-declension/command-runner-factory.js
var require_command_runner_factory = __commonJS({
  "node_modules/shevchenko/dist/cjs/word-declension/command-runner-factory.js"(exports2) {
    "use strict";
    var appendCommandRunner = require_append_command_runner();
    var declensionTypes = require_declension_types();
    var replaceCommandRunner = require_replace_command_runner();
    var CommandRunnerFactory = class {
      /**
       * Creates a new command runner for the given command.
       */
      make(command) {
        switch (command.action) {
          case declensionTypes.InflectionCommandAction.APPEND: {
            return new appendCommandRunner.AppendCommandRunner(command);
          }
          case declensionTypes.InflectionCommandAction.REPLACE: {
            return new replaceCommandRunner.ReplaceCommandRunner(command);
          }
          default: {
            throw new TypeError(`Invalid command action: ${command.action}.`);
          }
        }
      }
    };
    exports2.CommandRunnerFactory = CommandRunnerFactory;
  }
});

// node_modules/shevchenko/dist/cjs/word-declension/declension-rule-inflector.js
var require_declension_rule_inflector = __commonJS({
  "node_modules/shevchenko/dist/cjs/word-declension/declension-rule-inflector.js"(exports2) {
    "use strict";
    require_alphabet();
    require_word_class();
    require_grammatical_case();
    require_grammatical_gender();
    var letterCase = require_letter_case();
    var commandRunnerFactory = require_command_runner_factory();
    function countGroups(src) {
      const pattern = new RegExp(`${src.toString()}|`);
      const matches = pattern.exec("");
      if (matches == null) {
        return 0;
      }
      return matches.length - 1;
    }
    var DeclensionRuleInflector = class {
      constructor(rule) {
        this.rule = rule;
        this.commandRunnerFactory = new commandRunnerFactory.CommandRunnerFactory();
      }
      /**
       * Inflects the given word in the given grammatical case using the rule.
       */
      inflect(word, grammaticalCase) {
        const [commands] = this.rule.grammaticalCases[grammaticalCase];
        if (commands) {
          const searchValue = new RegExp(this.rule.pattern.modify, "gi");
          const inflectedWord = word.replace(searchValue, (match, ...groups) => {
            let replacer = "";
            const groupCount = countGroups(this.rule.pattern.modify);
            for (let groupIndex = 0; groupIndex < groupCount; groupIndex += 1) {
              let value = groups[groupIndex];
              const command = commands[groupIndex];
              if (command != null) {
                value = this.commandRunnerFactory.make(command).exec(value);
              }
              replacer += value;
            }
            return replacer;
          });
          return letterCase.copyLetterCase(word, inflectedWord);
        }
        return word;
      }
    };
    exports2.DeclensionRuleInflector = DeclensionRuleInflector;
    exports2.countGroups = countGroups;
  }
});

// node_modules/shevchenko/dist/cjs/word-declension/word-inflector.js
var require_word_inflector = __commonJS({
  "node_modules/shevchenko/dist/cjs/word-declension/word-inflector.js"(exports2) {
    "use strict";
    var declensionRuleInflector = require_declension_rule_inflector();
    var WordInflector = class {
      constructor(declensionRules) {
        this.declensionRules = [...declensionRules].sort((firstRule, lastRule) => lastRule.priority - firstRule.priority);
      }
      async inflect(word, params) {
        const [matchingRule] = await this.findMatchingRules(word, params);
        if (matchingRule == null) {
          return word;
        }
        return new declensionRuleInflector.DeclensionRuleInflector(matchingRule).inflect(word, params.grammaticalCase);
      }
      /**
       * Finds matching declension rules for the given word.
       */
      async findMatchingRules(word, params) {
        const matchingRules = this.declensionRules.filter((declensionRule) => {
          return declensionRule.gender.includes(params.gender);
        }).filter((declensionRule) => {
          return !params.applicationType || declensionRule.applicationType.length === 0 || declensionRule.applicationType.includes(params.applicationType);
        }).filter((declensionRule) => {
          return new RegExp(declensionRule.pattern.find, "gi").test(word);
        }).filter((declensionRule) => {
          return !params.wordClass || declensionRule.wordClass === params.wordClass;
        }).filter((declensionRule, index, declensionRules) => {
          return !params.customRuleFilter || params.customRuleFilter(declensionRule, index, declensionRules);
        });
        return matchingRules;
      }
    };
    exports2.WordInflector = WordInflector;
  }
});

// node_modules/shevchenko/dist/cjs/word-declension/bootstrap.js
var require_bootstrap = __commonJS({
  "node_modules/shevchenko/dist/cjs/word-declension/bootstrap.js"(exports2) {
    "use strict";
    var declensionRules = require_declension_rules_json();
    var wordInflector$1 = require_word_inflector();
    var wordInflector = new wordInflector$1.WordInflector(declensionRules.default);
    exports2.wordInflector = wordInflector;
  }
});

// node_modules/shevchenko/dist/cjs/anthroponym-declension/anthroponym-inflector.js
var require_anthroponym_inflector = __commonJS({
  "node_modules/shevchenko/dist/cjs/anthroponym-declension/anthroponym-inflector.js"(exports2) {
    "use strict";
    var AnthroponymInflector = class {
      constructor(givenNameInflector, patronymicNameInflector, familyNameInflector) {
        this.givenNameInflector = givenNameInflector;
        this.patronymicNameInflector = patronymicNameInflector;
        this.familyNameInflector = familyNameInflector;
      }
      /**
       * Inflects the anthroponym in the given grammatical case.
       */
      async inflect(anthroponym, gender, grammaticalCase) {
        const inflectedAnthroponym = {};
        if (anthroponym.givenName != null) {
          inflectedAnthroponym.givenName = await this.givenNameInflector.inflect(anthroponym.givenName, gender, grammaticalCase);
        }
        if (anthroponym.patronymicName != null) {
          inflectedAnthroponym.patronymicName = await this.patronymicNameInflector.inflect(anthroponym.patronymicName, gender, grammaticalCase);
        }
        if (anthroponym.familyName != null) {
          inflectedAnthroponym.familyName = await this.familyNameInflector.inflect(anthroponym.familyName, gender, grammaticalCase);
        }
        return inflectedAnthroponym;
      }
    };
    exports2.AnthroponymInflector = AnthroponymInflector;
  }
});

// node_modules/webidl-conversions/lib/index.js
var require_lib = __commonJS({
  "node_modules/webidl-conversions/lib/index.js"(exports2, module2) {
    "use strict";
    var conversions = {};
    module2.exports = conversions;
    function sign(x) {
      return x < 0 ? -1 : 1;
    }
    function evenRound(x) {
      if (x % 1 === 0.5 && (x & 1) === 0) {
        return Math.floor(x);
      } else {
        return Math.round(x);
      }
    }
    function createNumberConversion(bitLength, typeOpts) {
      if (!typeOpts.unsigned) {
        --bitLength;
      }
      const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength);
      const upperBound = Math.pow(2, bitLength) - 1;
      const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength);
      const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1);
      return function(V, opts) {
        if (!opts) opts = {};
        let x = +V;
        if (opts.enforceRange) {
          if (!Number.isFinite(x)) {
            throw new TypeError("Argument is not a finite number");
          }
          x = sign(x) * Math.floor(Math.abs(x));
          if (x < lowerBound || x > upperBound) {
            throw new TypeError("Argument is not in byte range");
          }
          return x;
        }
        if (!isNaN(x) && opts.clamp) {
          x = evenRound(x);
          if (x < lowerBound) x = lowerBound;
          if (x > upperBound) x = upperBound;
          return x;
        }
        if (!Number.isFinite(x) || x === 0) {
          return 0;
        }
        x = sign(x) * Math.floor(Math.abs(x));
        x = x % moduloVal;
        if (!typeOpts.unsigned && x >= moduloBound) {
          return x - moduloVal;
        } else if (typeOpts.unsigned) {
          if (x < 0) {
            x += moduloVal;
          } else if (x === -0) {
            return 0;
          }
        }
        return x;
      };
    }
    conversions["void"] = function() {
      return void 0;
    };
    conversions["boolean"] = function(val) {
      return !!val;
    };
    conversions["byte"] = createNumberConversion(8, { unsigned: false });
    conversions["octet"] = createNumberConversion(8, { unsigned: true });
    conversions["short"] = createNumberConversion(16, { unsigned: false });
    conversions["unsigned short"] = createNumberConversion(16, { unsigned: true });
    conversions["long"] = createNumberConversion(32, { unsigned: false });
    conversions["unsigned long"] = createNumberConversion(32, { unsigned: true });
    conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 });
    conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 });
    conversions["double"] = function(V) {
      const x = +V;
      if (!Number.isFinite(x)) {
        throw new TypeError("Argument is not a finite floating-point value");
      }
      return x;
    };
    conversions["unrestricted double"] = function(V) {
      const x = +V;
      if (isNaN(x)) {
        throw new TypeError("Argument is NaN");
      }
      return x;
    };
    conversions["float"] = conversions["double"];
    conversions["unrestricted float"] = conversions["unrestricted double"];
    conversions["DOMString"] = function(V, opts) {
      if (!opts) opts = {};
      if (opts.treatNullAsEmptyString && V === null) {
        return "";
      }
      return String(V);
    };
    conversions["ByteString"] = function(V, opts) {
      const x = String(V);
      let c = void 0;
      for (let i = 0; (c = x.codePointAt(i)) !== void 0; ++i) {
        if (c > 255) {
          throw new TypeError("Argument is not a valid bytestring");
        }
      }
      return x;
    };
    conversions["USVString"] = function(V) {
      const S = String(V);
      const n = S.length;
      const U = [];
      for (let i = 0; i < n; ++i) {
        const c = S.charCodeAt(i);
        if (c < 55296 || c > 57343) {
          U.push(String.fromCodePoint(c));
        } else if (56320 <= c && c <= 57343) {
          U.push(String.fromCodePoint(65533));
        } else {
          if (i === n - 1) {
            U.push(String.fromCodePoint(65533));
          } else {
            const d = S.charCodeAt(i + 1);
            if (56320 <= d && d <= 57343) {
              const a = c & 1023;
              const b = d & 1023;
              U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b));
              ++i;
            } else {
              U.push(String.fromCodePoint(65533));
            }
          }
        }
      }
      return U.join("");
    };
    conversions["Date"] = function(V, opts) {
      if (!(V instanceof Date)) {
        throw new TypeError("Argument is not a Date object");
      }
      if (isNaN(V)) {
        return void 0;
      }
      return V;
    };
    conversions["RegExp"] = function(V, opts) {
      if (!(V instanceof RegExp)) {
        V = new RegExp(V);
      }
      return V;
    };
  }
});

// node_modules/whatwg-url/lib/utils.js
var require_utils = __commonJS({
  "node_modules/whatwg-url/lib/utils.js"(exports2, module2) {
    "use strict";
    module2.exports.mixin = function mixin(target, source) {
      const keys = Object.getOwnPropertyNames(source);
      for (let i = 0; i < keys.length; ++i) {
        Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i]));
      }
    };
    module2.exports.wrapperSymbol = Symbol("wrapper");
    module2.exports.implSymbol = Symbol("impl");
    module2.exports.wrapperForImpl = function(impl) {
      return impl[module2.exports.wrapperSymbol];
    };
    module2.exports.implForWrapper = function(wrapper) {
      return wrapper[module2.exports.implSymbol];
    };
  }
});

// node_modules/tr46/lib/mappingTable.json
var require_mappingTable = __commonJS({
  "node_modules/tr46/lib/mappingTable.json"(exports2, module2) {
    module2.exports = [[[0, 44], "disallowed_STD3_valid"], [[45, 46], "valid"], [[47, 47], "disallowed_STD3_valid"], [[48, 57], "valid"], [[58, 64], "disallowed_STD3_valid"], [[65, 65], "mapped", [97]], [[66, 66], "mapped", [98]], [[67, 67], "mapped", [99]], [[68, 68], "mapped", [100]], [[69, 69], "mapped", [101]], [[70, 70], "mapped", [102]], [[71, 71], "mapped", [103]], [[72, 72], "mapped", [104]], [[73, 73], "mapped", [105]], [[74, 74], "mapped", [106]], [[75, 75], "mapped", [107]], [[76, 76], "mapped", [108]], [[77, 77], "mapped", [109]], [[78, 78], "mapped", [110]], [[79, 79], "mapped", [111]], [[80, 80], "mapped", [112]], [[81, 81], "mapped", [113]], [[82, 82], "mapped", [114]], [[83, 83], "mapped", [115]], [[84, 84], "mapped", [116]], [[85, 85], "mapped", [117]], [[86, 86], "mapped", [118]], [[87, 87], "mapped", [119]], [[88, 88], "mapped", [120]], [[89, 89], "mapped", [121]], [[90, 90], "mapped", [122]], [[91, 96], "disallowed_STD3_valid"], [[97, 122], "valid"], [[123, 127], "disallowed_STD3_valid"], [[128, 159], "disallowed"], [[160, 160], "disallowed_STD3_mapped", [32]], [[161, 167], "valid", [], "NV8"], [[168, 168], "disallowed_STD3_mapped", [32, 776]], [[169, 169], "valid", [], "NV8"], [[170, 170], "mapped", [97]], [[171, 172], "valid", [], "NV8"], [[173, 173], "ignored"], [[174, 174], "valid", [], "NV8"], [[175, 175], "disallowed_STD3_mapped", [32, 772]], [[176, 177], "valid", [], "NV8"], [[178, 178], "mapped", [50]], [[179, 179], "mapped", [51]], [[180, 180], "disallowed_STD3_mapped", [32, 769]], [[181, 181], "mapped", [956]], [[182, 182], "valid", [], "NV8"], [[183, 183], "valid"], [[184, 184], "disallowed_STD3_mapped", [32, 807]], [[185, 185], "mapped", [49]], [[186, 186], "mapped", [111]], [[187, 187], "valid", [], "NV8"], [[188, 188], "mapped", [49, 8260, 52]], [[189, 189], "mapped", [49, 8260, 50]], [[190, 190], "mapped", [51, 8260, 52]], [[191, 191], "valid", [], "NV8"], [[192, 192], "mapped", [224]], [[193, 193], "mapped", [225]], [[194, 194], "mapped", [226]], [[195, 195], "mapped", [227]], [[196, 196], "mapped", [228]], [[197, 197], "mapped", [229]], [[198, 198], "mapped", [230]], [[199, 199], "mapped", [231]], [[200, 200], "mapped", [232]], [[201, 201], "mapped", [233]], [[202, 202], "mapped", [234]], [[203, 203], "mapped", [235]], [[204, 204], "mapped", [236]], [[205, 205], "mapped", [237]], [[206, 206], "mapped", [238]], [[207, 207], "mapped", [239]], [[208, 208], "mapped", [240]], [[209, 209], "mapped", [241]], [[210, 210], "mapped", [242]], [[211, 211], "mapped", [243]], [[212, 212], "mapped", [244]], [[213, 213], "mapped", [245]], [[214, 214], "mapped", [246]], [[215, 215], "valid", [], "NV8"], [[216, 216], "mapped", [248]], [[217, 217], "mapped", [249]], [[218, 218], "mapped", [250]], [[219, 219], "mapped", [251]], [[220, 220], "mapped", [252]], [[221, 221], "mapped", [253]], [[222, 222], "mapped", [254]], [[223, 223], "deviation", [115, 115]], [[224, 246], "valid"], [[247, 247], "valid", [], "NV8"], [[248, 255], "valid"], [[256, 256], "mapped", [257]], [[257, 257], "valid"], [[258, 258], "mapped", [259]], [[259, 259], "valid"], [[260, 260], "mapped", [261]], [[261, 261], "valid"], [[262, 262], "mapped", [263]], [[263, 263], "valid"], [[264, 264], "mapped", [265]], [[265, 265], "valid"], [[266, 266], "mapped", [267]], [[267, 267], "valid"], [[268, 268], "mapped", [269]], [[269, 269], "valid"], [[270, 270], "mapped", [271]], [[271, 271], "valid"], [[272, 272], "mapped", [273]], [[273, 273], "valid"], [[274, 274], "mapped", [275]], [[275, 275], "valid"], [[276, 276], "mapped", [277]], [[277, 277], "valid"], [[278, 278], "mapped", [279]], [[279, 279], "valid"], [[280, 280], "mapped", [281]], [[281, 281], "valid"], [[282, 282], "mapped", [283]], [[283, 283], "valid"], [[284, 284], "mapped", [285]], [[285, 285], "valid"], [[286, 286], "mapped", [287]], [[287, 287], "valid"], [[288, 288], "mapped", [289]], [[289, 289], "valid"], [[290, 290], "mapped", [291]], [[291, 291], "valid"], [[292, 292], "mapped", [293]], [[293, 293], "valid"], [[294, 294], "mapped", [295]], [[295, 295], "valid"], [[296, 296], "mapped", [297]], [[297, 297], "valid"], [[298, 298], "mapped", [299]], [[299, 299], "valid"], [[300, 300], "mapped", [301]], [[301, 301], "valid"], [[302, 302], "mapped", [303]], [[303, 303], "valid"], [[304, 304], "mapped", [105, 775]], [[305, 305], "valid"], [[306, 307], "mapped", [105, 106]], [[308, 308], "mapped", [309]], [[309, 309], "valid"], [[310, 310], "mapped", [311]], [[311, 312], "valid"], [[313, 313], "mapped", [314]], [[314, 314], "valid"], [[315, 315], "mapped", [316]], [[316, 316], "valid"], [[317, 317], "mapped", [318]], [[318, 318], "valid"], [[319, 320], "mapped", [108, 183]], [[321, 321], "mapped", [322]], [[322, 322], "valid"], [[323, 323], "mapped", [324]], [[324, 324], "valid"], [[325, 325], "mapped", [326]], [[326, 326], "valid"], [[327, 327], "mapped", [328]], [[328, 328], "valid"], [[329, 329], "mapped", [700, 110]], [[330, 330], "mapped", [331]], [[331, 331], "valid"], [[332, 332], "mapped", [333]], [[333, 333], "valid"], [[334, 334], "mapped", [335]], [[335, 335], "valid"], [[336, 336], "mapped", [337]], [[337, 337], "valid"], [[338, 338], "mapped", [339]], [[339, 339], "valid"], [[340, 340], "mapped", [341]], [[341, 341], "valid"], [[342, 342], "mapped", [343]], [[343, 343], "valid"], [[344, 344], "mapped", [345]], [[345, 345], "valid"], [[346, 346], "mapped", [347]], [[347, 347], "valid"], [[348, 348], "mapped", [349]], [[349, 349], "valid"], [[350, 350], "mapped", [351]], [[351, 351], "valid"], [[352, 352], "mapped", [353]], [[353, 353], "valid"], [[354, 354], "mapped", [355]], [[355, 355], "valid"], [[356, 356], "mapped", [357]], [[357, 357], "valid"], [[358, 358], "mapped", [359]], [[359, 359], "valid"], [[360, 360], "mapped", [361]], [[361, 361], "valid"], [[362, 362], "mapped", [363]], [[363, 363], "valid"], [[364, 364], "mapped", [365]], [[365, 365], "valid"], [[366, 366], "mapped", [367]], [[367, 367], "valid"], [[368, 368], "mapped", [369]], [[369, 369], "valid"], [[370, 370], "mapped", [371]], [[371, 371], "valid"], [[372, 372], "mapped", [373]], [[373, 373], "valid"], [[374, 374], "mapped", [375]], [[375, 375], "valid"], [[376, 376], "mapped", [255]], [[377, 377], "mapped", [378]], [[378, 378], "valid"], [[379, 379], "mapped", [380]], [[380, 380], "valid"], [[381, 381], "mapped", [382]], [[382, 382], "valid"], [[383, 383], "mapped", [115]], [[384, 384], "valid"], [[385, 385], "mapped", [595]], [[386, 386], "mapped", [387]], [[387, 387], "valid"], [[388, 388], "mapped", [389]], [[389, 389], "valid"], [[390, 390], "mapped", [596]], [[391, 391], "mapped", [392]], [[392, 392], "valid"], [[393, 393], "mapped", [598]], [[394, 394], "mapped", [599]], [[395, 395], "mapped", [396]], [[396, 397], "valid"], [[398, 398], "mapped", [477]], [[399, 399], "mapped", [601]], [[400, 400], "mapped", [603]], [[401, 401], "mapped", [402]], [[402, 402], "valid"], [[403, 403], "mapped", [608]], [[404, 404], "mapped", [611]], [[405, 405], "valid"], [[406, 406], "mapped", [617]], [[407, 407], "mapped", [616]], [[408, 408], "mapped", [409]], [[409, 411], "valid"], [[412, 412], "mapped", [623]], [[413, 413], "mapped", [626]], [[414, 414], "valid"], [[415, 415], "mapped", [629]], [[416, 416], "mapped", [417]], [[417, 417], "valid"], [[418, 418], "mapped", [419]], [[419, 419], "valid"], [[420, 420], "mapped", [421]], [[421, 421], "valid"], [[422, 422], "mapped", [640]], [[423, 423], "mapped", [424]], [[424, 424], "valid"], [[425, 425], "mapped", [643]], [[426, 427], "valid"], [[428, 428], "mapped", [429]], [[429, 429], "valid"], [[430, 430], "mapped", [648]], [[431, 431], "mapped", [432]], [[432, 432], "valid"], [[433, 433], "mapped", [650]], [[434, 434], "mapped", [651]], [[435, 435], "mapped", [436]], [[436, 436], "valid"], [[437, 437], "mapped", [438]], [[438, 438], "valid"], [[439, 439], "mapped", [658]], [[440, 440], "mapped", [441]], [[441, 443], "valid"], [[444, 444], "mapped", [445]], [[445, 451], "valid"], [[452, 454], "mapped", [100, 382]], [[455, 457], "mapped", [108, 106]], [[458, 460], "mapped", [110, 106]], [[461, 461], "mapped", [462]], [[462, 462], "valid"], [[463, 463], "mapped", [464]], [[464, 464], "valid"], [[465, 465], "mapped", [466]], [[466, 466], "valid"], [[467, 467], "mapped", [468]], [[468, 468], "valid"], [[469, 469], "mapped", [470]], [[470, 470], "valid"], [[471, 471], "mapped", [472]], [[472, 472], "valid"], [[473, 473], "mapped", [474]], [[474, 474], "valid"], [[475, 475], "mapped", [476]], [[476, 477], "valid"], [[478, 478], "mapped", [479]], [[479, 479], "valid"], [[480, 480], "mapped", [481]], [[481, 481], "valid"], [[482, 482], "mapped", [483]], [[483, 483], "valid"], [[484, 484], "mapped", [485]], [[485, 485], "valid"], [[486, 486], "mapped", [487]], [[487, 487], "valid"], [[488, 488], "mapped", [489]], [[489, 489], "valid"], [[490, 490], "mapped", [491]], [[491, 491], "valid"], [[492, 492], "mapped", [493]], [[493, 493], "valid"], [[494, 494], "mapped", [495]], [[495, 496], "valid"], [[497, 499], "mapped", [100, 122]], [[500, 500], "mapped", [501]], [[501, 501], "valid"], [[502, 502], "mapped", [405]], [[503, 503], "mapped", [447]], [[504, 504], "mapped", [505]], [[505, 505], "valid"], [[506, 506], "mapped", [507]], [[507, 507], "valid"], [[508, 508], "mapped", [509]], [[509, 509], "valid"], [[510, 510], "mapped", [511]], [[511, 511], "valid"], [[512, 512], "mapped", [513]], [[513, 513], "valid"], [[514, 514], "mapped", [515]], [[515, 515], "valid"], [[516, 516], "mapped", [517]], [[517, 517], "valid"], [[518, 518], "mapped", [519]], [[519, 519], "valid"], [[520, 520], "mapped", [521]], [[521, 521], "valid"], [[522, 522], "mapped", [523]], [[523, 523], "valid"], [[524, 524], "mapped", [525]], [[525, 525], "valid"], [[526, 526], "mapped", [527]], [[527, 527], "valid"], [[528, 528], "mapped", [529]], [[529, 529], "valid"], [[530, 530], "mapped", [531]], [[531, 531], "valid"], [[532, 532], "mapped", [533]], [[533, 533], "valid"], [[534, 534], "mapped", [535]], [[535, 535], "valid"], [[536, 536], "mapped", [537]], [[537, 537], "valid"], [[538, 538], "mapped", [539]], [[539, 539], "valid"], [[540, 540], "mapped", [541]], [[541, 541], "valid"], [[542, 542], "mapped", [543]], [[543, 543], "valid"], [[544, 544], "mapped", [414]], [[545, 545], "valid"], [[546, 546], "mapped", [547]], [[547, 547], "valid"], [[548, 548], "mapped", [549]], [[549, 549], "valid"], [[550, 550], "mapped", [551]], [[551, 551], "valid"], [[552, 552], "mapped", [553]], [[553, 553], "valid"], [[554, 554], "mapped", [555]], [[555, 555], "valid"], [[556, 556], "mapped", [557]], [[557, 557], "valid"], [[558, 558], "mapped", [559]], [[559, 559], "valid"], [[560, 560], "mapped", [561]], [[561, 561], "valid"], [[562, 562], "mapped", [563]], [[563, 563], "valid"], [[564, 566], "valid"], [[567, 569], "valid"], [[570, 570], "mapped", [11365]], [[571, 571], "mapped", [572]], [[572, 572], "valid"], [[573, 573], "mapped", [410]], [[574, 574], "mapped", [11366]], [[575, 576], "valid"], [[577, 577], "mapped", [578]], [[578, 578], "valid"], [[579, 579], "mapped", [384]], [[580, 580], "mapped", [649]], [[581, 581], "mapped", [652]], [[582, 582], "mapped", [583]], [[583, 583], "valid"], [[584, 584], "mapped", [585]], [[585, 585], "valid"], [[586, 586], "mapped", [587]], [[587, 587], "valid"], [[588, 588], "mapped", [589]], [[589, 589], "valid"], [[590, 590], "mapped", [591]], [[591, 591], "valid"], [[592, 680], "valid"], [[681, 685], "valid"], [[686, 687], "valid"], [[688, 688], "mapped", [104]], [[689, 689], "mapped", [614]], [[690, 690], "mapped", [106]], [[691, 691], "mapped", [114]], [[692, 692], "mapped", [633]], [[693, 693], "mapped", [635]], [[694, 694], "mapped", [641]], [[695, 695], "mapped", [119]], [[696, 696], "mapped", [121]], [[697, 705], "valid"], [[706, 709], "valid", [], "NV8"], [[710, 721], "valid"], [[722, 727], "valid", [], "NV8"], [[728, 728], "disallowed_STD3_mapped", [32, 774]], [[729, 729], "disallowed_STD3_mapped", [32, 775]], [[730, 730], "disallowed_STD3_mapped", [32, 778]], [[731, 731], "disallowed_STD3_mapped", [32, 808]], [[732, 732], "disallowed_STD3_mapped", [32, 771]], [[733, 733], "disallowed_STD3_mapped", [32, 779]], [[734, 734], "valid", [], "NV8"], [[735, 735], "valid", [], "NV8"], [[736, 736], "mapped", [611]], [[737, 737], "mapped", [108]], [[738, 738], "mapped", [115]], [[739, 739], "mapped", [120]], [[740, 740], "mapped", [661]], [[741, 745], "valid", [], "NV8"], [[746, 747], "valid", [], "NV8"], [[748, 748], "valid"], [[749, 749], "valid", [], "NV8"], [[750, 750], "valid"], [[751, 767], "valid", [], "NV8"], [[768, 831], "valid"], [[832, 832], "mapped", [768]], [[833, 833], "mapped", [769]], [[834, 834], "valid"], [[835, 835], "mapped", [787]], [[836, 836], "mapped", [776, 769]], [[837, 837], "mapped", [953]], [[838, 846], "valid"], [[847, 847], "ignored"], [[848, 855], "valid"], [[856, 860], "valid"], [[861, 863], "valid"], [[864, 865], "valid"], [[866, 866], "valid"], [[867, 879], "valid"], [[880, 880], "mapped", [881]], [[881, 881], "valid"], [[882, 882], "mapped", [883]], [[883, 883], "valid"], [[884, 884], "mapped", [697]], [[885, 885], "valid"], [[886, 886], "mapped", [887]], [[887, 887], "valid"], [[888, 889], "disallowed"], [[890, 890], "disallowed_STD3_mapped", [32, 953]], [[891, 893], "valid"], [[894, 894], "disallowed_STD3_mapped", [59]], [[895, 895], "mapped", [1011]], [[896, 899], "disallowed"], [[900, 900], "disallowed_STD3_mapped", [32, 769]], [[901, 901], "disallowed_STD3_mapped", [32, 776, 769]], [[902, 902], "mapped", [940]], [[903, 903], "mapped", [183]], [[904, 904], "mapped", [941]], [[905, 905], "mapped", [942]], [[906, 906], "mapped", [943]], [[907, 907], "disallowed"], [[908, 908], "mapped", [972]], [[909, 909], "disallowed"], [[910, 910], "mapped", [973]], [[911, 911], "mapped", [974]], [[912, 912], "valid"], [[913, 913], "mapped", [945]], [[914, 914], "mapped", [946]], [[915, 915], "mapped", [947]], [[916, 916], "mapped", [948]], [[917, 917], "mapped", [949]], [[918, 918], "mapped", [950]], [[919, 919], "mapped", [951]], [[920, 920], "mapped", [952]], [[921, 921], "mapped", [953]], [[922, 922], "mapped", [954]], [[923, 923], "mapped", [955]], [[924, 924], "mapped", [956]], [[925, 925], "mapped", [957]], [[926, 926], "mapped", [958]], [[927, 927], "mapped", [959]], [[928, 928], "mapped", [960]], [[929, 929], "mapped", [961]], [[930, 930], "disallowed"], [[931, 931], "mapped", [963]], [[932, 932], "mapped", [964]], [[933, 933], "mapped", [965]], [[934, 934], "mapped", [966]], [[935, 935], "mapped", [967]], [[936, 936], "mapped", [968]], [[937, 937], "mapped", [969]], [[938, 938], "mapped", [970]], [[939, 939], "mapped", [971]], [[940, 961], "valid"], [[962, 962], "deviation", [963]], [[963, 974], "valid"], [[975, 975], "mapped", [983]], [[976, 976], "mapped", [946]], [[977, 977], "mapped", [952]], [[978, 978], "mapped", [965]], [[979, 979], "mapped", [973]], [[980, 980], "mapped", [971]], [[981, 981], "mapped", [966]], [[982, 982], "mapped", [960]], [[983, 983], "valid"], [[984, 984], "mapped", [985]], [[985, 985], "valid"], [[986, 986], "mapped", [987]], [[987, 987], "valid"], [[988, 988], "mapped", [989]], [[989, 989], "valid"], [[990, 990], "mapped", [991]], [[991, 991], "valid"], [[992, 992], "mapped", [993]], [[993, 993], "valid"], [[994, 994], "mapped", [995]], [[995, 995], "valid"], [[996, 996], "mapped", [997]], [[997, 997], "valid"], [[998, 998], "mapped", [999]], [[999, 999], "valid"], [[1e3, 1e3], "mapped", [1001]], [[1001, 1001], "valid"], [[1002, 1002], "mapped", [1003]], [[1003, 1003], "valid"], [[1004, 1004], "mapped", [1005]], [[1005, 1005], "valid"], [[1006, 1006], "mapped", [1007]], [[1007, 1007], "valid"], [[1008, 1008], "mapped", [954]], [[1009, 1009], "mapped", [961]], [[1010, 1010], "mapped", [963]], [[1011, 1011], "valid"], [[1012, 1012], "mapped", [952]], [[1013, 1013], "mapped", [949]], [[1014, 1014], "valid", [], "NV8"], [[1015, 1015], "mapped", [1016]], [[1016, 1016], "valid"], [[1017, 1017], "mapped", [963]], [[1018, 1018], "mapped", [1019]], [[1019, 1019], "valid"], [[1020, 1020], "valid"], [[1021, 1021], "mapped", [891]], [[1022, 1022], "mapped", [892]], [[1023, 1023], "mapped", [893]], [[1024, 1024], "mapped", [1104]], [[1025, 1025], "mapped", [1105]], [[1026, 1026], "mapped", [1106]], [[1027, 1027], "mapped", [1107]], [[1028, 1028], "mapped", [1108]], [[1029, 1029], "mapped", [1109]], [[1030, 1030], "mapped", [1110]], [[1031, 1031], "mapped", [1111]], [[1032, 1032], "mapped", [1112]], [[1033, 1033], "mapped", [1113]], [[1034, 1034], "mapped", [1114]], [[1035, 1035], "mapped", [1115]], [[1036, 1036], "mapped", [1116]], [[1037, 1037], "mapped", [1117]], [[1038, 1038], "mapped", [1118]], [[1039, 1039], "mapped", [1119]], [[1040, 1040], "mapped", [1072]], [[1041, 1041], "mapped", [1073]], [[1042, 1042], "mapped", [1074]], [[1043, 1043], "mapped", [1075]], [[1044, 1044], "mapped", [1076]], [[1045, 1045], "mapped", [1077]], [[1046, 1046], "mapped", [1078]], [[1047, 1047], "mapped", [1079]], [[1048, 1048], "mapped", [1080]], [[1049, 1049], "mapped", [1081]], [[1050, 1050], "mapped", [1082]], [[1051, 1051], "mapped", [1083]], [[1052, 1052], "mapped", [1084]], [[1053, 1053], "mapped", [1085]], [[1054, 1054], "mapped", [1086]], [[1055, 1055], "mapped", [1087]], [[1056, 1056], "mapped", [1088]], [[1057, 1057], "mapped", [1089]], [[1058, 1058], "mapped", [1090]], [[1059, 1059], "mapped", [1091]], [[1060, 1060], "mapped", [1092]], [[1061, 1061], "mapped", [1093]], [[1062, 1062], "mapped", [1094]], [[1063, 1063], "mapped", [1095]], [[1064, 1064], "mapped", [1096]], [[1065, 1065], "mapped", [1097]], [[1066, 1066], "mapped", [1098]], [[1067, 1067], "mapped", [1099]], [[1068, 1068], "mapped", [1100]], [[1069, 1069], "mapped", [1101]], [[1070, 1070], "mapped", [1102]], [[1071, 1071], "mapped", [1103]], [[1072, 1103], "valid"], [[1104, 1104], "valid"], [[1105, 1116], "valid"], [[1117, 1117], "valid"], [[1118, 1119], "valid"], [[1120, 1120], "mapped", [1121]], [[1121, 1121], "valid"], [[1122, 1122], "mapped", [1123]], [[1123, 1123], "valid"], [[1124, 1124], "mapped", [1125]], [[1125, 1125], "valid"], [[1126, 1126], "mapped", [1127]], [[1127, 1127], "valid"], [[1128, 1128], "mapped", [1129]], [[1129, 1129], "valid"], [[1130, 1130], "mapped", [1131]], [[1131, 1131], "valid"], [[1132, 1132], "mapped", [1133]], [[1133, 1133], "valid"], [[1134, 1134], "mapped", [1135]], [[1135, 1135], "valid"], [[1136, 1136], "mapped", [1137]], [[1137, 1137], "valid"], [[1138, 1138], "mapped", [1139]], [[1139, 1139], "valid"], [[1140, 1140], "mapped", [1141]], [[1141, 1141], "valid"], [[1142, 1142], "mapped", [1143]], [[1143, 1143], "valid"], [[1144, 1144], "mapped", [1145]], [[1145, 1145], "valid"], [[1146, 1146], "mapped", [1147]], [[1147, 1147], "valid"], [[1148, 1148], "mapped", [1149]], [[1149, 1149], "valid"], [[1150, 1150], "mapped", [1151]], [[1151, 1151], "valid"], [[1152, 1152], "mapped", [1153]], [[1153, 1153], "valid"], [[1154, 1154], "valid", [], "NV8"], [[1155, 1158], "valid"], [[1159, 1159], "valid"], [[1160, 1161], "valid", [], "NV8"], [[1162, 1162], "mapped", [1163]], [[1163, 1163], "valid"], [[1164, 1164], "mapped", [1165]], [[1165, 1165], "valid"], [[1166, 1166], "mapped", [1167]], [[1167, 1167], "valid"], [[1168, 1168], "mapped", [1169]], [[1169, 1169], "valid"], [[1170, 1170], "mapped", [1171]], [[1171, 1171], "valid"], [[1172, 1172], "mapped", [1173]], [[1173, 1173], "valid"], [[1174, 1174], "mapped", [1175]], [[1175, 1175], "valid"], [[1176, 1176], "mapped", [1177]], [[1177, 1177], "valid"], [[1178, 1178], "mapped", [1179]], [[1179, 1179], "valid"], [[1180, 1180], "mapped", [1181]], [[1181, 1181], "valid"], [[1182, 1182], "mapped", [1183]], [[1183, 1183], "valid"], [[1184, 1184], "mapped", [1185]], [[1185, 1185], "valid"], [[1186, 1186], "mapped", [1187]], [[1187, 1187], "valid"], [[1188, 1188], "mapped", [1189]], [[1189, 1189], "valid"], [[1190, 1190], "mapped", [1191]], [[1191, 1191], "valid"], [[1192, 1192], "mapped", [1193]], [[1193, 1193], "valid"], [[1194, 1194], "mapped", [1195]], [[1195, 1195], "valid"], [[1196, 1196], "mapped", [1197]], [[1197, 1197], "valid"], [[1198, 1198], "mapped", [1199]], [[1199, 1199], "valid"], [[1200, 1200], "mapped", [1201]], [[1201, 1201], "valid"], [[1202, 1202], "mapped", [1203]], [[1203, 1203], "valid"], [[1204, 1204], "mapped", [1205]], [[1205, 1205], "valid"], [[1206, 1206], "mapped", [1207]], [[1207, 1207], "valid"], [[1208, 1208], "mapped", [1209]], [[1209, 1209], "valid"], [[1210, 1210], "mapped", [1211]], [[1211, 1211], "valid"], [[1212, 1212], "mapped", [1213]], [[1213, 1213], "valid"], [[1214, 1214], "mapped", [1215]], [[1215, 1215], "valid"], [[1216, 1216], "disallowed"], [[1217, 1217], "mapped", [1218]], [[1218, 1218], "valid"], [[1219, 1219], "mapped", [1220]], [[1220, 1220], "valid"], [[1221, 1221], "mapped", [1222]], [[1222, 1222], "valid"], [[1223, 1223], "mapped", [1224]], [[1224, 1224], "valid"], [[1225, 1225], "mapped", [1226]], [[1226, 1226], "valid"], [[1227, 1227], "mapped", [1228]], [[1228, 1228], "valid"], [[1229, 1229], "mapped", [1230]], [[1230, 1230], "valid"], [[1231, 1231], "valid"], [[1232, 1232], "mapped", [1233]], [[1233, 1233], "valid"], [[1234, 1234], "mapped", [1235]], [[1235, 1235], "valid"], [[1236, 1236], "mapped", [1237]], [[1237, 1237], "valid"], [[1238, 1238], "mapped", [1239]], [[1239, 1239], "valid"], [[1240, 1240], "mapped", [1241]], [[1241, 1241], "valid"], [[1242, 1242], "mapped", [1243]], [[1243, 1243], "valid"], [[1244, 1244], "mapped", [1245]], [[1245, 1245], "valid"], [[1246, 1246], "mapped", [1247]], [[1247, 1247], "valid"], [[1248, 1248], "mapped", [1249]], [[1249, 1249], "valid"], [[1250, 1250], "mapped", [1251]], [[1251, 1251], "valid"], [[1252, 1252], "mapped", [1253]], [[1253, 1253], "valid"], [[1254, 1254], "mapped", [1255]], [[1255, 1255], "valid"], [[1256, 1256], "mapped", [1257]], [[1257, 1257], "valid"], [[1258, 1258], "mapped", [1259]], [[1259, 1259], "valid"], [[1260, 1260], "mapped", [1261]], [[1261, 1261], "valid"], [[1262, 1262], "mapped", [1263]], [[1263, 1263], "valid"], [[1264, 1264], "mapped", [1265]], [[1265, 1265], "valid"], [[1266, 1266], "mapped", [1267]], [[1267, 1267], "valid"], [[1268, 1268], "mapped", [1269]], [[1269, 1269], "valid"], [[1270, 1270], "mapped", [1271]], [[1271, 1271], "valid"], [[1272, 1272], "mapped", [1273]], [[1273, 1273], "valid"], [[1274, 1274], "mapped", [1275]], [[1275, 1275], "valid"], [[1276, 1276], "mapped", [1277]], [[1277, 1277], "valid"], [[1278, 1278], "mapped", [1279]], [[1279, 1279], "valid"], [[1280, 1280], "mapped", [1281]], [[1281, 1281], "valid"], [[1282, 1282], "mapped", [1283]], [[1283, 1283], "valid"], [[1284, 1284], "mapped", [1285]], [[1285, 1285], "valid"], [[1286, 1286], "mapped", [1287]], [[1287, 1287], "valid"], [[1288, 1288], "mapped", [1289]], [[1289, 1289], "valid"], [[1290, 1290], "mapped", [1291]], [[1291, 1291], "valid"], [[1292, 1292], "mapped", [1293]], [[1293, 1293], "valid"], [[1294, 1294], "mapped", [1295]], [[1295, 1295], "valid"], [[1296, 1296], "mapped", [1297]], [[1297, 1297], "valid"], [[1298, 1298], "mapped", [1299]], [[1299, 1299], "valid"], [[1300, 1300], "mapped", [1301]], [[1301, 1301], "valid"], [[1302, 1302], "mapped", [1303]], [[1303, 1303], "valid"], [[1304, 1304], "mapped", [1305]], [[1305, 1305], "valid"], [[1306, 1306], "mapped", [1307]], [[1307, 1307], "valid"], [[1308, 1308], "mapped", [1309]], [[1309, 1309], "valid"], [[1310, 1310], "mapped", [1311]], [[1311, 1311], "valid"], [[1312, 1312], "mapped", [1313]], [[1313, 1313], "valid"], [[1314, 1314], "mapped", [1315]], [[1315, 1315], "valid"], [[1316, 1316], "mapped", [1317]], [[1317, 1317], "valid"], [[1318, 1318], "mapped", [1319]], [[1319, 1319], "valid"], [[1320, 1320], "mapped", [1321]], [[1321, 1321], "valid"], [[1322, 1322], "mapped", [1323]], [[1323, 1323], "valid"], [[1324, 1324], "mapped", [1325]], [[1325, 1325], "valid"], [[1326, 1326], "mapped", [1327]], [[1327, 1327], "valid"], [[1328, 1328], "disallowed"], [[1329, 1329], "mapped", [1377]], [[1330, 1330], "mapped", [1378]], [[1331, 1331], "mapped", [1379]], [[1332, 1332], "mapped", [1380]], [[1333, 1333], "mapped", [1381]], [[1334, 1334], "mapped", [1382]], [[1335, 1335], "mapped", [1383]], [[1336, 1336], "mapped", [1384]], [[1337, 1337], "mapped", [1385]], [[1338, 1338], "mapped", [1386]], [[1339, 1339], "mapped", [1387]], [[1340, 1340], "mapped", [1388]], [[1341, 1341], "mapped", [1389]], [[1342, 1342], "mapped", [1390]], [[1343, 1343], "mapped", [1391]], [[1344, 1344], "mapped", [1392]], [[1345, 1345], "mapped", [1393]], [[1346, 1346], "mapped", [1394]], [[1347, 1347], "mapped", [1395]], [[1348, 1348], "mapped", [1396]], [[1349, 1349], "mapped", [1397]], [[1350, 1350], "mapped", [1398]], [[1351, 1351], "mapped", [1399]], [[1352, 1352], "mapped", [1400]], [[1353, 1353], "mapped", [1401]], [[1354, 1354], "mapped", [1402]], [[1355, 1355], "mapped", [1403]], [[1356, 1356], "mapped", [1404]], [[1357, 1357], "mapped", [1405]], [[1358, 1358], "mapped", [1406]], [[1359, 1359], "mapped", [1407]], [[1360, 1360], "mapped", [1408]], [[1361, 1361], "mapped", [1409]], [[1362, 1362], "mapped", [1410]], [[1363, 1363], "mapped", [1411]], [[1364, 1364], "mapped", [1412]], [[1365, 1365], "mapped", [1413]], [[1366, 1366], "mapped", [1414]], [[1367, 1368], "disallowed"], [[1369, 1369], "valid"], [[1370, 1375], "valid", [], "NV8"], [[1376, 1376], "disallowed"], [[1377, 1414], "valid"], [[1415, 1415], "mapped", [1381, 1410]], [[1416, 1416], "disallowed"], [[1417, 1417], "valid", [], "NV8"], [[1418, 1418], "valid", [], "NV8"], [[1419, 1420], "disallowed"], [[1421, 1422], "valid", [], "NV8"], [[1423, 1423], "valid", [], "NV8"], [[1424, 1424], "disallowed"], [[1425, 1441], "valid"], [[1442, 1442], "valid"], [[1443, 1455], "valid"], [[1456, 1465], "valid"], [[1466, 1466], "valid"], [[1467, 1469], "valid"], [[1470, 1470], "valid", [], "NV8"], [[1471, 1471], "valid"], [[1472, 1472], "valid", [], "NV8"], [[1473, 1474], "valid"], [[1475, 1475], "valid", [], "NV8"], [[1476, 1476], "valid"], [[1477, 1477], "valid"], [[1478, 1478], "valid", [], "NV8"], [[1479, 1479], "valid"], [[1480, 1487], "disallowed"], [[1488, 1514], "valid"], [[1515, 1519], "disallowed"], [[1520, 1524], "valid"], [[1525, 1535], "disallowed"], [[1536, 1539], "disallowed"], [[1540, 1540], "disallowed"], [[1541, 1541], "disallowed"], [[1542, 1546], "valid", [], "NV8"], [[1547, 1547], "valid", [], "NV8"], [[1548, 1548], "valid", [], "NV8"], [[1549, 1551], "valid", [], "NV8"], [[1552, 1557], "valid"], [[1558, 1562], "valid"], [[1563, 1563], "valid", [], "NV8"], [[1564, 1564], "disallowed"], [[1565, 1565], "disallowed"], [[1566, 1566], "valid", [], "NV8"], [[1567, 1567], "valid", [], "NV8"], [[1568, 1568], "valid"], [[1569, 1594], "valid"], [[1595, 1599], "valid"], [[1600, 1600], "valid", [], "NV8"], [[1601, 1618], "valid"], [[1619, 1621], "valid"], [[1622, 1624], "valid"], [[1625, 1630], "valid"], [[1631, 1631], "valid"], [[1632, 1641], "valid"], [[1642, 1645], "valid", [], "NV8"], [[1646, 1647], "valid"], [[1648, 1652], "valid"], [[1653, 1653], "mapped", [1575, 1652]], [[1654, 1654], "mapped", [1608, 1652]], [[1655, 1655], "mapped", [1735, 1652]], [[1656, 1656], "mapped", [1610, 1652]], [[1657, 1719], "valid"], [[1720, 1721], "valid"], [[1722, 1726], "valid"], [[1727, 1727], "valid"], [[1728, 1742], "valid"], [[1743, 1743], "valid"], [[1744, 1747], "valid"], [[1748, 1748], "valid", [], "NV8"], [[1749, 1756], "valid"], [[1757, 1757], "disallowed"], [[1758, 1758], "valid", [], "NV8"], [[1759, 1768], "valid"], [[1769, 1769], "valid", [], "NV8"], [[1770, 1773], "valid"], [[1774, 1775], "valid"], [[1776, 1785], "valid"], [[1786, 1790], "valid"], [[1791, 1791], "valid"], [[1792, 1805], "valid", [], "NV8"], [[1806, 1806], "disallowed"], [[1807, 1807], "disallowed"], [[1808, 1836], "valid"], [[1837, 1839], "valid"], [[1840, 1866], "valid"], [[1867, 1868], "disallowed"], [[1869, 1871], "valid"], [[1872, 1901], "valid"], [[1902, 1919], "valid"], [[1920, 1968], "valid"], [[1969, 1969], "valid"], [[1970, 1983], "disallowed"], [[1984, 2037], "valid"], [[2038, 2042], "valid", [], "NV8"], [[2043, 2047], "disallowed"], [[2048, 2093], "valid"], [[2094, 2095], "disallowed"], [[2096, 2110], "valid", [], "NV8"], [[2111, 2111], "disallowed"], [[2112, 2139], "valid"], [[2140, 2141], "disallowed"], [[2142, 2142], "valid", [], "NV8"], [[2143, 2207], "disallowed"], [[2208, 2208], "valid"], [[2209, 2209], "valid"], [[2210, 2220], "valid"], [[2221, 2226], "valid"], [[2227, 2228], "valid"], [[2229, 2274], "disallowed"], [[2275, 2275], "valid"], [[2276, 2302], "valid"], [[2303, 2303], "valid"], [[2304, 2304], "valid"], [[2305, 2307], "valid"], [[2308, 2308], "valid"], [[2309, 2361], "valid"], [[2362, 2363], "valid"], [[2364, 2381], "valid"], [[2382, 2382], "valid"], [[2383, 2383], "valid"], [[2384, 2388], "valid"], [[2389, 2389], "valid"], [[2390, 2391], "valid"], [[2392, 2392], "mapped", [2325, 2364]], [[2393, 2393], "mapped", [2326, 2364]], [[2394, 2394], "mapped", [2327, 2364]], [[2395, 2395], "mapped", [2332, 2364]], [[2396, 2396], "mapped", [2337, 2364]], [[2397, 2397], "mapped", [2338, 2364]], [[2398, 2398], "mapped", [2347, 2364]], [[2399, 2399], "mapped", [2351, 2364]], [[2400, 2403], "valid"], [[2404, 2405], "valid", [], "NV8"], [[2406, 2415], "valid"], [[2416, 2416], "valid", [], "NV8"], [[2417, 2418], "valid"], [[2419, 2423], "valid"], [[2424, 2424], "valid"], [[2425, 2426], "valid"], [[2427, 2428], "valid"], [[2429, 2429], "valid"], [[2430, 2431], "valid"], [[2432, 2432], "valid"], [[2433, 2435], "valid"], [[2436, 2436], "disallowed"], [[2437, 2444], "valid"], [[2445, 2446], "disallowed"], [[2447, 2448], "valid"], [[2449, 2450], "disallowed"], [[2451, 2472], "valid"], [[2473, 2473], "disallowed"], [[2474, 2480], "valid"], [[2481, 2481], "disallowed"], [[2482, 2482], "valid"], [[2483, 2485], "disallowed"], [[2486, 2489], "valid"], [[2490, 2491], "disallowed"], [[2492, 2492], "valid"], [[2493, 2493], "valid"], [[2494, 2500], "valid"], [[2501, 2502], "disallowed"], [[2503, 2504], "valid"], [[2505, 2506], "disallowed"], [[2507, 2509], "valid"], [[2510, 2510], "valid"], [[2511, 2518], "disallowed"], [[2519, 2519], "valid"], [[2520, 2523], "disallowed"], [[2524, 2524], "mapped", [2465, 2492]], [[2525, 2525], "mapped", [2466, 2492]], [[2526, 2526], "disallowed"], [[2527, 2527], "mapped", [2479, 2492]], [[2528, 2531], "valid"], [[2532, 2533], "disallowed"], [[2534, 2545], "valid"], [[2546, 2554], "valid", [], "NV8"], [[2555, 2555], "valid", [], "NV8"], [[2556, 2560], "disallowed"], [[2561, 2561], "valid"], [[2562, 2562], "valid"], [[2563, 2563], "valid"], [[2564, 2564], "disallowed"], [[2565, 2570], "valid"], [[2571, 2574], "disallowed"], [[2575, 2576], "valid"], [[2577, 2578], "disallowed"], [[2579, 2600], "valid"], [[2601, 2601], "disallowed"], [[2602, 2608], "valid"], [[2609, 2609], "disallowed"], [[2610, 2610], "valid"], [[2611, 2611], "mapped", [2610, 2620]], [[2612, 2612], "disallowed"], [[2613, 2613], "valid"], [[2614, 2614], "mapped", [2616, 2620]], [[2615, 2615], "disallowed"], [[2616, 2617], "valid"], [[2618, 2619], "disallowed"], [[2620, 2620], "valid"], [[2621, 2621], "disallowed"], [[2622, 2626], "valid"], [[2627, 2630], "disallowed"], [[2631, 2632], "valid"], [[2633, 2634], "disallowed"], [[2635, 2637], "valid"], [[2638, 2640], "disallowed"], [[2641, 2641], "valid"], [[2642, 2648], "disallowed"], [[2649, 2649], "mapped", [2582, 2620]], [[2650, 2650], "mapped", [2583, 2620]], [[2651, 2651], "mapped", [2588, 2620]], [[2652, 2652], "valid"], [[2653, 2653], "disallowed"], [[2654, 2654], "mapped", [2603, 2620]], [[2655, 2661], "disallowed"], [[2662, 2676], "valid"], [[2677, 2677], "valid"], [[2678, 2688], "disallowed"], [[2689, 2691], "valid"], [[2692, 2692], "disallowed"], [[2693, 2699], "valid"], [[2700, 2700], "valid"], [[2701, 2701], "valid"], [[2702, 2702], "disallowed"], [[2703, 2705], "valid"], [[2706, 2706], "disallowed"], [[2707, 2728], "valid"], [[2729, 2729], "disallowed"], [[2730, 2736], "valid"], [[2737, 2737], "disallowed"], [[2738, 2739], "valid"], [[2740, 2740], "disallowed"], [[2741, 2745], "valid"], [[2746, 2747], "disallowed"], [[2748, 2757], "valid"], [[2758, 2758], "disallowed"], [[2759, 2761], "valid"], [[2762, 2762], "disallowed"], [[2763, 2765], "valid"], [[2766, 2767], "disallowed"], [[2768, 2768], "valid"], [[2769, 2783], "disallowed"], [[2784, 2784], "valid"], [[2785, 2787], "valid"], [[2788, 2789], "disallowed"], [[2790, 2799], "valid"], [[2800, 2800], "valid", [], "NV8"], [[2801, 2801], "valid", [], "NV8"], [[2802, 2808], "disallowed"], [[2809, 2809], "valid"], [[2810, 2816], "disallowed"], [[2817, 2819], "valid"], [[2820, 2820], "disallowed"], [[2821, 2828], "valid"], [[2829, 2830], "disallowed"], [[2831, 2832], "valid"], [[2833, 2834], "disallowed"], [[2835, 2856], "valid"], [[2857, 2857], "disallowed"], [[2858, 2864], "valid"], [[2865, 2865], "disallowed"], [[2866, 2867], "valid"], [[2868, 2868], "disallowed"], [[2869, 2869], "valid"], [[2870, 2873], "valid"], [[2874, 2875], "disallowed"], [[2876, 2883], "valid"], [[2884, 2884], "valid"], [[2885, 2886], "disallowed"], [[2887, 2888], "valid"], [[2889, 2890], "disallowed"], [[2891, 2893], "valid"], [[2894, 2901], "disallowed"], [[2902, 2903], "valid"], [[2904, 2907], "disallowed"], [[2908, 2908], "mapped", [2849, 2876]], [[2909, 2909], "mapped", [2850, 2876]], [[2910, 2910], "disallowed"], [[2911, 2913], "valid"], [[2914, 2915], "valid"], [[2916, 2917], "disallowed"], [[2918, 2927], "valid"], [[2928, 2928], "valid", [], "NV8"], [[2929, 2929], "valid"], [[2930, 2935], "valid", [], "NV8"], [[2936, 2945], "disallowed"], [[2946, 2947], "valid"], [[2948, 2948], "disallowed"], [[2949, 2954], "valid"], [[2955, 2957], "disallowed"], [[2958, 2960], "valid"], [[2961, 2961], "disallowed"], [[2962, 2965], "valid"], [[2966, 2968], "disallowed"], [[2969, 2970], "valid"], [[2971, 2971], "disallowed"], [[2972, 2972], "valid"], [[2973, 2973], "disallowed"], [[2974, 2975], "valid"], [[2976, 2978], "disallowed"], [[2979, 2980], "valid"], [[2981, 2983], "disallowed"], [[2984, 2986], "valid"], [[2987, 2989], "disallowed"], [[2990, 2997], "valid"], [[2998, 2998], "valid"], [[2999, 3001], "valid"], [[3002, 3005], "disallowed"], [[3006, 3010], "valid"], [[3011, 3013], "disallowed"], [[3014, 3016], "valid"], [[3017, 3017], "disallowed"], [[3018, 3021], "valid"], [[3022, 3023], "disallowed"], [[3024, 3024], "valid"], [[3025, 3030], "disallowed"], [[3031, 3031], "valid"], [[3032, 3045], "disallowed"], [[3046, 3046], "valid"], [[3047, 3055], "valid"], [[3056, 3058], "valid", [], "NV8"], [[3059, 3066], "valid", [], "NV8"], [[3067, 3071], "disallowed"], [[3072, 3072], "valid"], [[3073, 3075], "valid"], [[3076, 3076], "disallowed"], [[3077, 3084], "valid"], [[3085, 3085], "disallowed"], [[3086, 3088], "valid"], [[3089, 3089], "disallowed"], [[3090, 3112], "valid"], [[3113, 3113], "disallowed"], [[3114, 3123], "valid"], [[3124, 3124], "valid"], [[3125, 3129], "valid"], [[3130, 3132], "disallowed"], [[3133, 3133], "valid"], [[3134, 3140], "valid"], [[3141, 3141], "disallowed"], [[3142, 3144], "valid"], [[3145, 3145], "disallowed"], [[3146, 3149], "valid"], [[3150, 3156], "disallowed"], [[3157, 3158], "valid"], [[3159, 3159], "disallowed"], [[3160, 3161], "valid"], [[3162, 3162], "valid"], [[3163, 3167], "disallowed"], [[3168, 3169], "valid"], [[3170, 3171], "valid"], [[3172, 3173], "disallowed"], [[3174, 3183], "valid"], [[3184, 3191], "disallowed"], [[3192, 3199], "valid", [], "NV8"], [[3200, 3200], "disallowed"], [[3201, 3201], "valid"], [[3202, 3203], "valid"], [[3204, 3204], "disallowed"], [[3205, 3212], "valid"], [[3213, 3213], "disallowed"], [[3214, 3216], "valid"], [[3217, 3217], "disallowed"], [[3218, 3240], "valid"], [[3241, 3241], "disallowed"], [[3242, 3251], "valid"], [[3252, 3252], "disallowed"], [[3253, 3257], "valid"], [[3258, 3259], "disallowed"], [[3260, 3261], "valid"], [[3262, 3268], "valid"], [[3269, 3269], "disallowed"], [[3270, 3272], "valid"], [[3273, 3273], "disallowed"], [[3274, 3277], "valid"], [[3278, 3284], "disallowed"], [[3285, 3286], "valid"], [[3287, 3293], "disallowed"], [[3294, 3294], "valid"], [[3295, 3295], "disallowed"], [[3296, 3297], "valid"], [[3298, 3299], "valid"], [[3300, 3301], "disallowed"], [[3302, 3311], "valid"], [[3312, 3312], "disallowed"], [[3313, 3314], "valid"], [[3315, 3328], "disallowed"], [[3329, 3329], "valid"], [[3330, 3331], "valid"], [[3332, 3332], "disallowed"], [[3333, 3340], "valid"], [[3341, 3341], "disallowed"], [[3342, 3344], "valid"], [[3345, 3345], "disallowed"], [[3346, 3368], "valid"], [[3369, 3369], "valid"], [[3370, 3385], "valid"], [[3386, 3386], "valid"], [[3387, 3388], "disallowed"], [[3389, 3389], "valid"], [[3390, 3395], "valid"], [[3396, 3396], "valid"], [[3397, 3397], "disallowed"], [[3398, 3400], "valid"], [[3401, 3401], "disallowed"], [[3402, 3405], "valid"], [[3406, 3406], "valid"], [[3407, 3414], "disallowed"], [[3415, 3415], "valid"], [[3416, 3422], "disallowed"], [[3423, 3423], "valid"], [[3424, 3425], "valid"], [[3426, 3427], "valid"], [[3428, 3429], "disallowed"], [[3430, 3439], "valid"], [[3440, 3445], "valid", [], "NV8"], [[3446, 3448], "disallowed"], [[3449, 3449], "valid", [], "NV8"], [[3450, 3455], "valid"], [[3456, 3457], "disallowed"], [[3458, 3459], "valid"], [[3460, 3460], "disallowed"], [[3461, 3478], "valid"], [[3479, 3481], "disallowed"], [[3482, 3505], "valid"], [[3506, 3506], "disallowed"], [[3507, 3515], "valid"], [[3516, 3516], "disallowed"], [[3517, 3517], "valid"], [[3518, 3519], "disallowed"], [[3520, 3526], "valid"], [[3527, 3529], "disallowed"], [[3530, 3530], "valid"], [[3531, 3534], "disallowed"], [[3535, 3540], "valid"], [[3541, 3541], "disallowed"], [[3542, 3542], "valid"], [[3543, 3543], "disallowed"], [[3544, 3551], "valid"], [[3552, 3557], "disallowed"], [[3558, 3567], "valid"], [[3568, 3569], "disallowed"], [[3570, 3571], "valid"], [[3572, 3572], "valid", [], "NV8"], [[3573, 3584], "disallowed"], [[3585, 3634], "valid"], [[3635, 3635], "mapped", [3661, 3634]], [[3636, 3642], "valid"], [[3643, 3646], "disallowed"], [[3647, 3647], "valid", [], "NV8"], [[3648, 3662], "valid"], [[3663, 3663], "valid", [], "NV8"], [[3664, 3673], "valid"], [[3674, 3675], "valid", [], "NV8"], [[3676, 3712], "disallowed"], [[3713, 3714], "valid"], [[3715, 3715], "disallowed"], [[3716, 3716], "valid"], [[3717, 3718], "disallowed"], [[3719, 3720], "valid"], [[3721, 3721], "disallowed"], [[3722, 3722], "valid"], [[3723, 3724], "disallowed"], [[3725, 3725], "valid"], [[3726, 3731], "disallowed"], [[3732, 3735], "valid"], [[3736, 3736], "disallowed"], [[3737, 3743], "valid"], [[3744, 3744], "disallowed"], [[3745, 3747], "valid"], [[3748, 3748], "disallowed"], [[3749, 3749], "valid"], [[3750, 3750], "disallowed"], [[3751, 3751], "valid"], [[3752, 3753], "disallowed"], [[3754, 3755], "valid"], [[3756, 3756], "disallowed"], [[3757, 3762], "valid"], [[3763, 3763], "mapped", [3789, 3762]], [[3764, 3769], "valid"], [[3770, 3770], "disallowed"], [[3771, 3773], "valid"], [[3774, 3775], "disallowed"], [[3776, 3780], "valid"], [[3781, 3781], "disallowed"], [[3782, 3782], "valid"], [[3783, 3783], "disallowed"], [[3784, 3789], "valid"], [[3790, 3791], "disallowed"], [[3792, 3801], "valid"], [[3802, 3803], "disallowed"], [[3804, 3804], "mapped", [3755, 3737]], [[3805, 3805], "mapped", [3755, 3745]], [[3806, 3807], "valid"], [[3808, 3839], "disallowed"], [[3840, 3840], "valid"], [[3841, 3850], "valid", [], "NV8"], [[3851, 3851], "valid"], [[3852, 3852], "mapped", [3851]], [[3853, 3863], "valid", [], "NV8"], [[3864, 3865], "valid"], [[3866, 3871], "valid", [], "NV8"], [[3872, 3881], "valid"], [[3882, 3892], "valid", [], "NV8"], [[3893, 3893], "valid"], [[3894, 3894], "valid", [], "NV8"], [[3895, 3895], "valid"], [[3896, 3896], "valid", [], "NV8"], [[3897, 3897], "valid"], [[3898, 3901], "valid", [], "NV8"], [[3902, 3906], "valid"], [[3907, 3907], "mapped", [3906, 4023]], [[3908, 3911], "valid"], [[3912, 3912], "disallowed"], [[3913, 3916], "valid"], [[3917, 3917], "mapped", [3916, 4023]], [[3918, 3921], "valid"], [[3922, 3922], "mapped", [3921, 4023]], [[3923, 3926], "valid"], [[3927, 3927], "mapped", [3926, 4023]], [[3928, 3931], "valid"], [[3932, 3932], "mapped", [3931, 4023]], [[3933, 3944], "valid"], [[3945, 3945], "mapped", [3904, 4021]], [[3946, 3946], "valid"], [[3947, 3948], "valid"], [[3949, 3952], "disallowed"], [[3953, 3954], "valid"], [[3955, 3955], "mapped", [3953, 3954]], [[3956, 3956], "valid"], [[3957, 3957], "mapped", [3953, 3956]], [[3958, 3958], "mapped", [4018, 3968]], [[3959, 3959], "mapped", [4018, 3953, 3968]], [[3960, 3960], "mapped", [4019, 3968]], [[3961, 3961], "mapped", [4019, 3953, 3968]], [[3962, 3968], "valid"], [[3969, 3969], "mapped", [3953, 3968]], [[3970, 3972], "valid"], [[3973, 3973], "valid", [], "NV8"], [[3974, 3979], "valid"], [[3980, 3983], "valid"], [[3984, 3986], "valid"], [[3987, 3987], "mapped", [3986, 4023]], [[3988, 3989], "valid"], [[3990, 3990], "valid"], [[3991, 3991], "valid"], [[3992, 3992], "disallowed"], [[3993, 3996], "valid"], [[3997, 3997], "mapped", [3996, 4023]], [[3998, 4001], "valid"], [[4002, 4002], "mapped", [4001, 4023]], [[4003, 4006], "valid"], [[4007, 4007], "mapped", [4006, 4023]], [[4008, 4011], "valid"], [[4012, 4012], "mapped", [4011, 4023]], [[4013, 4013], "valid"], [[4014, 4016], "valid"], [[4017, 4023], "valid"], [[4024, 4024], "valid"], [[4025, 4025], "mapped", [3984, 4021]], [[4026, 4028], "valid"], [[4029, 4029], "disallowed"], [[4030, 4037], "valid", [], "NV8"], [[4038, 4038], "valid"], [[4039, 4044], "valid", [], "NV8"], [[4045, 4045], "disallowed"], [[4046, 4046], "valid", [], "NV8"], [[4047, 4047], "valid", [], "NV8"], [[4048, 4049], "valid", [], "NV8"], [[4050, 4052], "valid", [], "NV8"], [[4053, 4056], "valid", [], "NV8"], [[4057, 4058], "valid", [], "NV8"], [[4059, 4095], "disallowed"], [[4096, 4129], "valid"], [[4130, 4130], "valid"], [[4131, 4135], "valid"], [[4136, 4136], "valid"], [[4137, 4138], "valid"], [[4139, 4139], "valid"], [[4140, 4146], "valid"], [[4147, 4149], "valid"], [[4150, 4153], "valid"], [[4154, 4159], "valid"], [[4160, 4169], "valid"], [[4170, 4175], "valid", [], "NV8"], [[4176, 4185], "valid"], [[4186, 4249], "valid"], [[4250, 4253], "valid"], [[4254, 4255], "valid", [], "NV8"], [[4256, 4293], "disallowed"], [[4294, 4294], "disallowed"], [[4295, 4295], "mapped", [11559]], [[4296, 4300], "disallowed"], [[4301, 4301], "mapped", [11565]], [[4302, 4303], "disallowed"], [[4304, 4342], "valid"], [[4343, 4344], "valid"], [[4345, 4346], "valid"], [[4347, 4347], "valid", [], "NV8"], [[4348, 4348], "mapped", [4316]], [[4349, 4351], "valid"], [[4352, 4441], "valid", [], "NV8"], [[4442, 4446], "valid", [], "NV8"], [[4447, 4448], "disallowed"], [[4449, 4514], "valid", [], "NV8"], [[4515, 4519], "valid", [], "NV8"], [[4520, 4601], "valid", [], "NV8"], [[4602, 4607], "valid", [], "NV8"], [[4608, 4614], "valid"], [[4615, 4615], "valid"], [[4616, 4678], "valid"], [[4679, 4679], "valid"], [[4680, 4680], "valid"], [[4681, 4681], "disallowed"], [[4682, 4685], "valid"], [[4686, 4687], "disallowed"], [[4688, 4694], "valid"], [[4695, 4695], "disallowed"], [[4696, 4696], "valid"], [[4697, 4697], "disallowed"], [[4698, 4701], "valid"], [[4702, 4703], "disallowed"], [[4704, 4742], "valid"], [[4743, 4743], "valid"], [[4744, 4744], "valid"], [[4745, 4745], "disallowed"], [[4746, 4749], "valid"], [[4750, 4751], "disallowed"], [[4752, 4782], "valid"], [[4783, 4783], "valid"], [[4784, 4784], "valid"], [[4785, 4785], "disallowed"], [[4786, 4789], "valid"], [[4790, 4791], "disallowed"], [[4792, 4798], "valid"], [[4799, 4799], "disallowed"], [[4800, 4800], "valid"], [[4801, 4801], "disallowed"], [[4802, 4805], "valid"], [[4806, 4807], "disallowed"], [[4808, 4814], "valid"], [[4815, 4815], "valid"], [[4816, 4822], "valid"], [[4823, 4823], "disallowed"], [[4824, 4846], "valid"], [[4847, 4847], "valid"], [[4848, 4878], "valid"], [[4879, 4879], "valid"], [[4880, 4880], "valid"], [[4881, 4881], "disallowed"], [[4882, 4885], "valid"], [[4886, 4887], "disallowed"], [[4888, 4894], "valid"], [[4895, 4895], "valid"], [[4896, 4934], "valid"], [[4935, 4935], "valid"], [[4936, 4954], "valid"], [[4955, 4956], "disallowed"], [[4957, 4958], "valid"], [[4959, 4959], "valid"], [[4960, 4960], "valid", [], "NV8"], [[4961, 4988], "valid", [], "NV8"], [[4989, 4991], "disallowed"], [[4992, 5007], "valid"], [[5008, 5017], "valid", [], "NV8"], [[5018, 5023], "disallowed"], [[5024, 5108], "valid"], [[5109, 5109], "valid"], [[5110, 5111], "disallowed"], [[5112, 5112], "mapped", [5104]], [[5113, 5113], "mapped", [5105]], [[5114, 5114], "mapped", [5106]], [[5115, 5115], "mapped", [5107]], [[5116, 5116], "mapped", [5108]], [[5117, 5117], "mapped", [5109]], [[5118, 5119], "disallowed"], [[5120, 5120], "valid", [], "NV8"], [[5121, 5740], "valid"], [[5741, 5742], "valid", [], "NV8"], [[5743, 5750], "valid"], [[5751, 5759], "valid"], [[5760, 5760], "disallowed"], [[5761, 5786], "valid"], [[5787, 5788], "valid", [], "NV8"], [[5789, 5791], "disallowed"], [[5792, 5866], "valid"], [[5867, 5872], "valid", [], "NV8"], [[5873, 5880], "valid"], [[5881, 5887], "disallowed"], [[5888, 5900], "valid"], [[5901, 5901], "disallowed"], [[5902, 5908], "valid"], [[5909, 5919], "disallowed"], [[5920, 5940], "valid"], [[5941, 5942], "valid", [], "NV8"], [[5943, 5951], "disallowed"], [[5952, 5971], "valid"], [[5972, 5983], "disallowed"], [[5984, 5996], "valid"], [[5997, 5997], "disallowed"], [[5998, 6e3], "valid"], [[6001, 6001], "disallowed"], [[6002, 6003], "valid"], [[6004, 6015], "disallowed"], [[6016, 6067], "valid"], [[6068, 6069], "disallowed"], [[6070, 6099], "valid"], [[6100, 6102], "valid", [], "NV8"], [[6103, 6103], "valid"], [[6104, 6107], "valid", [], "NV8"], [[6108, 6108], "valid"], [[6109, 6109], "valid"], [[6110, 6111], "disallowed"], [[6112, 6121], "valid"], [[6122, 6127], "disallowed"], [[6128, 6137], "valid", [], "NV8"], [[6138, 6143], "disallowed"], [[6144, 6149], "valid", [], "NV8"], [[6150, 6150], "disallowed"], [[6151, 6154], "valid", [], "NV8"], [[6155, 6157], "ignored"], [[6158, 6158], "disallowed"], [[6159, 6159], "disallowed"], [[6160, 6169], "valid"], [[6170, 6175], "disallowed"], [[6176, 6263], "valid"], [[6264, 6271], "disallowed"], [[6272, 6313], "valid"], [[6314, 6314], "valid"], [[6315, 6319], "disallowed"], [[6320, 6389], "valid"], [[6390, 6399], "disallowed"], [[6400, 6428], "valid"], [[6429, 6430], "valid"], [[6431, 6431], "disallowed"], [[6432, 6443], "valid"], [[6444, 6447], "disallowed"], [[6448, 6459], "valid"], [[6460, 6463], "disallowed"], [[6464, 6464], "valid", [], "NV8"], [[6465, 6467], "disallowed"], [[6468, 6469], "valid", [], "NV8"], [[6470, 6509], "valid"], [[6510, 6511], "disallowed"], [[6512, 6516], "valid"], [[6517, 6527], "disallowed"], [[6528, 6569], "valid"], [[6570, 6571], "valid"], [[6572, 6575], "disallowed"], [[6576, 6601], "valid"], [[6602, 6607], "disallowed"], [[6608, 6617], "valid"], [[6618, 6618], "valid", [], "XV8"], [[6619, 6621], "disallowed"], [[6622, 6623], "valid", [], "NV8"], [[6624, 6655], "valid", [], "NV8"], [[6656, 6683], "valid"], [[6684, 6685], "disallowed"], [[6686, 6687], "valid", [], "NV8"], [[6688, 6750], "valid"], [[6751, 6751], "disallowed"], [[6752, 6780], "valid"], [[6781, 6782], "disallowed"], [[6783, 6793], "valid"], [[6794, 6799], "disallowed"], [[6800, 6809], "valid"], [[6810, 6815], "disallowed"], [[6816, 6822], "valid", [], "NV8"], [[6823, 6823], "valid"], [[6824, 6829], "valid", [], "NV8"], [[6830, 6831], "disallowed"], [[6832, 6845], "valid"], [[6846, 6846], "valid", [], "NV8"], [[6847, 6911], "disallowed"], [[6912, 6987], "valid"], [[6988, 6991], "disallowed"], [[6992, 7001], "valid"], [[7002, 7018], "valid", [], "NV8"], [[7019, 7027], "valid"], [[7028, 7036], "valid", [], "NV8"], [[7037, 7039], "disallowed"], [[7040, 7082], "valid"], [[7083, 7085], "valid"], [[7086, 7097], "valid"], [[7098, 7103], "valid"], [[7104, 7155], "valid"], [[7156, 7163], "disallowed"], [[7164, 7167], "valid", [], "NV8"], [[7168, 7223], "valid"], [[7224, 7226], "disallowed"], [[7227, 7231], "valid", [], "NV8"], [[7232, 7241], "valid"], [[7242, 7244], "disallowed"], [[7245, 7293], "valid"], [[7294, 7295], "valid", [], "NV8"], [[7296, 7359], "disallowed"], [[7360, 7367], "valid", [], "NV8"], [[7368, 7375], "disallowed"], [[7376, 7378], "valid"], [[7379, 7379], "valid", [], "NV8"], [[7380, 7410], "valid"], [[7411, 7414], "valid"], [[7415, 7415], "disallowed"], [[7416, 7417], "valid"], [[7418, 7423], "disallowed"], [[7424, 7467], "valid"], [[7468, 7468], "mapped", [97]], [[7469, 7469], "mapped", [230]], [[7470, 7470], "mapped", [98]], [[7471, 7471], "valid"], [[7472, 7472], "mapped", [100]], [[7473, 7473], "mapped", [101]], [[7474, 7474], "mapped", [477]], [[7475, 7475], "mapped", [103]], [[7476, 7476], "mapped", [104]], [[7477, 7477], "mapped", [105]], [[7478, 7478], "mapped", [106]], [[7479, 7479], "mapped", [107]], [[7480, 7480], "mapped", [108]], [[7481, 7481], "mapped", [109]], [[7482, 7482], "mapped", [110]], [[7483, 7483], "valid"], [[7484, 7484], "mapped", [111]], [[7485, 7485], "mapped", [547]], [[7486, 7486], "mapped", [112]], [[7487, 7487], "mapped", [114]], [[7488, 7488], "mapped", [116]], [[7489, 7489], "mapped", [117]], [[7490, 7490], "mapped", [119]], [[7491, 7491], "mapped", [97]], [[7492, 7492], "mapped", [592]], [[7493, 7493], "mapped", [593]], [[7494, 7494], "mapped", [7426]], [[7495, 7495], "mapped", [98]], [[7496, 7496], "mapped", [100]], [[7497, 7497], "mapped", [101]], [[7498, 7498], "mapped", [601]], [[7499, 7499], "mapped", [603]], [[7500, 7500], "mapped", [604]], [[7501, 7501], "mapped", [103]], [[7502, 7502], "valid"], [[7503, 7503], "mapped", [107]], [[7504, 7504], "mapped", [109]], [[7505, 7505], "mapped", [331]], [[7506, 7506], "mapped", [111]], [[7507, 7507], "mapped", [596]], [[7508, 7508], "mapped", [7446]], [[7509, 7509], "mapped", [7447]], [[7510, 7510], "mapped", [112]], [[7511, 7511], "mapped", [116]], [[7512, 7512], "mapped", [117]], [[7513, 7513], "mapped", [7453]], [[7514, 7514], "mapped", [623]], [[7515, 7515], "mapped", [118]], [[7516, 7516], "mapped", [7461]], [[7517, 7517], "mapped", [946]], [[7518, 7518], "mapped", [947]], [[7519, 7519], "mapped", [948]], [[7520, 7520], "mapped", [966]], [[7521, 7521], "mapped", [967]], [[7522, 7522], "mapped", [105]], [[7523, 7523], "mapped", [114]], [[7524, 7524], "mapped", [117]], [[7525, 7525], "mapped", [118]], [[7526, 7526], "mapped", [946]], [[7527, 7527], "mapped", [947]], [[7528, 7528], "mapped", [961]], [[7529, 7529], "mapped", [966]], [[7530, 7530], "mapped", [967]], [[7531, 7531], "valid"], [[7532, 7543], "valid"], [[7544, 7544], "mapped", [1085]], [[7545, 7578], "valid"], [[7579, 7579], "mapped", [594]], [[7580, 7580], "mapped", [99]], [[7581, 7581], "mapped", [597]], [[7582, 7582], "mapped", [240]], [[7583, 7583], "mapped", [604]], [[7584, 7584], "mapped", [102]], [[7585, 7585], "mapped", [607]], [[7586, 7586], "mapped", [609]], [[7587, 7587], "mapped", [613]], [[7588, 7588], "mapped", [616]], [[7589, 7589], "mapped", [617]], [[7590, 7590], "mapped", [618]], [[7591, 7591], "mapped", [7547]], [[7592, 7592], "mapped", [669]], [[7593, 7593], "mapped", [621]], [[7594, 7594], "mapped", [7557]], [[7595, 7595], "mapped", [671]], [[7596, 7596], "mapped", [625]], [[7597, 7597], "mapped", [624]], [[7598, 7598], "mapped", [626]], [[7599, 7599], "mapped", [627]], [[7600, 7600], "mapped", [628]], [[7601, 7601], "mapped", [629]], [[7602, 7602], "mapped", [632]], [[7603, 7603], "mapped", [642]], [[7604, 7604], "mapped", [643]], [[7605, 7605], "mapped", [427]], [[7606, 7606], "mapped", [649]], [[7607, 7607], "mapped", [650]], [[7608, 7608], "mapped", [7452]], [[7609, 7609], "mapped", [651]], [[7610, 7610], "mapped", [652]], [[7611, 7611], "mapped", [122]], [[7612, 7612], "mapped", [656]], [[7613, 7613], "mapped", [657]], [[7614, 7614], "mapped", [658]], [[7615, 7615], "mapped", [952]], [[7616, 7619], "valid"], [[7620, 7626], "valid"], [[7627, 7654], "valid"], [[7655, 7669], "valid"], [[7670, 7675], "disallowed"], [[7676, 7676], "valid"], [[7677, 7677], "valid"], [[7678, 7679], "valid"], [[7680, 7680], "mapped", [7681]], [[7681, 7681], "valid"], [[7682, 7682], "mapped", [7683]], [[7683, 7683], "valid"], [[7684, 7684], "mapped", [7685]], [[7685, 7685], "valid"], [[7686, 7686], "mapped", [7687]], [[7687, 7687], "valid"], [[7688, 7688], "mapped", [7689]], [[7689, 7689], "valid"], [[7690, 7690], "mapped", [7691]], [[7691, 7691], "valid"], [[7692, 7692], "mapped", [7693]], [[7693, 7693], "valid"], [[7694, 7694], "mapped", [7695]], [[7695, 7695], "valid"], [[7696, 7696], "mapped", [7697]], [[7697, 7697], "valid"], [[7698, 7698], "mapped", [7699]], [[7699, 7699], "valid"], [[7700, 7700], "mapped", [7701]], [[7701, 7701], "valid"], [[7702, 7702], "mapped", [7703]], [[7703, 7703], "valid"], [[7704, 7704], "mapped", [7705]], [[7705, 7705], "valid"], [[7706, 7706], "mapped", [7707]], [[7707, 7707], "valid"], [[7708, 7708], "mapped", [7709]], [[7709, 7709], "valid"], [[7710, 7710], "mapped", [7711]], [[7711, 7711], "valid"], [[7712, 7712], "mapped", [7713]], [[7713, 7713], "valid"], [[7714, 7714], "mapped", [7715]], [[7715, 7715], "valid"], [[7716, 7716], "mapped", [7717]], [[7717, 7717], "valid"], [[7718, 7718], "mapped", [7719]], [[7719, 7719], "valid"], [[7720, 7720], "mapped", [7721]], [[7721, 7721], "valid"], [[7722, 7722], "mapped", [7723]], [[7723, 7723], "valid"], [[7724, 7724], "mapped", [7725]], [[7725, 7725], "valid"], [[7726, 7726], "mapped", [7727]], [[7727, 7727], "valid"], [[7728, 7728], "mapped", [7729]], [[7729, 7729], "valid"], [[7730, 7730], "mapped", [7731]], [[7731, 7731], "valid"], [[7732, 7732], "mapped", [7733]], [[7733, 7733], "valid"], [[7734, 7734], "mapped", [7735]], [[7735, 7735], "valid"], [[7736, 7736], "mapped", [7737]], [[7737, 7737], "valid"], [[7738, 7738], "mapped", [7739]], [[7739, 7739], "valid"], [[7740, 7740], "mapped", [7741]], [[7741, 7741], "valid"], [[7742, 7742], "mapped", [7743]], [[7743, 7743], "valid"], [[7744, 7744], "mapped", [7745]], [[7745, 7745], "valid"], [[7746, 7746], "mapped", [7747]], [[7747, 7747], "valid"], [[7748, 7748], "mapped", [7749]], [[7749, 7749], "valid"], [[7750, 7750], "mapped", [7751]], [[7751, 7751], "valid"], [[7752, 7752], "mapped", [7753]], [[7753, 7753], "valid"], [[7754, 7754], "mapped", [7755]], [[7755, 7755], "valid"], [[7756, 7756], "mapped", [7757]], [[7757, 7757], "valid"], [[7758, 7758], "mapped", [7759]], [[7759, 7759], "valid"], [[7760, 7760], "mapped", [7761]], [[7761, 7761], "valid"], [[7762, 7762], "mapped", [7763]], [[7763, 7763], "valid"], [[7764, 7764], "mapped", [7765]], [[7765, 7765], "valid"], [[7766, 7766], "mapped", [7767]], [[7767, 7767], "valid"], [[7768, 7768], "mapped", [7769]], [[7769, 7769], "valid"], [[7770, 7770], "mapped", [7771]], [[7771, 7771], "valid"], [[7772, 7772], "mapped", [7773]], [[7773, 7773], "valid"], [[7774, 7774], "mapped", [7775]], [[7775, 7775], "valid"], [[7776, 7776], "mapped", [7777]], [[7777, 7777], "valid"], [[7778, 7778], "mapped", [7779]], [[7779, 7779], "valid"], [[7780, 7780], "mapped", [7781]], [[7781, 7781], "valid"], [[7782, 7782], "mapped", [7783]], [[7783, 7783], "valid"], [[7784, 7784], "mapped", [7785]], [[7785, 7785], "valid"], [[7786, 7786], "mapped", [7787]], [[7787, 7787], "valid"], [[7788, 7788], "mapped", [7789]], [[7789, 7789], "valid"], [[7790, 7790], "mapped", [7791]], [[7791, 7791], "valid"], [[7792, 7792], "mapped", [7793]], [[7793, 7793], "valid"], [[7794, 7794], "mapped", [7795]], [[7795, 7795], "valid"], [[7796, 7796], "mapped", [7797]], [[7797, 7797], "valid"], [[7798, 7798], "mapped", [7799]], [[7799, 7799], "valid"], [[7800, 7800], "mapped", [7801]], [[7801, 7801], "valid"], [[7802, 7802], "mapped", [7803]], [[7803, 7803], "valid"], [[7804, 7804], "mapped", [7805]], [[7805, 7805], "valid"], [[7806, 7806], "mapped", [7807]], [[7807, 7807], "valid"], [[7808, 7808], "mapped", [7809]], [[7809, 7809], "valid"], [[7810, 7810], "mapped", [7811]], [[7811, 7811], "valid"], [[7812, 7812], "mapped", [7813]], [[7813, 7813], "valid"], [[7814, 7814], "mapped", [7815]], [[7815, 7815], "valid"], [[7816, 7816], "mapped", [7817]], [[7817, 7817], "valid"], [[7818, 7818], "mapped", [7819]], [[7819, 7819], "valid"], [[7820, 7820], "mapped", [7821]], [[7821, 7821], "valid"], [[7822, 7822], "mapped", [7823]], [[7823, 7823], "valid"], [[7824, 7824], "mapped", [7825]], [[7825, 7825], "valid"], [[7826, 7826], "mapped", [7827]], [[7827, 7827], "valid"], [[7828, 7828], "mapped", [7829]], [[7829, 7833], "valid"], [[7834, 7834], "mapped", [97, 702]], [[7835, 7835], "mapped", [7777]], [[7836, 7837], "valid"], [[7838, 7838], "mapped", [115, 115]], [[7839, 7839], "valid"], [[7840, 7840], "mapped", [7841]], [[7841, 7841], "valid"], [[7842, 7842], "mapped", [7843]], [[7843, 7843], "valid"], [[7844, 7844], "mapped", [7845]], [[7845, 7845], "valid"], [[7846, 7846], "mapped", [7847]], [[7847, 7847], "valid"], [[7848, 7848], "mapped", [7849]], [[7849, 7849], "valid"], [[7850, 7850], "mapped", [7851]], [[7851, 7851], "valid"], [[7852, 7852], "mapped", [7853]], [[7853, 7853], "valid"], [[7854, 7854], "mapped", [7855]], [[7855, 7855], "valid"], [[7856, 7856], "mapped", [7857]], [[7857, 7857], "valid"], [[7858, 7858], "mapped", [7859]], [[7859, 7859], "valid"], [[7860, 7860], "mapped", [7861]], [[7861, 7861], "valid"], [[7862, 7862], "mapped", [7863]], [[7863, 7863], "valid"], [[7864, 7864], "mapped", [7865]], [[7865, 7865], "valid"], [[7866, 7866], "mapped", [7867]], [[7867, 7867], "valid"], [[7868, 7868], "mapped", [7869]], [[7869, 7869], "valid"], [[7870, 7870], "mapped", [7871]], [[7871, 7871], "valid"], [[7872, 7872], "mapped", [7873]], [[7873, 7873], "valid"], [[7874, 7874], "mapped", [7875]], [[7875, 7875], "valid"], [[7876, 7876], "mapped", [7877]], [[7877, 7877], "valid"], [[7878, 7878], "mapped", [7879]], [[7879, 7879], "valid"], [[7880, 7880], "mapped", [7881]], [[7881, 7881], "valid"], [[7882, 7882], "mapped", [7883]], [[7883, 7883], "valid"], [[7884, 7884], "mapped", [7885]], [[7885, 7885], "valid"], [[7886, 7886], "mapped", [7887]], [[7887, 7887], "valid"], [[7888, 7888], "mapped", [7889]], [[7889, 7889], "valid"], [[7890, 7890], "mapped", [7891]], [[7891, 7891], "valid"], [[7892, 7892], "mapped", [7893]], [[7893, 7893], "valid"], [[7894, 7894], "mapped", [7895]], [[7895, 7895], "valid"], [[7896, 7896], "mapped", [7897]], [[7897, 7897], "valid"], [[7898, 7898], "mapped", [7899]], [[7899, 7899], "valid"], [[7900, 7900], "mapped", [7901]], [[7901, 7901], "valid"], [[7902, 7902], "mapped", [7903]], [[7903, 7903], "valid"], [[7904, 7904], "mapped", [7905]], [[7905, 7905], "valid"], [[7906, 7906], "mapped", [7907]], [[7907, 7907], "valid"], [[7908, 7908], "mapped", [7909]], [[7909, 7909], "valid"], [[7910, 7910], "mapped", [7911]], [[7911, 7911], "valid"], [[7912, 7912], "mapped", [7913]], [[7913, 7913], "valid"], [[7914, 7914], "mapped", [7915]], [[7915, 7915], "valid"], [[7916, 7916], "mapped", [7917]], [[7917, 7917], "valid"], [[7918, 7918], "mapped", [7919]], [[7919, 7919], "valid"], [[7920, 7920], "mapped", [7921]], [[7921, 7921], "valid"], [[7922, 7922], "mapped", [7923]], [[7923, 7923], "valid"], [[7924, 7924], "mapped", [7925]], [[7925, 7925], "valid"], [[7926, 7926], "mapped", [7927]], [[7927, 7927], "valid"], [[7928, 7928], "mapped", [7929]], [[7929, 7929], "valid"], [[7930, 7930], "mapped", [7931]], [[7931, 7931], "valid"], [[7932, 7932], "mapped", [7933]], [[7933, 7933], "valid"], [[7934, 7934], "mapped", [7935]], [[7935, 7935], "valid"], [[7936, 7943], "valid"], [[7944, 7944], "mapped", [7936]], [[7945, 7945], "mapped", [7937]], [[7946, 7946], "mapped", [7938]], [[7947, 7947], "mapped", [7939]], [[7948, 7948], "mapped", [7940]], [[7949, 7949], "mapped", [7941]], [[7950, 7950], "mapped", [7942]], [[7951, 7951], "mapped", [7943]], [[7952, 7957], "valid"], [[7958, 7959], "disallowed"], [[7960, 7960], "mapped", [7952]], [[7961, 7961], "mapped", [7953]], [[7962, 7962], "mapped", [7954]], [[7963, 7963], "mapped", [7955]], [[7964, 7964], "mapped", [7956]], [[7965, 7965], "mapped", [7957]], [[7966, 7967], "disallowed"], [[7968, 7975], "valid"], [[7976, 7976], "mapped", [7968]], [[7977, 7977], "mapped", [7969]], [[7978, 7978], "mapped", [7970]], [[7979, 7979], "mapped", [7971]], [[7980, 7980], "mapped", [7972]], [[7981, 7981], "mapped", [7973]], [[7982, 7982], "mapped", [7974]], [[7983, 7983], "mapped", [7975]], [[7984, 7991], "valid"], [[7992, 7992], "mapped", [7984]], [[7993, 7993], "mapped", [7985]], [[7994, 7994], "mapped", [7986]], [[7995, 7995], "mapped", [7987]], [[7996, 7996], "mapped", [7988]], [[7997, 7997], "mapped", [7989]], [[7998, 7998], "mapped", [7990]], [[7999, 7999], "mapped", [7991]], [[8e3, 8005], "valid"], [[8006, 8007], "disallowed"], [[8008, 8008], "mapped", [8e3]], [[8009, 8009], "mapped", [8001]], [[8010, 8010], "mapped", [8002]], [[8011, 8011], "mapped", [8003]], [[8012, 8012], "mapped", [8004]], [[8013, 8013], "mapped", [8005]], [[8014, 8015], "disallowed"], [[8016, 8023], "valid"], [[8024, 8024], "disallowed"], [[8025, 8025], "mapped", [8017]], [[8026, 8026], "disallowed"], [[8027, 8027], "mapped", [8019]], [[8028, 8028], "disallowed"], [[8029, 8029], "mapped", [8021]], [[8030, 8030], "disallowed"], [[8031, 8031], "mapped", [8023]], [[8032, 8039], "valid"], [[8040, 8040], "mapped", [8032]], [[8041, 8041], "mapped", [8033]], [[8042, 8042], "mapped", [8034]], [[8043, 8043], "mapped", [8035]], [[8044, 8044], "mapped", [8036]], [[8045, 8045], "mapped", [8037]], [[8046, 8046], "mapped", [8038]], [[8047, 8047], "mapped", [8039]], [[8048, 8048], "valid"], [[8049, 8049], "mapped", [940]], [[8050, 8050], "valid"], [[8051, 8051], "mapped", [941]], [[8052, 8052], "valid"], [[8053, 8053], "mapped", [942]], [[8054, 8054], "valid"], [[8055, 8055], "mapped", [943]], [[8056, 8056], "valid"], [[8057, 8057], "mapped", [972]], [[8058, 8058], "valid"], [[8059, 8059], "mapped", [973]], [[8060, 8060], "valid"], [[8061, 8061], "mapped", [974]], [[8062, 8063], "disallowed"], [[8064, 8064], "mapped", [7936, 953]], [[8065, 8065], "mapped", [7937, 953]], [[8066, 8066], "mapped", [7938, 953]], [[8067, 8067], "mapped", [7939, 953]], [[8068, 8068], "mapped", [7940, 953]], [[8069, 8069], "mapped", [7941, 953]], [[8070, 8070], "mapped", [7942, 953]], [[8071, 8071], "mapped", [7943, 953]], [[8072, 8072], "mapped", [7936, 953]], [[8073, 8073], "mapped", [7937, 953]], [[8074, 8074], "mapped", [7938, 953]], [[8075, 8075], "mapped", [7939, 953]], [[8076, 8076], "mapped", [7940, 953]], [[8077, 8077], "mapped", [7941, 953]], [[8078, 8078], "mapped", [7942, 953]], [[8079, 8079], "mapped", [7943, 953]], [[8080, 8080], "mapped", [7968, 953]], [[8081, 8081], "mapped", [7969, 953]], [[8082, 8082], "mapped", [7970, 953]], [[8083, 8083], "mapped", [7971, 953]], [[8084, 8084], "mapped", [7972, 953]], [[8085, 8085], "mapped", [7973, 953]], [[8086, 8086], "mapped", [7974, 953]], [[8087, 8087], "mapped", [7975, 953]], [[8088, 8088], "mapped", [7968, 953]], [[8089, 8089], "mapped", [7969, 953]], [[8090, 8090], "mapped", [7970, 953]], [[8091, 8091], "mapped", [7971, 953]], [[8092, 8092], "mapped", [7972, 953]], [[8093, 8093], "mapped", [7973, 953]], [[8094, 8094], "mapped", [7974, 953]], [[8095, 8095], "mapped", [7975, 953]], [[8096, 8096], "mapped", [8032, 953]], [[8097, 8097], "mapped", [8033, 953]], [[8098, 8098], "mapped", [8034, 953]], [[8099, 8099], "mapped", [8035, 953]], [[8100, 8100], "mapped", [8036, 953]], [[8101, 8101], "mapped", [8037, 953]], [[8102, 8102], "mapped", [8038, 953]], [[8103, 8103], "mapped", [8039, 953]], [[8104, 8104], "mapped", [8032, 953]], [[8105, 8105], "mapped", [8033, 953]], [[8106, 8106], "mapped", [8034, 953]], [[8107, 8107], "mapped", [8035, 953]], [[8108, 8108], "mapped", [8036, 953]], [[8109, 8109], "mapped", [8037, 953]], [[8110, 8110], "mapped", [8038, 953]], [[8111, 8111], "mapped", [8039, 953]], [[8112, 8113], "valid"], [[8114, 8114], "mapped", [8048, 953]], [[8115, 8115], "mapped", [945, 953]], [[8116, 8116], "mapped", [940, 953]], [[8117, 8117], "disallowed"], [[8118, 8118], "valid"], [[8119, 8119], "mapped", [8118, 953]], [[8120, 8120], "mapped", [8112]], [[8121, 8121], "mapped", [8113]], [[8122, 8122], "mapped", [8048]], [[8123, 8123], "mapped", [940]], [[8124, 8124], "mapped", [945, 953]], [[8125, 8125], "disallowed_STD3_mapped", [32, 787]], [[8126, 8126], "mapped", [953]], [[8127, 8127], "disallowed_STD3_mapped", [32, 787]], [[8128, 8128], "disallowed_STD3_mapped", [32, 834]], [[8129, 8129], "disallowed_STD3_mapped", [32, 776, 834]], [[8130, 8130], "mapped", [8052, 953]], [[8131, 8131], "mapped", [951, 953]], [[8132, 8132], "mapped", [942, 953]], [[8133, 8133], "disallowed"], [[8134, 8134], "valid"], [[8135, 8135], "mapped", [8134, 953]], [[8136, 8136], "mapped", [8050]], [[8137, 8137], "mapped", [941]], [[8138, 8138], "mapped", [8052]], [[8139, 8139], "mapped", [942]], [[8140, 8140], "mapped", [951, 953]], [[8141, 8141], "disallowed_STD3_mapped", [32, 787, 768]], [[8142, 8142], "disallowed_STD3_mapped", [32, 787, 769]], [[8143, 8143], "disallowed_STD3_mapped", [32, 787, 834]], [[8144, 8146], "valid"], [[8147, 8147], "mapped", [912]], [[8148, 8149], "disallowed"], [[8150, 8151], "valid"], [[8152, 8152], "mapped", [8144]], [[8153, 8153], "mapped", [8145]], [[8154, 8154], "mapped", [8054]], [[8155, 8155], "mapped", [943]], [[8156, 8156], "disallowed"], [[8157, 8157], "disallowed_STD3_mapped", [32, 788, 768]], [[8158, 8158], "disallowed_STD3_mapped", [32, 788, 769]], [[8159, 8159], "disallowed_STD3_mapped", [32, 788, 834]], [[8160, 8162], "valid"], [[8163, 8163], "mapped", [944]], [[8164, 8167], "valid"], [[8168, 8168], "mapped", [8160]], [[8169, 8169], "mapped", [8161]], [[8170, 8170], "mapped", [8058]], [[8171, 8171], "mapped", [973]], [[8172, 8172], "mapped", [8165]], [[8173, 8173], "disallowed_STD3_mapped", [32, 776, 768]], [[8174, 8174], "disallowed_STD3_mapped", [32, 776, 769]], [[8175, 8175], "disallowed_STD3_mapped", [96]], [[8176, 8177], "disallowed"], [[8178, 8178], "mapped", [8060, 953]], [[8179, 8179], "mapped", [969, 953]], [[8180, 8180], "mapped", [974, 953]], [[8181, 8181], "disallowed"], [[8182, 8182], "valid"], [[8183, 8183], "mapped", [8182, 953]], [[8184, 8184], "mapped", [8056]], [[8185, 8185], "mapped", [972]], [[8186, 8186], "mapped", [8060]], [[8187, 8187], "mapped", [974]], [[8188, 8188], "mapped", [969, 953]], [[8189, 8189], "disallowed_STD3_mapped", [32, 769]], [[8190, 8190], "disallowed_STD3_mapped", [32, 788]], [[8191, 8191], "disallowed"], [[8192, 8202], "disallowed_STD3_mapped", [32]], [[8203, 8203], "ignored"], [[8204, 8205], "deviation", []], [[8206, 8207], "disallowed"], [[8208, 8208], "valid", [], "NV8"], [[8209, 8209], "mapped", [8208]], [[8210, 8214], "valid", [], "NV8"], [[8215, 8215], "disallowed_STD3_mapped", [32, 819]], [[8216, 8227], "valid", [], "NV8"], [[8228, 8230], "disallowed"], [[8231, 8231], "valid", [], "NV8"], [[8232, 8238], "disallowed"], [[8239, 8239], "disallowed_STD3_mapped", [32]], [[8240, 8242], "valid", [], "NV8"], [[8243, 8243], "mapped", [8242, 8242]], [[8244, 8244], "mapped", [8242, 8242, 8242]], [[8245, 8245], "valid", [], "NV8"], [[8246, 8246], "mapped", [8245, 8245]], [[8247, 8247], "mapped", [8245, 8245, 8245]], [[8248, 8251], "valid", [], "NV8"], [[8252, 8252], "disallowed_STD3_mapped", [33, 33]], [[8253, 8253], "valid", [], "NV8"], [[8254, 8254], "disallowed_STD3_mapped", [32, 773]], [[8255, 8262], "valid", [], "NV8"], [[8263, 8263], "disallowed_STD3_mapped", [63, 63]], [[8264, 8264], "disallowed_STD3_mapped", [63, 33]], [[8265, 8265], "disallowed_STD3_mapped", [33, 63]], [[8266, 8269], "valid", [], "NV8"], [[8270, 8274], "valid", [], "NV8"], [[8275, 8276], "valid", [], "NV8"], [[8277, 8278], "valid", [], "NV8"], [[8279, 8279], "mapped", [8242, 8242, 8242, 8242]], [[8280, 8286], "valid", [], "NV8"], [[8287, 8287], "disallowed_STD3_mapped", [32]], [[8288, 8288], "ignored"], [[8289, 8291], "disallowed"], [[8292, 8292], "ignored"], [[8293, 8293], "disallowed"], [[8294, 8297], "disallowed"], [[8298, 8303], "disallowed"], [[8304, 8304], "mapped", [48]], [[8305, 8305], "mapped", [105]], [[8306, 8307], "disallowed"], [[8308, 8308], "mapped", [52]], [[8309, 8309], "mapped", [53]], [[8310, 8310], "mapped", [54]], [[8311, 8311], "mapped", [55]], [[8312, 8312], "mapped", [56]], [[8313, 8313], "mapped", [57]], [[8314, 8314], "disallowed_STD3_mapped", [43]], [[8315, 8315], "mapped", [8722]], [[8316, 8316], "disallowed_STD3_mapped", [61]], [[8317, 8317], "disallowed_STD3_mapped", [40]], [[8318, 8318], "disallowed_STD3_mapped", [41]], [[8319, 8319], "mapped", [110]], [[8320, 8320], "mapped", [48]], [[8321, 8321], "mapped", [49]], [[8322, 8322], "mapped", [50]], [[8323, 8323], "mapped", [51]], [[8324, 8324], "mapped", [52]], [[8325, 8325], "mapped", [53]], [[8326, 8326], "mapped", [54]], [[8327, 8327], "mapped", [55]], [[8328, 8328], "mapped", [56]], [[8329, 8329], "mapped", [57]], [[8330, 8330], "disallowed_STD3_mapped", [43]], [[8331, 8331], "mapped", [8722]], [[8332, 8332], "disallowed_STD3_mapped", [61]], [[8333, 8333], "disallowed_STD3_mapped", [40]], [[8334, 8334], "disallowed_STD3_mapped", [41]], [[8335, 8335], "disallowed"], [[8336, 8336], "mapped", [97]], [[8337, 8337], "mapped", [101]], [[8338, 8338], "mapped", [111]], [[8339, 8339], "mapped", [120]], [[8340, 8340], "mapped", [601]], [[8341, 8341], "mapped", [104]], [[8342, 8342], "mapped", [107]], [[8343, 8343], "mapped", [108]], [[8344, 8344], "mapped", [109]], [[8345, 8345], "mapped", [110]], [[8346, 8346], "mapped", [112]], [[8347, 8347], "mapped", [115]], [[8348, 8348], "mapped", [116]], [[8349, 8351], "disallowed"], [[8352, 8359], "valid", [], "NV8"], [[8360, 8360], "mapped", [114, 115]], [[8361, 8362], "valid", [], "NV8"], [[8363, 8363], "valid", [], "NV8"], [[8364, 8364], "valid", [], "NV8"], [[8365, 8367], "valid", [], "NV8"], [[8368, 8369], "valid", [], "NV8"], [[8370, 8373], "valid", [], "NV8"], [[8374, 8376], "valid", [], "NV8"], [[8377, 8377], "valid", [], "NV8"], [[8378, 8378], "valid", [], "NV8"], [[8379, 8381], "valid", [], "NV8"], [[8382, 8382], "valid", [], "NV8"], [[8383, 8399], "disallowed"], [[8400, 8417], "valid", [], "NV8"], [[8418, 8419], "valid", [], "NV8"], [[8420, 8426], "valid", [], "NV8"], [[8427, 8427], "valid", [], "NV8"], [[8428, 8431], "valid", [], "NV8"], [[8432, 8432], "valid", [], "NV8"], [[8433, 8447], "disallowed"], [[8448, 8448], "disallowed_STD3_mapped", [97, 47, 99]], [[8449, 8449], "disallowed_STD3_mapped", [97, 47, 115]], [[8450, 8450], "mapped", [99]], [[8451, 8451], "mapped", [176, 99]], [[8452, 8452], "valid", [], "NV8"], [[8453, 8453], "disallowed_STD3_mapped", [99, 47, 111]], [[8454, 8454], "disallowed_STD3_mapped", [99, 47, 117]], [[8455, 8455], "mapped", [603]], [[8456, 8456], "valid", [], "NV8"], [[8457, 8457], "mapped", [176, 102]], [[8458, 8458], "mapped", [103]], [[8459, 8462], "mapped", [104]], [[8463, 8463], "mapped", [295]], [[8464, 8465], "mapped", [105]], [[8466, 8467], "mapped", [108]], [[8468, 8468], "valid", [], "NV8"], [[8469, 8469], "mapped", [110]], [[8470, 8470], "mapped", [110, 111]], [[8471, 8472], "valid", [], "NV8"], [[8473, 8473], "mapped", [112]], [[8474, 8474], "mapped", [113]], [[8475, 8477], "mapped", [114]], [[8478, 8479], "valid", [], "NV8"], [[8480, 8480], "mapped", [115, 109]], [[8481, 8481], "mapped", [116, 101, 108]], [[8482, 8482], "mapped", [116, 109]], [[8483, 8483], "valid", [], "NV8"], [[8484, 8484], "mapped", [122]], [[8485, 8485], "valid", [], "NV8"], [[8486, 8486], "mapped", [969]], [[8487, 8487], "valid", [], "NV8"], [[8488, 8488], "mapped", [122]], [[8489, 8489], "valid", [], "NV8"], [[8490, 8490], "mapped", [107]], [[8491, 8491], "mapped", [229]], [[8492, 8492], "mapped", [98]], [[8493, 8493], "mapped", [99]], [[8494, 8494], "valid", [], "NV8"], [[8495, 8496], "mapped", [101]], [[8497, 8497], "mapped", [102]], [[8498, 8498], "disallowed"], [[8499, 8499], "mapped", [109]], [[8500, 8500], "mapped", [111]], [[8501, 8501], "mapped", [1488]], [[8502, 8502], "mapped", [1489]], [[8503, 8503], "mapped", [1490]], [[8504, 8504], "mapped", [1491]], [[8505, 8505], "mapped", [105]], [[8506, 8506], "valid", [], "NV8"], [[8507, 8507], "mapped", [102, 97, 120]], [[8508, 8508], "mapped", [960]], [[8509, 8510], "mapped", [947]], [[8511, 8511], "mapped", [960]], [[8512, 8512], "mapped", [8721]], [[8513, 8516], "valid", [], "NV8"], [[8517, 8518], "mapped", [100]], [[8519, 8519], "mapped", [101]], [[8520, 8520], "mapped", [105]], [[8521, 8521], "mapped", [106]], [[8522, 8523], "valid", [], "NV8"], [[8524, 8524], "valid", [], "NV8"], [[8525, 8525], "valid", [], "NV8"], [[8526, 8526], "valid"], [[8527, 8527], "valid", [], "NV8"], [[8528, 8528], "mapped", [49, 8260, 55]], [[8529, 8529], "mapped", [49, 8260, 57]], [[8530, 8530], "mapped", [49, 8260, 49, 48]], [[8531, 8531], "mapped", [49, 8260, 51]], [[8532, 8532], "mapped", [50, 8260, 51]], [[8533, 8533], "mapped", [49, 8260, 53]], [[8534, 8534], "mapped", [50, 8260, 53]], [[8535, 8535], "mapped", [51, 8260, 53]], [[8536, 8536], "mapped", [52, 8260, 53]], [[8537, 8537], "mapped", [49, 8260, 54]], [[8538, 8538], "mapped", [53, 8260, 54]], [[8539, 8539], "mapped", [49, 8260, 56]], [[8540, 8540], "mapped", [51, 8260, 56]], [[8541, 8541], "mapped", [53, 8260, 56]], [[8542, 8542], "mapped", [55, 8260, 56]], [[8543, 8543], "mapped", [49, 8260]], [[8544, 8544], "mapped", [105]], [[8545, 8545], "mapped", [105, 105]], [[8546, 8546], "mapped", [105, 105, 105]], [[8547, 8547], "mapped", [105, 118]], [[8548, 8548], "mapped", [118]], [[8549, 8549], "mapped", [118, 105]], [[8550, 8550], "mapped", [118, 105, 105]], [[8551, 8551], "mapped", [118, 105, 105, 105]], [[8552, 8552], "mapped", [105, 120]], [[8553, 8553], "mapped", [120]], [[8554, 8554], "mapped", [120, 105]], [[8555, 8555], "mapped", [120, 105, 105]], [[8556, 8556], "mapped", [108]], [[8557, 8557], "mapped", [99]], [[8558, 8558], "mapped", [100]], [[8559, 8559], "mapped", [109]], [[8560, 8560], "mapped", [105]], [[8561, 8561], "mapped", [105, 105]], [[8562, 8562], "mapped", [105, 105, 105]], [[8563, 8563], "mapped", [105, 118]], [[8564, 8564], "mapped", [118]], [[8565, 8565], "mapped", [118, 105]], [[8566, 8566], "mapped", [118, 105, 105]], [[8567, 8567], "mapped", [118, 105, 105, 105]], [[8568, 8568], "mapped", [105, 120]], [[8569, 8569], "mapped", [120]], [[8570, 8570], "mapped", [120, 105]], [[8571, 8571], "mapped", [120, 105, 105]], [[8572, 8572], "mapped", [108]], [[8573, 8573], "mapped", [99]], [[8574, 8574], "mapped", [100]], [[8575, 8575], "mapped", [109]], [[8576, 8578], "valid", [], "NV8"], [[8579, 8579], "disallowed"], [[8580, 8580], "valid"], [[8581, 8584], "valid", [], "NV8"], [[8585, 8585], "mapped", [48, 8260, 51]], [[8586, 8587], "valid", [], "NV8"], [[8588, 8591], "disallowed"], [[8592, 8682], "valid", [], "NV8"], [[8683, 8691], "valid", [], "NV8"], [[8692, 8703], "valid", [], "NV8"], [[8704, 8747], "valid", [], "NV8"], [[8748, 8748], "mapped", [8747, 8747]], [[8749, 8749], "mapped", [8747, 8747, 8747]], [[8750, 8750], "valid", [], "NV8"], [[8751, 8751], "mapped", [8750, 8750]], [[8752, 8752], "mapped", [8750, 8750, 8750]], [[8753, 8799], "valid", [], "NV8"], [[8800, 8800], "disallowed_STD3_valid"], [[8801, 8813], "valid", [], "NV8"], [[8814, 8815], "disallowed_STD3_valid"], [[8816, 8945], "valid", [], "NV8"], [[8946, 8959], "valid", [], "NV8"], [[8960, 8960], "valid", [], "NV8"], [[8961, 8961], "valid", [], "NV8"], [[8962, 9e3], "valid", [], "NV8"], [[9001, 9001], "mapped", [12296]], [[9002, 9002], "mapped", [12297]], [[9003, 9082], "valid", [], "NV8"], [[9083, 9083], "valid", [], "NV8"], [[9084, 9084], "valid", [], "NV8"], [[9085, 9114], "valid", [], "NV8"], [[9115, 9166], "valid", [], "NV8"], [[9167, 9168], "valid", [], "NV8"], [[9169, 9179], "valid", [], "NV8"], [[9180, 9191], "valid", [], "NV8"], [[9192, 9192], "valid", [], "NV8"], [[9193, 9203], "valid", [], "NV8"], [[9204, 9210], "valid", [], "NV8"], [[9211, 9215], "disallowed"], [[9216, 9252], "valid", [], "NV8"], [[9253, 9254], "valid", [], "NV8"], [[9255, 9279], "disallowed"], [[9280, 9290], "valid", [], "NV8"], [[9291, 9311], "disallowed"], [[9312, 9312], "mapped", [49]], [[9313, 9313], "mapped", [50]], [[9314, 9314], "mapped", [51]], [[9315, 9315], "mapped", [52]], [[9316, 9316], "mapped", [53]], [[9317, 9317], "mapped", [54]], [[9318, 9318], "mapped", [55]], [[9319, 9319], "mapped", [56]], [[9320, 9320], "mapped", [57]], [[9321, 9321], "mapped", [49, 48]], [[9322, 9322], "mapped", [49, 49]], [[9323, 9323], "mapped", [49, 50]], [[9324, 9324], "mapped", [49, 51]], [[9325, 9325], "mapped", [49, 52]], [[9326, 9326], "mapped", [49, 53]], [[9327, 9327], "mapped", [49, 54]], [[9328, 9328], "mapped", [49, 55]], [[9329, 9329], "mapped", [49, 56]], [[9330, 9330], "mapped", [49, 57]], [[9331, 9331], "mapped", [50, 48]], [[9332, 9332], "disallowed_STD3_mapped", [40, 49, 41]], [[9333, 9333], "disallowed_STD3_mapped", [40, 50, 41]], [[9334, 9334], "disallowed_STD3_mapped", [40, 51, 41]], [[9335, 9335], "disallowed_STD3_mapped", [40, 52, 41]], [[9336, 9336], "disallowed_STD3_mapped", [40, 53, 41]], [[9337, 9337], "disallowed_STD3_mapped", [40, 54, 41]], [[9338, 9338], "disallowed_STD3_mapped", [40, 55, 41]], [[9339, 9339], "disallowed_STD3_mapped", [40, 56, 41]], [[9340, 9340], "disallowed_STD3_mapped", [40, 57, 41]], [[9341, 9341], "disallowed_STD3_mapped", [40, 49, 48, 41]], [[9342, 9342], "disallowed_STD3_mapped", [40, 49, 49, 41]], [[9343, 9343], "disallowed_STD3_mapped", [40, 49, 50, 41]], [[9344, 9344], "disallowed_STD3_mapped", [40, 49, 51, 41]], [[9345, 9345], "disallowed_STD3_mapped", [40, 49, 52, 41]], [[9346, 9346], "disallowed_STD3_mapped", [40, 49, 53, 41]], [[9347, 9347], "disallowed_STD3_mapped", [40, 49, 54, 41]], [[9348, 9348], "disallowed_STD3_mapped", [40, 49, 55, 41]], [[9349, 9349], "disallowed_STD3_mapped", [40, 49, 56, 41]], [[9350, 9350], "disallowed_STD3_mapped", [40, 49, 57, 41]], [[9351, 9351], "disallowed_STD3_mapped", [40, 50, 48, 41]], [[9352, 9371], "disallowed"], [[9372, 9372], "disallowed_STD3_mapped", [40, 97, 41]], [[9373, 9373], "disallowed_STD3_mapped", [40, 98, 41]], [[9374, 9374], "disallowed_STD3_mapped", [40, 99, 41]], [[9375, 9375], "disallowed_STD3_mapped", [40, 100, 41]], [[9376, 9376], "disallowed_STD3_mapped", [40, 101, 41]], [[9377, 9377], "disallowed_STD3_mapped", [40, 102, 41]], [[9378, 9378], "disallowed_STD3_mapped", [40, 103, 41]], [[9379, 9379], "disallowed_STD3_mapped", [40, 104, 41]], [[9380, 9380], "disallowed_STD3_mapped", [40, 105, 41]], [[9381, 9381], "disallowed_STD3_mapped", [40, 106, 41]], [[9382, 9382], "disallowed_STD3_mapped", [40, 107, 41]], [[9383, 9383], "disallowed_STD3_mapped", [40, 108, 41]], [[9384, 9384], "disallowed_STD3_mapped", [40, 109, 41]], [[9385, 9385], "disallowed_STD3_mapped", [40, 110, 41]], [[9386, 9386], "disallowed_STD3_mapped", [40, 111, 41]], [[9387, 9387], "disallowed_STD3_mapped", [40, 112, 41]], [[9388, 9388], "disallowed_STD3_mapped", [40, 113, 41]], [[9389, 9389], "disallowed_STD3_mapped", [40, 114, 41]], [[9390, 9390], "disallowed_STD3_mapped", [40, 115, 41]], [[9391, 9391], "disallowed_STD3_mapped", [40, 116, 41]], [[9392, 9392], "disallowed_STD3_mapped", [40, 117, 41]], [[9393, 9393], "disallowed_STD3_mapped", [40, 118, 41]], [[9394, 9394], "disallowed_STD3_mapped", [40, 119, 41]], [[9395, 9395], "disallowed_STD3_mapped", [40, 120, 41]], [[9396, 9396], "disallowed_STD3_mapped", [40, 121, 41]], [[9397, 9397], "disallowed_STD3_mapped", [40, 122, 41]], [[9398, 9398], "mapped", [97]], [[9399, 9399], "mapped", [98]], [[9400, 9400], "mapped", [99]], [[9401, 9401], "mapped", [100]], [[9402, 9402], "mapped", [101]], [[9403, 9403], "mapped", [102]], [[9404, 9404], "mapped", [103]], [[9405, 9405], "mapped", [104]], [[9406, 9406], "mapped", [105]], [[9407, 9407], "mapped", [106]], [[9408, 9408], "mapped", [107]], [[9409, 9409], "mapped", [108]], [[9410, 9410], "mapped", [109]], [[9411, 9411], "mapped", [110]], [[9412, 9412], "mapped", [111]], [[9413, 9413], "mapped", [112]], [[9414, 9414], "mapped", [113]], [[9415, 9415], "mapped", [114]], [[9416, 9416], "mapped", [115]], [[9417, 9417], "mapped", [116]], [[9418, 9418], "mapped", [117]], [[9419, 9419], "mapped", [118]], [[9420, 9420], "mapped", [119]], [[9421, 9421], "mapped", [120]], [[9422, 9422], "mapped", [121]], [[9423, 9423], "mapped", [122]], [[9424, 9424], "mapped", [97]], [[9425, 9425], "mapped", [98]], [[9426, 9426], "mapped", [99]], [[9427, 9427], "mapped", [100]], [[9428, 9428], "mapped", [101]], [[9429, 9429], "mapped", [102]], [[9430, 9430], "mapped", [103]], [[9431, 9431], "mapped", [104]], [[9432, 9432], "mapped", [105]], [[9433, 9433], "mapped", [106]], [[9434, 9434], "mapped", [107]], [[9435, 9435], "mapped", [108]], [[9436, 9436], "mapped", [109]], [[9437, 9437], "mapped", [110]], [[9438, 9438], "mapped", [111]], [[9439, 9439], "mapped", [112]], [[9440, 9440], "mapped", [113]], [[9441, 9441], "mapped", [114]], [[9442, 9442], "mapped", [115]], [[9443, 9443], "mapped", [116]], [[9444, 9444], "mapped", [117]], [[9445, 9445], "mapped", [118]], [[9446, 9446], "mapped", [119]], [[9447, 9447], "mapped", [120]], [[9448, 9448], "mapped", [121]], [[9449, 9449], "mapped", [122]], [[9450, 9450], "mapped", [48]], [[9451, 9470], "valid", [], "NV8"], [[9471, 9471], "valid", [], "NV8"], [[9472, 9621], "valid", [], "NV8"], [[9622, 9631], "valid", [], "NV8"], [[9632, 9711], "valid", [], "NV8"], [[9712, 9719], "valid", [], "NV8"], [[9720, 9727], "valid", [], "NV8"], [[9728, 9747], "valid", [], "NV8"], [[9748, 9749], "valid", [], "NV8"], [[9750, 9751], "valid", [], "NV8"], [[9752, 9752], "valid", [], "NV8"], [[9753, 9753], "valid", [], "NV8"], [[9754, 9839], "valid", [], "NV8"], [[9840, 9841], "valid", [], "NV8"], [[9842, 9853], "valid", [], "NV8"], [[9854, 9855], "valid", [], "NV8"], [[9856, 9865], "valid", [], "NV8"], [[9866, 9873], "valid", [], "NV8"], [[9874, 9884], "valid", [], "NV8"], [[9885, 9885], "valid", [], "NV8"], [[9886, 9887], "valid", [], "NV8"], [[9888, 9889], "valid", [], "NV8"], [[9890, 9905], "valid", [], "NV8"], [[9906, 9906], "valid", [], "NV8"], [[9907, 9916], "valid", [], "NV8"], [[9917, 9919], "valid", [], "NV8"], [[9920, 9923], "valid", [], "NV8"], [[9924, 9933], "valid", [], "NV8"], [[9934, 9934], "valid", [], "NV8"], [[9935, 9953], "valid", [], "NV8"], [[9954, 9954], "valid", [], "NV8"], [[9955, 9955], "valid", [], "NV8"], [[9956, 9959], "valid", [], "NV8"], [[9960, 9983], "valid", [], "NV8"], [[9984, 9984], "valid", [], "NV8"], [[9985, 9988], "valid", [], "NV8"], [[9989, 9989], "valid", [], "NV8"], [[9990, 9993], "valid", [], "NV8"], [[9994, 9995], "valid", [], "NV8"], [[9996, 10023], "valid", [], "NV8"], [[10024, 10024], "valid", [], "NV8"], [[10025, 10059], "valid", [], "NV8"], [[10060, 10060], "valid", [], "NV8"], [[10061, 10061], "valid", [], "NV8"], [[10062, 10062], "valid", [], "NV8"], [[10063, 10066], "valid", [], "NV8"], [[10067, 10069], "valid", [], "NV8"], [[10070, 10070], "valid", [], "NV8"], [[10071, 10071], "valid", [], "NV8"], [[10072, 10078], "valid", [], "NV8"], [[10079, 10080], "valid", [], "NV8"], [[10081, 10087], "valid", [], "NV8"], [[10088, 10101], "valid", [], "NV8"], [[10102, 10132], "valid", [], "NV8"], [[10133, 10135], "valid", [], "NV8"], [[10136, 10159], "valid", [], "NV8"], [[10160, 10160], "valid", [], "NV8"], [[10161, 10174], "valid", [], "NV8"], [[10175, 10175], "valid", [], "NV8"], [[10176, 10182], "valid", [], "NV8"], [[10183, 10186], "valid", [], "NV8"], [[10187, 10187], "valid", [], "NV8"], [[10188, 10188], "valid", [], "NV8"], [[10189, 10189], "valid", [], "NV8"], [[10190, 10191], "valid", [], "NV8"], [[10192, 10219], "valid", [], "NV8"], [[10220, 10223], "valid", [], "NV8"], [[10224, 10239], "valid", [], "NV8"], [[10240, 10495], "valid", [], "NV8"], [[10496, 10763], "valid", [], "NV8"], [[10764, 10764], "mapped", [8747, 8747, 8747, 8747]], [[10765, 10867], "valid", [], "NV8"], [[10868, 10868], "disallowed_STD3_mapped", [58, 58, 61]], [[10869, 10869], "disallowed_STD3_mapped", [61, 61]], [[10870, 10870], "disallowed_STD3_mapped", [61, 61, 61]], [[10871, 10971], "valid", [], "NV8"], [[10972, 10972], "mapped", [10973, 824]], [[10973, 11007], "valid", [], "NV8"], [[11008, 11021], "valid", [], "NV8"], [[11022, 11027], "valid", [], "NV8"], [[11028, 11034], "valid", [], "NV8"], [[11035, 11039], "valid", [], "NV8"], [[11040, 11043], "valid", [], "NV8"], [[11044, 11084], "valid", [], "NV8"], [[11085, 11087], "valid", [], "NV8"], [[11088, 11092], "valid", [], "NV8"], [[11093, 11097], "valid", [], "NV8"], [[11098, 11123], "valid", [], "NV8"], [[11124, 11125], "disallowed"], [[11126, 11157], "valid", [], "NV8"], [[11158, 11159], "disallowed"], [[11160, 11193], "valid", [], "NV8"], [[11194, 11196], "disallowed"], [[11197, 11208], "valid", [], "NV8"], [[11209, 11209], "disallowed"], [[11210, 11217], "valid", [], "NV8"], [[11218, 11243], "disallowed"], [[11244, 11247], "valid", [], "NV8"], [[11248, 11263], "disallowed"], [[11264, 11264], "mapped", [11312]], [[11265, 11265], "mapped", [11313]], [[11266, 11266], "mapped", [11314]], [[11267, 11267], "mapped", [11315]], [[11268, 11268], "mapped", [11316]], [[11269, 11269], "mapped", [11317]], [[11270, 11270], "mapped", [11318]], [[11271, 11271], "mapped", [11319]], [[11272, 11272], "mapped", [11320]], [[11273, 11273], "mapped", [11321]], [[11274, 11274], "mapped", [11322]], [[11275, 11275], "mapped", [11323]], [[11276, 11276], "mapped", [11324]], [[11277, 11277], "mapped", [11325]], [[11278, 11278], "mapped", [11326]], [[11279, 11279], "mapped", [11327]], [[11280, 11280], "mapped", [11328]], [[11281, 11281], "mapped", [11329]], [[11282, 11282], "mapped", [11330]], [[11283, 11283], "mapped", [11331]], [[11284, 11284], "mapped", [11332]], [[11285, 11285], "mapped", [11333]], [[11286, 11286], "mapped", [11334]], [[11287, 11287], "mapped", [11335]], [[11288, 11288], "mapped", [11336]], [[11289, 11289], "mapped", [11337]], [[11290, 11290], "mapped", [11338]], [[11291, 11291], "mapped", [11339]], [[11292, 11292], "mapped", [11340]], [[11293, 11293], "mapped", [11341]], [[11294, 11294], "mapped", [11342]], [[11295, 11295], "mapped", [11343]], [[11296, 11296], "mapped", [11344]], [[11297, 11297], "mapped", [11345]], [[11298, 11298], "mapped", [11346]], [[11299, 11299], "mapped", [11347]], [[11300, 11300], "mapped", [11348]], [[11301, 11301], "mapped", [11349]], [[11302, 11302], "mapped", [11350]], [[11303, 11303], "mapped", [11351]], [[11304, 11304], "mapped", [11352]], [[11305, 11305], "mapped", [11353]], [[11306, 11306], "mapped", [11354]], [[11307, 11307], "mapped", [11355]], [[11308, 11308], "mapped", [11356]], [[11309, 11309], "mapped", [11357]], [[11310, 11310], "mapped", [11358]], [[11311, 11311], "disallowed"], [[11312, 11358], "valid"], [[11359, 11359], "disallowed"], [[11360, 11360], "mapped", [11361]], [[11361, 11361], "valid"], [[11362, 11362], "mapped", [619]], [[11363, 11363], "mapped", [7549]], [[11364, 11364], "mapped", [637]], [[11365, 11366], "valid"], [[11367, 11367], "mapped", [11368]], [[11368, 11368], "valid"], [[11369, 11369], "mapped", [11370]], [[11370, 11370], "valid"], [[11371, 11371], "mapped", [11372]], [[11372, 11372], "valid"], [[11373, 11373], "mapped", [593]], [[11374, 11374], "mapped", [625]], [[11375, 11375], "mapped", [592]], [[11376, 11376], "mapped", [594]], [[11377, 11377], "valid"], [[11378, 11378], "mapped", [11379]], [[11379, 11379], "valid"], [[11380, 11380], "valid"], [[11381, 11381], "mapped", [11382]], [[11382, 11383], "valid"], [[11384, 11387], "valid"], [[11388, 11388], "mapped", [106]], [[11389, 11389], "mapped", [118]], [[11390, 11390], "mapped", [575]], [[11391, 11391], "mapped", [576]], [[11392, 11392], "mapped", [11393]], [[11393, 11393], "valid"], [[11394, 11394], "mapped", [11395]], [[11395, 11395], "valid"], [[11396, 11396], "mapped", [11397]], [[11397, 11397], "valid"], [[11398, 11398], "mapped", [11399]], [[11399, 11399], "valid"], [[11400, 11400], "mapped", [11401]], [[11401, 11401], "valid"], [[11402, 11402], "mapped", [11403]], [[11403, 11403], "valid"], [[11404, 11404], "mapped", [11405]], [[11405, 11405], "valid"], [[11406, 11406], "mapped", [11407]], [[11407, 11407], "valid"], [[11408, 11408], "mapped", [11409]], [[11409, 11409], "valid"], [[11410, 11410], "mapped", [11411]], [[11411, 11411], "valid"], [[11412, 11412], "mapped", [11413]], [[11413, 11413], "valid"], [[11414, 11414], "mapped", [11415]], [[11415, 11415], "valid"], [[11416, 11416], "mapped", [11417]], [[11417, 11417], "valid"], [[11418, 11418], "mapped", [11419]], [[11419, 11419], "valid"], [[11420, 11420], "mapped", [11421]], [[11421, 11421], "valid"], [[11422, 11422], "mapped", [11423]], [[11423, 11423], "valid"], [[11424, 11424], "mapped", [11425]], [[11425, 11425], "valid"], [[11426, 11426], "mapped", [11427]], [[11427, 11427], "valid"], [[11428, 11428], "mapped", [11429]], [[11429, 11429], "valid"], [[11430, 11430], "mapped", [11431]], [[11431, 11431], "valid"], [[11432, 11432], "mapped", [11433]], [[11433, 11433], "valid"], [[11434, 11434], "mapped", [11435]], [[11435, 11435], "valid"], [[11436, 11436], "mapped", [11437]], [[11437, 11437], "valid"], [[11438, 11438], "mapped", [11439]], [[11439, 11439], "valid"], [[11440, 11440], "mapped", [11441]], [[11441, 11441], "valid"], [[11442, 11442], "mapped", [11443]], [[11443, 11443], "valid"], [[11444, 11444], "mapped", [11445]], [[11445, 11445], "valid"], [[11446, 11446], "mapped", [11447]], [[11447, 11447], "valid"], [[11448, 11448], "mapped", [11449]], [[11449, 11449], "valid"], [[11450, 11450], "mapped", [11451]], [[11451, 11451], "valid"], [[11452, 11452], "mapped", [11453]], [[11453, 11453], "valid"], [[11454, 11454], "mapped", [11455]], [[11455, 11455], "valid"], [[11456, 11456], "mapped", [11457]], [[11457, 11457], "valid"], [[11458, 11458], "mapped", [11459]], [[11459, 11459], "valid"], [[11460, 11460], "mapped", [11461]], [[11461, 11461], "valid"], [[11462, 11462], "mapped", [11463]], [[11463, 11463], "valid"], [[11464, 11464], "mapped", [11465]], [[11465, 11465], "valid"], [[11466, 11466], "mapped", [11467]], [[11467, 11467], "valid"], [[11468, 11468], "mapped", [11469]], [[11469, 11469], "valid"], [[11470, 11470], "mapped", [11471]], [[11471, 11471], "valid"], [[11472, 11472], "mapped", [11473]], [[11473, 11473], "valid"], [[11474, 11474], "mapped", [11475]], [[11475, 11475], "valid"], [[11476, 11476], "mapped", [11477]], [[11477, 11477], "valid"], [[11478, 11478], "mapped", [11479]], [[11479, 11479], "valid"], [[11480, 11480], "mapped", [11481]], [[11481, 11481], "valid"], [[11482, 11482], "mapped", [11483]], [[11483, 11483], "valid"], [[11484, 11484], "mapped", [11485]], [[11485, 11485], "valid"], [[11486, 11486], "mapped", [11487]], [[11487, 11487], "valid"], [[11488, 11488], "mapped", [11489]], [[11489, 11489], "valid"], [[11490, 11490], "mapped", [11491]], [[11491, 11492], "valid"], [[11493, 11498], "valid", [], "NV8"], [[11499, 11499], "mapped", [11500]], [[11500, 11500], "valid"], [[11501, 11501], "mapped", [11502]], [[11502, 11505], "valid"], [[11506, 11506], "mapped", [11507]], [[11507, 11507], "valid"], [[11508, 11512], "disallowed"], [[11513, 11519], "valid", [], "NV8"], [[11520, 11557], "valid"], [[11558, 11558], "disallowed"], [[11559, 11559], "valid"], [[11560, 11564], "disallowed"], [[11565, 11565], "valid"], [[11566, 11567], "disallowed"], [[11568, 11621], "valid"], [[11622, 11623], "valid"], [[11624, 11630], "disallowed"], [[11631, 11631], "mapped", [11617]], [[11632, 11632], "valid", [], "NV8"], [[11633, 11646], "disallowed"], [[11647, 11647], "valid"], [[11648, 11670], "valid"], [[11671, 11679], "disallowed"], [[11680, 11686], "valid"], [[11687, 11687], "disallowed"], [[11688, 11694], "valid"], [[11695, 11695], "disallowed"], [[11696, 11702], "valid"], [[11703, 11703], "disallowed"], [[11704, 11710], "valid"], [[11711, 11711], "disallowed"], [[11712, 11718], "valid"], [[11719, 11719], "disallowed"], [[11720, 11726], "valid"], [[11727, 11727], "disallowed"], [[11728, 11734], "valid"], [[11735, 11735], "disallowed"], [[11736, 11742], "valid"], [[11743, 11743], "disallowed"], [[11744, 11775], "valid"], [[11776, 11799], "valid", [], "NV8"], [[11800, 11803], "valid", [], "NV8"], [[11804, 11805], "valid", [], "NV8"], [[11806, 11822], "valid", [], "NV8"], [[11823, 11823], "valid"], [[11824, 11824], "valid", [], "NV8"], [[11825, 11825], "valid", [], "NV8"], [[11826, 11835], "valid", [], "NV8"], [[11836, 11842], "valid", [], "NV8"], [[11843, 11903], "disallowed"], [[11904, 11929], "valid", [], "NV8"], [[11930, 11930], "disallowed"], [[11931, 11934], "valid", [], "NV8"], [[11935, 11935], "mapped", [27597]], [[11936, 12018], "valid", [], "NV8"], [[12019, 12019], "mapped", [40863]], [[12020, 12031], "disallowed"], [[12032, 12032], "mapped", [19968]], [[12033, 12033], "mapped", [20008]], [[12034, 12034], "mapped", [20022]], [[12035, 12035], "mapped", [20031]], [[12036, 12036], "mapped", [20057]], [[12037, 12037], "mapped", [20101]], [[12038, 12038], "mapped", [20108]], [[12039, 12039], "mapped", [20128]], [[12040, 12040], "mapped", [20154]], [[12041, 12041], "mapped", [20799]], [[12042, 12042], "mapped", [20837]], [[12043, 12043], "mapped", [20843]], [[12044, 12044], "mapped", [20866]], [[12045, 12045], "mapped", [20886]], [[12046, 12046], "mapped", [20907]], [[12047, 12047], "mapped", [20960]], [[12048, 12048], "mapped", [20981]], [[12049, 12049], "mapped", [20992]], [[12050, 12050], "mapped", [21147]], [[12051, 12051], "mapped", [21241]], [[12052, 12052], "mapped", [21269]], [[12053, 12053], "mapped", [21274]], [[12054, 12054], "mapped", [21304]], [[12055, 12055], "mapped", [21313]], [[12056, 12056], "mapped", [21340]], [[12057, 12057], "mapped", [21353]], [[12058, 12058], "mapped", [21378]], [[12059, 12059], "mapped", [21430]], [[12060, 12060], "mapped", [21448]], [[12061, 12061], "mapped", [21475]], [[12062, 12062], "mapped", [22231]], [[12063, 12063], "mapped", [22303]], [[12064, 12064], "mapped", [22763]], [[12065, 12065], "mapped", [22786]], [[12066, 12066], "mapped", [22794]], [[12067, 12067], "mapped", [22805]], [[12068, 12068], "mapped", [22823]], [[12069, 12069], "mapped", [22899]], [[12070, 12070], "mapped", [23376]], [[12071, 12071], "mapped", [23424]], [[12072, 12072], "mapped", [23544]], [[12073, 12073], "mapped", [23567]], [[12074, 12074], "mapped", [23586]], [[12075, 12075], "mapped", [23608]], [[12076, 12076], "mapped", [23662]], [[12077, 12077], "mapped", [23665]], [[12078, 12078], "mapped", [24027]], [[12079, 12079], "mapped", [24037]], [[12080, 12080], "mapped", [24049]], [[12081, 12081], "mapped", [24062]], [[12082, 12082], "mapped", [24178]], [[12083, 12083], "mapped", [24186]], [[12084, 12084], "mapped", [24191]], [[12085, 12085], "mapped", [24308]], [[12086, 12086], "mapped", [24318]], [[12087, 12087], "mapped", [24331]], [[12088, 12088], "mapped", [24339]], [[12089, 12089], "mapped", [24400]], [[12090, 12090], "mapped", [24417]], [[12091, 12091], "mapped", [24435]], [[12092, 12092], "mapped", [24515]], [[12093, 12093], "mapped", [25096]], [[12094, 12094], "mapped", [25142]], [[12095, 12095], "mapped", [25163]], [[12096, 12096], "mapped", [25903]], [[12097, 12097], "mapped", [25908]], [[12098, 12098], "mapped", [25991]], [[12099, 12099], "mapped", [26007]], [[12100, 12100], "mapped", [26020]], [[12101, 12101], "mapped", [26041]], [[12102, 12102], "mapped", [26080]], [[12103, 12103], "mapped", [26085]], [[12104, 12104], "mapped", [26352]], [[12105, 12105], "mapped", [26376]], [[12106, 12106], "mapped", [26408]], [[12107, 12107], "mapped", [27424]], [[12108, 12108], "mapped", [27490]], [[12109, 12109], "mapped", [27513]], [[12110, 12110], "mapped", [27571]], [[12111, 12111], "mapped", [27595]], [[12112, 12112], "mapped", [27604]], [[12113, 12113], "mapped", [27611]], [[12114, 12114], "mapped", [27663]], [[12115, 12115], "mapped", [27668]], [[12116, 12116], "mapped", [27700]], [[12117, 12117], "mapped", [28779]], [[12118, 12118], "mapped", [29226]], [[12119, 12119], "mapped", [29238]], [[12120, 12120], "mapped", [29243]], [[12121, 12121], "mapped", [29247]], [[12122, 12122], "mapped", [29255]], [[12123, 12123], "mapped", [29273]], [[12124, 12124], "mapped", [29275]], [[12125, 12125], "mapped", [29356]], [[12126, 12126], "mapped", [29572]], [[12127, 12127], "mapped", [29577]], [[12128, 12128], "mapped", [29916]], [[12129, 12129], "mapped", [29926]], [[12130, 12130], "mapped", [29976]], [[12131, 12131], "mapped", [29983]], [[12132, 12132], "mapped", [29992]], [[12133, 12133], "mapped", [3e4]], [[12134, 12134], "mapped", [30091]], [[12135, 12135], "mapped", [30098]], [[12136, 12136], "mapped", [30326]], [[12137, 12137], "mapped", [30333]], [[12138, 12138], "mapped", [30382]], [[12139, 12139], "mapped", [30399]], [[12140, 12140], "mapped", [30446]], [[12141, 12141], "mapped", [30683]], [[12142, 12142], "mapped", [30690]], [[12143, 12143], "mapped", [30707]], [[12144, 12144], "mapped", [31034]], [[12145, 12145], "mapped", [31160]], [[12146, 12146], "mapped", [31166]], [[12147, 12147], "mapped", [31348]], [[12148, 12148], "mapped", [31435]], [[12149, 12149], "mapped", [31481]], [[12150, 12150], "mapped", [31859]], [[12151, 12151], "mapped", [31992]], [[12152, 12152], "mapped", [32566]], [[12153, 12153], "mapped", [32593]], [[12154, 12154], "mapped", [32650]], [[12155, 12155], "mapped", [32701]], [[12156, 12156], "mapped", [32769]], [[12157, 12157], "mapped", [32780]], [[12158, 12158], "mapped", [32786]], [[12159, 12159], "mapped", [32819]], [[12160, 12160], "mapped", [32895]], [[12161, 12161], "mapped", [32905]], [[12162, 12162], "mapped", [33251]], [[12163, 12163], "mapped", [33258]], [[12164, 12164], "mapped", [33267]], [[12165, 12165], "mapped", [33276]], [[12166, 12166], "mapped", [33292]], [[12167, 12167], "mapped", [33307]], [[12168, 12168], "mapped", [33311]], [[12169, 12169], "mapped", [33390]], [[12170, 12170], "mapped", [33394]], [[12171, 12171], "mapped", [33400]], [[12172, 12172], "mapped", [34381]], [[12173, 12173], "mapped", [34411]], [[12174, 12174], "mapped", [34880]], [[12175, 12175], "mapped", [34892]], [[12176, 12176], "mapped", [34915]], [[12177, 12177], "mapped", [35198]], [[12178, 12178], "mapped", [35211]], [[12179, 12179], "mapped", [35282]], [[12180, 12180], "mapped", [35328]], [[12181, 12181], "mapped", [35895]], [[12182, 12182], "mapped", [35910]], [[12183, 12183], "mapped", [35925]], [[12184, 12184], "mapped", [35960]], [[12185, 12185], "mapped", [35997]], [[12186, 12186], "mapped", [36196]], [[12187, 12187], "mapped", [36208]], [[12188, 12188], "mapped", [36275]], [[12189, 12189], "mapped", [36523]], [[12190, 12190], "mapped", [36554]], [[12191, 12191], "mapped", [36763]], [[12192, 12192], "mapped", [36784]], [[12193, 12193], "mapped", [36789]], [[12194, 12194], "mapped", [37009]], [[12195, 12195], "mapped", [37193]], [[12196, 12196], "mapped", [37318]], [[12197, 12197], "mapped", [37324]], [[12198, 12198], "mapped", [37329]], [[12199, 12199], "mapped", [38263]], [[12200, 12200], "mapped", [38272]], [[12201, 12201], "mapped", [38428]], [[12202, 12202], "mapped", [38582]], [[12203, 12203], "mapped", [38585]], [[12204, 12204], "mapped", [38632]], [[12205, 12205], "mapped", [38737]], [[12206, 12206], "mapped", [38750]], [[12207, 12207], "mapped", [38754]], [[12208, 12208], "mapped", [38761]], [[12209, 12209], "mapped", [38859]], [[12210, 12210], "mapped", [38893]], [[12211, 12211], "mapped", [38899]], [[12212, 12212], "mapped", [38913]], [[12213, 12213], "mapped", [39080]], [[12214, 12214], "mapped", [39131]], [[12215, 12215], "mapped", [39135]], [[12216, 12216], "mapped", [39318]], [[12217, 12217], "mapped", [39321]], [[12218, 12218], "mapped", [39340]], [[12219, 12219], "mapped", [39592]], [[12220, 12220], "mapped", [39640]], [[12221, 12221], "mapped", [39647]], [[12222, 12222], "mapped", [39717]], [[12223, 12223], "mapped", [39727]], [[12224, 12224], "mapped", [39730]], [[12225, 12225], "mapped", [39740]], [[12226, 12226], "mapped", [39770]], [[12227, 12227], "mapped", [40165]], [[12228, 12228], "mapped", [40565]], [[12229, 12229], "mapped", [40575]], [[12230, 12230], "mapped", [40613]], [[12231, 12231], "mapped", [40635]], [[12232, 12232], "mapped", [40643]], [[12233, 12233], "mapped", [40653]], [[12234, 12234], "mapped", [40657]], [[12235, 12235], "mapped", [40697]], [[12236, 12236], "mapped", [40701]], [[12237, 12237], "mapped", [40718]], [[12238, 12238], "mapped", [40723]], [[12239, 12239], "mapped", [40736]], [[12240, 12240], "mapped", [40763]], [[12241, 12241], "mapped", [40778]], [[12242, 12242], "mapped", [40786]], [[12243, 12243], "mapped", [40845]], [[12244, 12244], "mapped", [40860]], [[12245, 12245], "mapped", [40864]], [[12246, 12271], "disallowed"], [[12272, 12283], "disallowed"], [[12284, 12287], "disallowed"], [[12288, 12288], "disallowed_STD3_mapped", [32]], [[12289, 12289], "valid", [], "NV8"], [[12290, 12290], "mapped", [46]], [[12291, 12292], "valid", [], "NV8"], [[12293, 12295], "valid"], [[12296, 12329], "valid", [], "NV8"], [[12330, 12333], "valid"], [[12334, 12341], "valid", [], "NV8"], [[12342, 12342], "mapped", [12306]], [[12343, 12343], "valid", [], "NV8"], [[12344, 12344], "mapped", [21313]], [[12345, 12345], "mapped", [21316]], [[12346, 12346], "mapped", [21317]], [[12347, 12347], "valid", [], "NV8"], [[12348, 12348], "valid"], [[12349, 12349], "valid", [], "NV8"], [[12350, 12350], "valid", [], "NV8"], [[12351, 12351], "valid", [], "NV8"], [[12352, 12352], "disallowed"], [[12353, 12436], "valid"], [[12437, 12438], "valid"], [[12439, 12440], "disallowed"], [[12441, 12442], "valid"], [[12443, 12443], "disallowed_STD3_mapped", [32, 12441]], [[12444, 12444], "disallowed_STD3_mapped", [32, 12442]], [[12445, 12446], "valid"], [[12447, 12447], "mapped", [12424, 12426]], [[12448, 12448], "valid", [], "NV8"], [[12449, 12542], "valid"], [[12543, 12543], "mapped", [12467, 12488]], [[12544, 12548], "disallowed"], [[12549, 12588], "valid"], [[12589, 12589], "valid"], [[12590, 12592], "disallowed"], [[12593, 12593], "mapped", [4352]], [[12594, 12594], "mapped", [4353]], [[12595, 12595], "mapped", [4522]], [[12596, 12596], "mapped", [4354]], [[12597, 12597], "mapped", [4524]], [[12598, 12598], "mapped", [4525]], [[12599, 12599], "mapped", [4355]], [[12600, 12600], "mapped", [4356]], [[12601, 12601], "mapped", [4357]], [[12602, 12602], "mapped", [4528]], [[12603, 12603], "mapped", [4529]], [[12604, 12604], "mapped", [4530]], [[12605, 12605], "mapped", [4531]], [[12606, 12606], "mapped", [4532]], [[12607, 12607], "mapped", [4533]], [[12608, 12608], "mapped", [4378]], [[12609, 12609], "mapped", [4358]], [[12610, 12610], "mapped", [4359]], [[12611, 12611], "mapped", [4360]], [[12612, 12612], "mapped", [4385]], [[12613, 12613], "mapped", [4361]], [[12614, 12614], "mapped", [4362]], [[12615, 12615], "mapped", [4363]], [[12616, 12616], "mapped", [4364]], [[12617, 12617], "mapped", [4365]], [[12618, 12618], "mapped", [4366]], [[12619, 12619], "mapped", [4367]], [[12620, 12620], "mapped", [4368]], [[12621, 12621], "mapped", [4369]], [[12622, 12622], "mapped", [4370]], [[12623, 12623], "mapped", [4449]], [[12624, 12624], "mapped", [4450]], [[12625, 12625], "mapped", [4451]], [[12626, 12626], "mapped", [4452]], [[12627, 12627], "mapped", [4453]], [[12628, 12628], "mapped", [4454]], [[12629, 12629], "mapped", [4455]], [[12630, 12630], "mapped", [4456]], [[12631, 12631], "mapped", [4457]], [[12632, 12632], "mapped", [4458]], [[12633, 12633], "mapped", [4459]], [[12634, 12634], "mapped", [4460]], [[12635, 12635], "mapped", [4461]], [[12636, 12636], "mapped", [4462]], [[12637, 12637], "mapped", [4463]], [[12638, 12638], "mapped", [4464]], [[12639, 12639], "mapped", [4465]], [[12640, 12640], "mapped", [4466]], [[12641, 12641], "mapped", [4467]], [[12642, 12642], "mapped", [4468]], [[12643, 12643], "mapped", [4469]], [[12644, 12644], "disallowed"], [[12645, 12645], "mapped", [4372]], [[12646, 12646], "mapped", [4373]], [[12647, 12647], "mapped", [4551]], [[12648, 12648], "mapped", [4552]], [[12649, 12649], "mapped", [4556]], [[12650, 12650], "mapped", [4558]], [[12651, 12651], "mapped", [4563]], [[12652, 12652], "mapped", [4567]], [[12653, 12653], "mapped", [4569]], [[12654, 12654], "mapped", [4380]], [[12655, 12655], "mapped", [4573]], [[12656, 12656], "mapped", [4575]], [[12657, 12657], "mapped", [4381]], [[12658, 12658], "mapped", [4382]], [[12659, 12659], "mapped", [4384]], [[12660, 12660], "mapped", [4386]], [[12661, 12661], "mapped", [4387]], [[12662, 12662], "mapped", [4391]], [[12663, 12663], "mapped", [4393]], [[12664, 12664], "mapped", [4395]], [[12665, 12665], "mapped", [4396]], [[12666, 12666], "mapped", [4397]], [[12667, 12667], "mapped", [4398]], [[12668, 12668], "mapped", [4399]], [[12669, 12669], "mapped", [4402]], [[12670, 12670], "mapped", [4406]], [[12671, 12671], "mapped", [4416]], [[12672, 12672], "mapped", [4423]], [[12673, 12673], "mapped", [4428]], [[12674, 12674], "mapped", [4593]], [[12675, 12675], "mapped", [4594]], [[12676, 12676], "mapped", [4439]], [[12677, 12677], "mapped", [4440]], [[12678, 12678], "mapped", [4441]], [[12679, 12679], "mapped", [4484]], [[12680, 12680], "mapped", [4485]], [[12681, 12681], "mapped", [4488]], [[12682, 12682], "mapped", [4497]], [[12683, 12683], "mapped", [4498]], [[12684, 12684], "mapped", [4500]], [[12685, 12685], "mapped", [4510]], [[12686, 12686], "mapped", [4513]], [[12687, 12687], "disallowed"], [[12688, 12689], "valid", [], "NV8"], [[12690, 12690], "mapped", [19968]], [[12691, 12691], "mapped", [20108]], [[12692, 12692], "mapped", [19977]], [[12693, 12693], "mapped", [22235]], [[12694, 12694], "mapped", [19978]], [[12695, 12695], "mapped", [20013]], [[12696, 12696], "mapped", [19979]], [[12697, 12697], "mapped", [30002]], [[12698, 12698], "mapped", [20057]], [[12699, 12699], "mapped", [19993]], [[12700, 12700], "mapped", [19969]], [[12701, 12701], "mapped", [22825]], [[12702, 12702], "mapped", [22320]], [[12703, 12703], "mapped", [20154]], [[12704, 12727], "valid"], [[12728, 12730], "valid"], [[12731, 12735], "disallowed"], [[12736, 12751], "valid", [], "NV8"], [[12752, 12771], "valid", [], "NV8"], [[12772, 12783], "disallowed"], [[12784, 12799], "valid"], [[12800, 12800], "disallowed_STD3_mapped", [40, 4352, 41]], [[12801, 12801], "disallowed_STD3_mapped", [40, 4354, 41]], [[12802, 12802], "disallowed_STD3_mapped", [40, 4355, 41]], [[12803, 12803], "disallowed_STD3_mapped", [40, 4357, 41]], [[12804, 12804], "disallowed_STD3_mapped", [40, 4358, 41]], [[12805, 12805], "disallowed_STD3_mapped", [40, 4359, 41]], [[12806, 12806], "disallowed_STD3_mapped", [40, 4361, 41]], [[12807, 12807], "disallowed_STD3_mapped", [40, 4363, 41]], [[12808, 12808], "disallowed_STD3_mapped", [40, 4364, 41]], [[12809, 12809], "disallowed_STD3_mapped", [40, 4366, 41]], [[12810, 12810], "disallowed_STD3_mapped", [40, 4367, 41]], [[12811, 12811], "disallowed_STD3_mapped", [40, 4368, 41]], [[12812, 12812], "disallowed_STD3_mapped", [40, 4369, 41]], [[12813, 12813], "disallowed_STD3_mapped", [40, 4370, 41]], [[12814, 12814], "disallowed_STD3_mapped", [40, 44032, 41]], [[12815, 12815], "disallowed_STD3_mapped", [40, 45208, 41]], [[12816, 12816], "disallowed_STD3_mapped", [40, 45796, 41]], [[12817, 12817], "disallowed_STD3_mapped", [40, 46972, 41]], [[12818, 12818], "disallowed_STD3_mapped", [40, 47560, 41]], [[12819, 12819], "disallowed_STD3_mapped", [40, 48148, 41]], [[12820, 12820], "disallowed_STD3_mapped", [40, 49324, 41]], [[12821, 12821], "disallowed_STD3_mapped", [40, 50500, 41]], [[12822, 12822], "disallowed_STD3_mapped", [40, 51088, 41]], [[12823, 12823], "disallowed_STD3_mapped", [40, 52264, 41]], [[12824, 12824], "disallowed_STD3_mapped", [40, 52852, 41]], [[12825, 12825], "disallowed_STD3_mapped", [40, 53440, 41]], [[12826, 12826], "disallowed_STD3_mapped", [40, 54028, 41]], [[12827, 12827], "disallowed_STD3_mapped", [40, 54616, 41]], [[12828, 12828], "disallowed_STD3_mapped", [40, 51452, 41]], [[12829, 12829], "disallowed_STD3_mapped", [40, 50724, 51204, 41]], [[12830, 12830], "disallowed_STD3_mapped", [40, 50724, 54980, 41]], [[12831, 12831], "disallowed"], [[12832, 12832], "disallowed_STD3_mapped", [40, 19968, 41]], [[12833, 12833], "disallowed_STD3_mapped", [40, 20108, 41]], [[12834, 12834], "disallowed_STD3_mapped", [40, 19977, 41]], [[12835, 12835], "disallowed_STD3_mapped", [40, 22235, 41]], [[12836, 12836], "disallowed_STD3_mapped", [40, 20116, 41]], [[12837, 12837], "disallowed_STD3_mapped", [40, 20845, 41]], [[12838, 12838], "disallowed_STD3_mapped", [40, 19971, 41]], [[12839, 12839], "disallowed_STD3_mapped", [40, 20843, 41]], [[12840, 12840], "disallowed_STD3_mapped", [40, 20061, 41]], [[12841, 12841], "disallowed_STD3_mapped", [40, 21313, 41]], [[12842, 12842], "disallowed_STD3_mapped", [40, 26376, 41]], [[12843, 12843], "disallowed_STD3_mapped", [40, 28779, 41]], [[12844, 12844], "disallowed_STD3_mapped", [40, 27700, 41]], [[12845, 12845], "disallowed_STD3_mapped", [40, 26408, 41]], [[12846, 12846], "disallowed_STD3_mapped", [40, 37329, 41]], [[12847, 12847], "disallowed_STD3_mapped", [40, 22303, 41]], [[12848, 12848], "disallowed_STD3_mapped", [40, 26085, 41]], [[12849, 12849], "disallowed_STD3_mapped", [40, 26666, 41]], [[12850, 12850], "disallowed_STD3_mapped", [40, 26377, 41]], [[12851, 12851], "disallowed_STD3_mapped", [40, 31038, 41]], [[12852, 12852], "disallowed_STD3_mapped", [40, 21517, 41]], [[12853, 12853], "disallowed_STD3_mapped", [40, 29305, 41]], [[12854, 12854], "disallowed_STD3_mapped", [40, 36001, 41]], [[12855, 12855], "disallowed_STD3_mapped", [40, 31069, 41]], [[12856, 12856], "disallowed_STD3_mapped", [40, 21172, 41]], [[12857, 12857], "disallowed_STD3_mapped", [40, 20195, 41]], [[12858, 12858], "disallowed_STD3_mapped", [40, 21628, 41]], [[12859, 12859], "disallowed_STD3_mapped", [40, 23398, 41]], [[12860, 12860], "disallowed_STD3_mapped", [40, 30435, 41]], [[12861, 12861], "disallowed_STD3_mapped", [40, 20225, 41]], [[12862, 12862], "disallowed_STD3_mapped", [40, 36039, 41]], [[12863, 12863], "disallowed_STD3_mapped", [40, 21332, 41]], [[12864, 12864], "disallowed_STD3_mapped", [40, 31085, 41]], [[12865, 12865], "disallowed_STD3_mapped", [40, 20241, 41]], [[12866, 12866], "disallowed_STD3_mapped", [40, 33258, 41]], [[12867, 12867], "disallowed_STD3_mapped", [40, 33267, 41]], [[12868, 12868], "mapped", [21839]], [[12869, 12869], "mapped", [24188]], [[12870, 12870], "mapped", [25991]], [[12871, 12871], "mapped", [31631]], [[12872, 12879], "valid", [], "NV8"], [[12880, 12880], "mapped", [112, 116, 101]], [[12881, 12881], "mapped", [50, 49]], [[12882, 12882], "mapped", [50, 50]], [[12883, 12883], "mapped", [50, 51]], [[12884, 12884], "mapped", [50, 52]], [[12885, 12885], "mapped", [50, 53]], [[12886, 12886], "mapped", [50, 54]], [[12887, 12887], "mapped", [50, 55]], [[12888, 12888], "mapped", [50, 56]], [[12889, 12889], "mapped", [50, 57]], [[12890, 12890], "mapped", [51, 48]], [[12891, 12891], "mapped", [51, 49]], [[12892, 12892], "mapped", [51, 50]], [[12893, 12893], "mapped", [51, 51]], [[12894, 12894], "mapped", [51, 52]], [[12895, 12895], "mapped", [51, 53]], [[12896, 12896], "mapped", [4352]], [[12897, 12897], "mapped", [4354]], [[12898, 12898], "mapped", [4355]], [[12899, 12899], "mapped", [4357]], [[12900, 12900], "mapped", [4358]], [[12901, 12901], "mapped", [4359]], [[12902, 12902], "mapped", [4361]], [[12903, 12903], "mapped", [4363]], [[12904, 12904], "mapped", [4364]], [[12905, 12905], "mapped", [4366]], [[12906, 12906], "mapped", [4367]], [[12907, 12907], "mapped", [4368]], [[12908, 12908], "mapped", [4369]], [[12909, 12909], "mapped", [4370]], [[12910, 12910], "mapped", [44032]], [[12911, 12911], "mapped", [45208]], [[12912, 12912], "mapped", [45796]], [[12913, 12913], "mapped", [46972]], [[12914, 12914], "mapped", [47560]], [[12915, 12915], "mapped", [48148]], [[12916, 12916], "mapped", [49324]], [[12917, 12917], "mapped", [50500]], [[12918, 12918], "mapped", [51088]], [[12919, 12919], "mapped", [52264]], [[12920, 12920], "mapped", [52852]], [[12921, 12921], "mapped", [53440]], [[12922, 12922], "mapped", [54028]], [[12923, 12923], "mapped", [54616]], [[12924, 12924], "mapped", [52280, 44256]], [[12925, 12925], "mapped", [51452, 51032]], [[12926, 12926], "mapped", [50864]], [[12927, 12927], "valid", [], "NV8"], [[12928, 12928], "mapped", [19968]], [[12929, 12929], "mapped", [20108]], [[12930, 12930], "mapped", [19977]], [[12931, 12931], "mapped", [22235]], [[12932, 12932], "mapped", [20116]], [[12933, 12933], "mapped", [20845]], [[12934, 12934], "mapped", [19971]], [[12935, 12935], "mapped", [20843]], [[12936, 12936], "mapped", [20061]], [[12937, 12937], "mapped", [21313]], [[12938, 12938], "mapped", [26376]], [[12939, 12939], "mapped", [28779]], [[12940, 12940], "mapped", [27700]], [[12941, 12941], "mapped", [26408]], [[12942, 12942], "mapped", [37329]], [[12943, 12943], "mapped", [22303]], [[12944, 12944], "mapped", [26085]], [[12945, 12945], "mapped", [26666]], [[12946, 12946], "mapped", [26377]], [[12947, 12947], "mapped", [31038]], [[12948, 12948], "mapped", [21517]], [[12949, 12949], "mapped", [29305]], [[12950, 12950], "mapped", [36001]], [[12951, 12951], "mapped", [31069]], [[12952, 12952], "mapped", [21172]], [[12953, 12953], "mapped", [31192]], [[12954, 12954], "mapped", [30007]], [[12955, 12955], "mapped", [22899]], [[12956, 12956], "mapped", [36969]], [[12957, 12957], "mapped", [20778]], [[12958, 12958], "mapped", [21360]], [[12959, 12959], "mapped", [27880]], [[12960, 12960], "mapped", [38917]], [[12961, 12961], "mapped", [20241]], [[12962, 12962], "mapped", [20889]], [[12963, 12963], "mapped", [27491]], [[12964, 12964], "mapped", [19978]], [[12965, 12965], "mapped", [20013]], [[12966, 12966], "mapped", [19979]], [[12967, 12967], "mapped", [24038]], [[12968, 12968], "mapped", [21491]], [[12969, 12969], "mapped", [21307]], [[12970, 12970], "mapped", [23447]], [[12971, 12971], "mapped", [23398]], [[12972, 12972], "mapped", [30435]], [[12973, 12973], "mapped", [20225]], [[12974, 12974], "mapped", [36039]], [[12975, 12975], "mapped", [21332]], [[12976, 12976], "mapped", [22812]], [[12977, 12977], "mapped", [51, 54]], [[12978, 12978], "mapped", [51, 55]], [[12979, 12979], "mapped", [51, 56]], [[12980, 12980], "mapped", [51, 57]], [[12981, 12981], "mapped", [52, 48]], [[12982, 12982], "mapped", [52, 49]], [[12983, 12983], "mapped", [52, 50]], [[12984, 12984], "mapped", [52, 51]], [[12985, 12985], "mapped", [52, 52]], [[12986, 12986], "mapped", [52, 53]], [[12987, 12987], "mapped", [52, 54]], [[12988, 12988], "mapped", [52, 55]], [[12989, 12989], "mapped", [52, 56]], [[12990, 12990], "mapped", [52, 57]], [[12991, 12991], "mapped", [53, 48]], [[12992, 12992], "mapped", [49, 26376]], [[12993, 12993], "mapped", [50, 26376]], [[12994, 12994], "mapped", [51, 26376]], [[12995, 12995], "mapped", [52, 26376]], [[12996, 12996], "mapped", [53, 26376]], [[12997, 12997], "mapped", [54, 26376]], [[12998, 12998], "mapped", [55, 26376]], [[12999, 12999], "mapped", [56, 26376]], [[13e3, 13e3], "mapped", [57, 26376]], [[13001, 13001], "mapped", [49, 48, 26376]], [[13002, 13002], "mapped", [49, 49, 26376]], [[13003, 13003], "mapped", [49, 50, 26376]], [[13004, 13004], "mapped", [104, 103]], [[13005, 13005], "mapped", [101, 114, 103]], [[13006, 13006], "mapped", [101, 118]], [[13007, 13007], "mapped", [108, 116, 100]], [[13008, 13008], "mapped", [12450]], [[13009, 13009], "mapped", [12452]], [[13010, 13010], "mapped", [12454]], [[13011, 13011], "mapped", [12456]], [[13012, 13012], "mapped", [12458]], [[13013, 13013], "mapped", [12459]], [[13014, 13014], "mapped", [12461]], [[13015, 13015], "mapped", [12463]], [[13016, 13016], "mapped", [12465]], [[13017, 13017], "mapped", [12467]], [[13018, 13018], "mapped", [12469]], [[13019, 13019], "mapped", [12471]], [[13020, 13020], "mapped", [12473]], [[13021, 13021], "mapped", [12475]], [[13022, 13022], "mapped", [12477]], [[13023, 13023], "mapped", [12479]], [[13024, 13024], "mapped", [12481]], [[13025, 13025], "mapped", [12484]], [[13026, 13026], "mapped", [12486]], [[13027, 13027], "mapped", [12488]], [[13028, 13028], "mapped", [12490]], [[13029, 13029], "mapped", [12491]], [[13030, 13030], "mapped", [12492]], [[13031, 13031], "mapped", [12493]], [[13032, 13032], "mapped", [12494]], [[13033, 13033], "mapped", [12495]], [[13034, 13034], "mapped", [12498]], [[13035, 13035], "mapped", [12501]], [[13036, 13036], "mapped", [12504]], [[13037, 13037], "mapped", [12507]], [[13038, 13038], "mapped", [12510]], [[13039, 13039], "mapped", [12511]], [[13040, 13040], "mapped", [12512]], [[13041, 13041], "mapped", [12513]], [[13042, 13042], "mapped", [12514]], [[13043, 13043], "mapped", [12516]], [[13044, 13044], "mapped", [12518]], [[13045, 13045], "mapped", [12520]], [[13046, 13046], "mapped", [12521]], [[13047, 13047], "mapped", [12522]], [[13048, 13048], "mapped", [12523]], [[13049, 13049], "mapped", [12524]], [[13050, 13050], "mapped", [12525]], [[13051, 13051], "mapped", [12527]], [[13052, 13052], "mapped", [12528]], [[13053, 13053], "mapped", [12529]], [[13054, 13054], "mapped", [12530]], [[13055, 13055], "disallowed"], [[13056, 13056], "mapped", [12450, 12497, 12540, 12488]], [[13057, 13057], "mapped", [12450, 12523, 12501, 12449]], [[13058, 13058], "mapped", [12450, 12531, 12506, 12450]], [[13059, 13059], "mapped", [12450, 12540, 12523]], [[13060, 13060], "mapped", [12452, 12491, 12531, 12464]], [[13061, 13061], "mapped", [12452, 12531, 12481]], [[13062, 13062], "mapped", [12454, 12457, 12531]], [[13063, 13063], "mapped", [12456, 12473, 12463, 12540, 12489]], [[13064, 13064], "mapped", [12456, 12540, 12459, 12540]], [[13065, 13065], "mapped", [12458, 12531, 12473]], [[13066, 13066], "mapped", [12458, 12540, 12512]], [[13067, 13067], "mapped", [12459, 12452, 12522]], [[13068, 13068], "mapped", [12459, 12521, 12483, 12488]], [[13069, 13069], "mapped", [12459, 12525, 12522, 12540]], [[13070, 13070], "mapped", [12460, 12525, 12531]], [[13071, 13071], "mapped", [12460, 12531, 12510]], [[13072, 13072], "mapped", [12462, 12460]], [[13073, 13073], "mapped", [12462, 12491, 12540]], [[13074, 13074], "mapped", [12461, 12517, 12522, 12540]], [[13075, 13075], "mapped", [12462, 12523, 12480, 12540]], [[13076, 13076], "mapped", [12461, 12525]], [[13077, 13077], "mapped", [12461, 12525, 12464, 12521, 12512]], [[13078, 13078], "mapped", [12461, 12525, 12513, 12540, 12488, 12523]], [[13079, 13079], "mapped", [12461, 12525, 12527, 12483, 12488]], [[13080, 13080], "mapped", [12464, 12521, 12512]], [[13081, 13081], "mapped", [12464, 12521, 12512, 12488, 12531]], [[13082, 13082], "mapped", [12463, 12523, 12476, 12452, 12525]], [[13083, 13083], "mapped", [12463, 12525, 12540, 12493]], [[13084, 13084], "mapped", [12465, 12540, 12473]], [[13085, 13085], "mapped", [12467, 12523, 12490]], [[13086, 13086], "mapped", [12467, 12540, 12509]], [[13087, 13087], "mapped", [12469, 12452, 12463, 12523]], [[13088, 13088], "mapped", [12469, 12531, 12481, 12540, 12512]], [[13089, 13089], "mapped", [12471, 12522, 12531, 12464]], [[13090, 13090], "mapped", [12475, 12531, 12481]], [[13091, 13091], "mapped", [12475, 12531, 12488]], [[13092, 13092], "mapped", [12480, 12540, 12473]], [[13093, 13093], "mapped", [12487, 12471]], [[13094, 13094], "mapped", [12489, 12523]], [[13095, 13095], "mapped", [12488, 12531]], [[13096, 13096], "mapped", [12490, 12494]], [[13097, 13097], "mapped", [12494, 12483, 12488]], [[13098, 13098], "mapped", [12495, 12452, 12484]], [[13099, 13099], "mapped", [12497, 12540, 12475, 12531, 12488]], [[13100, 13100], "mapped", [12497, 12540, 12484]], [[13101, 13101], "mapped", [12496, 12540, 12524, 12523]], [[13102, 13102], "mapped", [12500, 12450, 12473, 12488, 12523]], [[13103, 13103], "mapped", [12500, 12463, 12523]], [[13104, 13104], "mapped", [12500, 12467]], [[13105, 13105], "mapped", [12499, 12523]], [[13106, 13106], "mapped", [12501, 12449, 12521, 12483, 12489]], [[13107, 13107], "mapped", [12501, 12451, 12540, 12488]], [[13108, 13108], "mapped", [12502, 12483, 12471, 12455, 12523]], [[13109, 13109], "mapped", [12501, 12521, 12531]], [[13110, 13110], "mapped", [12504, 12463, 12479, 12540, 12523]], [[13111, 13111], "mapped", [12506, 12477]], [[13112, 13112], "mapped", [12506, 12491, 12498]], [[13113, 13113], "mapped", [12504, 12523, 12484]], [[13114, 13114], "mapped", [12506, 12531, 12473]], [[13115, 13115], "mapped", [12506, 12540, 12472]], [[13116, 13116], "mapped", [12505, 12540, 12479]], [[13117, 13117], "mapped", [12509, 12452, 12531, 12488]], [[13118, 13118], "mapped", [12508, 12523, 12488]], [[13119, 13119], "mapped", [12507, 12531]], [[13120, 13120], "mapped", [12509, 12531, 12489]], [[13121, 13121], "mapped", [12507, 12540, 12523]], [[13122, 13122], "mapped", [12507, 12540, 12531]], [[13123, 13123], "mapped", [12510, 12452, 12463, 12525]], [[13124, 13124], "mapped", [12510, 12452, 12523]], [[13125, 13125], "mapped", [12510, 12483, 12495]], [[13126, 13126], "mapped", [12510, 12523, 12463]], [[13127, 13127], "mapped", [12510, 12531, 12471, 12519, 12531]], [[13128, 13128], "mapped", [12511, 12463, 12525, 12531]], [[13129, 13129], "mapped", [12511, 12522]], [[13130, 13130], "mapped", [12511, 12522, 12496, 12540, 12523]], [[13131, 13131], "mapped", [12513, 12460]], [[13132, 13132], "mapped", [12513, 12460, 12488, 12531]], [[13133, 13133], "mapped", [12513, 12540, 12488, 12523]], [[13134, 13134], "mapped", [12516, 12540, 12489]], [[13135, 13135], "mapped", [12516, 12540, 12523]], [[13136, 13136], "mapped", [12518, 12450, 12531]], [[13137, 13137], "mapped", [12522, 12483, 12488, 12523]], [[13138, 13138], "mapped", [12522, 12521]], [[13139, 13139], "mapped", [12523, 12500, 12540]], [[13140, 13140], "mapped", [12523, 12540, 12502, 12523]], [[13141, 13141], "mapped", [12524, 12512]], [[13142, 13142], "mapped", [12524, 12531, 12488, 12466, 12531]], [[13143, 13143], "mapped", [12527, 12483, 12488]], [[13144, 13144], "mapped", [48, 28857]], [[13145, 13145], "mapped", [49, 28857]], [[13146, 13146], "mapped", [50, 28857]], [[13147, 13147], "mapped", [51, 28857]], [[13148, 13148], "mapped", [52, 28857]], [[13149, 13149], "mapped", [53, 28857]], [[13150, 13150], "mapped", [54, 28857]], [[13151, 13151], "mapped", [55, 28857]], [[13152, 13152], "mapped", [56, 28857]], [[13153, 13153], "mapped", [57, 28857]], [[13154, 13154], "mapped", [49, 48, 28857]], [[13155, 13155], "mapped", [49, 49, 28857]], [[13156, 13156], "mapped", [49, 50, 28857]], [[13157, 13157], "mapped", [49, 51, 28857]], [[13158, 13158], "mapped", [49, 52, 28857]], [[13159, 13159], "mapped", [49, 53, 28857]], [[13160, 13160], "mapped", [49, 54, 28857]], [[13161, 13161], "mapped", [49, 55, 28857]], [[13162, 13162], "mapped", [49, 56, 28857]], [[13163, 13163], "mapped", [49, 57, 28857]], [[13164, 13164], "mapped", [50, 48, 28857]], [[13165, 13165], "mapped", [50, 49, 28857]], [[13166, 13166], "mapped", [50, 50, 28857]], [[13167, 13167], "mapped", [50, 51, 28857]], [[13168, 13168], "mapped", [50, 52, 28857]], [[13169, 13169], "mapped", [104, 112, 97]], [[13170, 13170], "mapped", [100, 97]], [[13171, 13171], "mapped", [97, 117]], [[13172, 13172], "mapped", [98, 97, 114]], [[13173, 13173], "mapped", [111, 118]], [[13174, 13174], "mapped", [112, 99]], [[13175, 13175], "mapped", [100, 109]], [[13176, 13176], "mapped", [100, 109, 50]], [[13177, 13177], "mapped", [100, 109, 51]], [[13178, 13178], "mapped", [105, 117]], [[13179, 13179], "mapped", [24179, 25104]], [[13180, 13180], "mapped", [26157, 21644]], [[13181, 13181], "mapped", [22823, 27491]], [[13182, 13182], "mapped", [26126, 27835]], [[13183, 13183], "mapped", [26666, 24335, 20250, 31038]], [[13184, 13184], "mapped", [112, 97]], [[13185, 13185], "mapped", [110, 97]], [[13186, 13186], "mapped", [956, 97]], [[13187, 13187], "mapped", [109, 97]], [[13188, 13188], "mapped", [107, 97]], [[13189, 13189], "mapped", [107, 98]], [[13190, 13190], "mapped", [109, 98]], [[13191, 13191], "mapped", [103, 98]], [[13192, 13192], "mapped", [99, 97, 108]], [[13193, 13193], "mapped", [107, 99, 97, 108]], [[13194, 13194], "mapped", [112, 102]], [[13195, 13195], "mapped", [110, 102]], [[13196, 13196], "mapped", [956, 102]], [[13197, 13197], "mapped", [956, 103]], [[13198, 13198], "mapped", [109, 103]], [[13199, 13199], "mapped", [107, 103]], [[13200, 13200], "mapped", [104, 122]], [[13201, 13201], "mapped", [107, 104, 122]], [[13202, 13202], "mapped", [109, 104, 122]], [[13203, 13203], "mapped", [103, 104, 122]], [[13204, 13204], "mapped", [116, 104, 122]], [[13205, 13205], "mapped", [956, 108]], [[13206, 13206], "mapped", [109, 108]], [[13207, 13207], "mapped", [100, 108]], [[13208, 13208], "mapped", [107, 108]], [[13209, 13209], "mapped", [102, 109]], [[13210, 13210], "mapped", [110, 109]], [[13211, 13211], "mapped", [956, 109]], [[13212, 13212], "mapped", [109, 109]], [[13213, 13213], "mapped", [99, 109]], [[13214, 13214], "mapped", [107, 109]], [[13215, 13215], "mapped", [109, 109, 50]], [[13216, 13216], "mapped", [99, 109, 50]], [[13217, 13217], "mapped", [109, 50]], [[13218, 13218], "mapped", [107, 109, 50]], [[13219, 13219], "mapped", [109, 109, 51]], [[13220, 13220], "mapped", [99, 109, 51]], [[13221, 13221], "mapped", [109, 51]], [[13222, 13222], "mapped", [107, 109, 51]], [[13223, 13223], "mapped", [109, 8725, 115]], [[13224, 13224], "mapped", [109, 8725, 115, 50]], [[13225, 13225], "mapped", [112, 97]], [[13226, 13226], "mapped", [107, 112, 97]], [[13227, 13227], "mapped", [109, 112, 97]], [[13228, 13228], "mapped", [103, 112, 97]], [[13229, 13229], "mapped", [114, 97, 100]], [[13230, 13230], "mapped", [114, 97, 100, 8725, 115]], [[13231, 13231], "mapped", [114, 97, 100, 8725, 115, 50]], [[13232, 13232], "mapped", [112, 115]], [[13233, 13233], "mapped", [110, 115]], [[13234, 13234], "mapped", [956, 115]], [[13235, 13235], "mapped", [109, 115]], [[13236, 13236], "mapped", [112, 118]], [[13237, 13237], "mapped", [110, 118]], [[13238, 13238], "mapped", [956, 118]], [[13239, 13239], "mapped", [109, 118]], [[13240, 13240], "mapped", [107, 118]], [[13241, 13241], "mapped", [109, 118]], [[13242, 13242], "mapped", [112, 119]], [[13243, 13243], "mapped", [110, 119]], [[13244, 13244], "mapped", [956, 119]], [[13245, 13245], "mapped", [109, 119]], [[13246, 13246], "mapped", [107, 119]], [[13247, 13247], "mapped", [109, 119]], [[13248, 13248], "mapped", [107, 969]], [[13249, 13249], "mapped", [109, 969]], [[13250, 13250], "disallowed"], [[13251, 13251], "mapped", [98, 113]], [[13252, 13252], "mapped", [99, 99]], [[13253, 13253], "mapped", [99, 100]], [[13254, 13254], "mapped", [99, 8725, 107, 103]], [[13255, 13255], "disallowed"], [[13256, 13256], "mapped", [100, 98]], [[13257, 13257], "mapped", [103, 121]], [[13258, 13258], "mapped", [104, 97]], [[13259, 13259], "mapped", [104, 112]], [[13260, 13260], "mapped", [105, 110]], [[13261, 13261], "mapped", [107, 107]], [[13262, 13262], "mapped", [107, 109]], [[13263, 13263], "mapped", [107, 116]], [[13264, 13264], "mapped", [108, 109]], [[13265, 13265], "mapped", [108, 110]], [[13266, 13266], "mapped", [108, 111, 103]], [[13267, 13267], "mapped", [108, 120]], [[13268, 13268], "mapped", [109, 98]], [[13269, 13269], "mapped", [109, 105, 108]], [[13270, 13270], "mapped", [109, 111, 108]], [[13271, 13271], "mapped", [112, 104]], [[13272, 13272], "disallowed"], [[13273, 13273], "mapped", [112, 112, 109]], [[13274, 13274], "mapped", [112, 114]], [[13275, 13275], "mapped", [115, 114]], [[13276, 13276], "mapped", [115, 118]], [[13277, 13277], "mapped", [119, 98]], [[13278, 13278], "mapped", [118, 8725, 109]], [[13279, 13279], "mapped", [97, 8725, 109]], [[13280, 13280], "mapped", [49, 26085]], [[13281, 13281], "mapped", [50, 26085]], [[13282, 13282], "mapped", [51, 26085]], [[13283, 13283], "mapped", [52, 26085]], [[13284, 13284], "mapped", [53, 26085]], [[13285, 13285], "mapped", [54, 26085]], [[13286, 13286], "mapped", [55, 26085]], [[13287, 13287], "mapped", [56, 26085]], [[13288, 13288], "mapped", [57, 26085]], [[13289, 13289], "mapped", [49, 48, 26085]], [[13290, 13290], "mapped", [49, 49, 26085]], [[13291, 13291], "mapped", [49, 50, 26085]], [[13292, 13292], "mapped", [49, 51, 26085]], [[13293, 13293], "mapped", [49, 52, 26085]], [[13294, 13294], "mapped", [49, 53, 26085]], [[13295, 13295], "mapped", [49, 54, 26085]], [[13296, 13296], "mapped", [49, 55, 26085]], [[13297, 13297], "mapped", [49, 56, 26085]], [[13298, 13298], "mapped", [49, 57, 26085]], [[13299, 13299], "mapped", [50, 48, 26085]], [[13300, 13300], "mapped", [50, 49, 26085]], [[13301, 13301], "mapped", [50, 50, 26085]], [[13302, 13302], "mapped", [50, 51, 26085]], [[13303, 13303], "mapped", [50, 52, 26085]], [[13304, 13304], "mapped", [50, 53, 26085]], [[13305, 13305], "mapped", [50, 54, 26085]], [[13306, 13306], "mapped", [50, 55, 26085]], [[13307, 13307], "mapped", [50, 56, 26085]], [[13308, 13308], "mapped", [50, 57, 26085]], [[13309, 13309], "mapped", [51, 48, 26085]], [[13310, 13310], "mapped", [51, 49, 26085]], [[13311, 13311], "mapped", [103, 97, 108]], [[13312, 19893], "valid"], [[19894, 19903], "disallowed"], [[19904, 19967], "valid", [], "NV8"], [[19968, 40869], "valid"], [[40870, 40891], "valid"], [[40892, 40899], "valid"], [[40900, 40907], "valid"], [[40908, 40908], "valid"], [[40909, 40917], "valid"], [[40918, 40959], "disallowed"], [[40960, 42124], "valid"], [[42125, 42127], "disallowed"], [[42128, 42145], "valid", [], "NV8"], [[42146, 42147], "valid", [], "NV8"], [[42148, 42163], "valid", [], "NV8"], [[42164, 42164], "valid", [], "NV8"], [[42165, 42176], "valid", [], "NV8"], [[42177, 42177], "valid", [], "NV8"], [[42178, 42180], "valid", [], "NV8"], [[42181, 42181], "valid", [], "NV8"], [[42182, 42182], "valid", [], "NV8"], [[42183, 42191], "disallowed"], [[42192, 42237], "valid"], [[42238, 42239], "valid", [], "NV8"], [[42240, 42508], "valid"], [[42509, 42511], "valid", [], "NV8"], [[42512, 42539], "valid"], [[42540, 42559], "disallowed"], [[42560, 42560], "mapped", [42561]], [[42561, 42561], "valid"], [[42562, 42562], "mapped", [42563]], [[42563, 42563], "valid"], [[42564, 42564], "mapped", [42565]], [[42565, 42565], "valid"], [[42566, 42566], "mapped", [42567]], [[42567, 42567], "valid"], [[42568, 42568], "mapped", [42569]], [[42569, 42569], "valid"], [[42570, 42570], "mapped", [42571]], [[42571, 42571], "valid"], [[42572, 42572], "mapped", [42573]], [[42573, 42573], "valid"], [[42574, 42574], "mapped", [42575]], [[42575, 42575], "valid"], [[42576, 42576], "mapped", [42577]], [[42577, 42577], "valid"], [[42578, 42578], "mapped", [42579]], [[42579, 42579], "valid"], [[42580, 42580], "mapped", [42581]], [[42581, 42581], "valid"], [[42582, 42582], "mapped", [42583]], [[42583, 42583], "valid"], [[42584, 42584], "mapped", [42585]], [[42585, 42585], "valid"], [[42586, 42586], "mapped", [42587]], [[42587, 42587], "valid"], [[42588, 42588], "mapped", [42589]], [[42589, 42589], "valid"], [[42590, 42590], "mapped", [42591]], [[42591, 42591], "valid"], [[42592, 42592], "mapped", [42593]], [[42593, 42593], "valid"], [[42594, 42594], "mapped", [42595]], [[42595, 42595], "valid"], [[42596, 42596], "mapped", [42597]], [[42597, 42597], "valid"], [[42598, 42598], "mapped", [42599]], [[42599, 42599], "valid"], [[42600, 42600], "mapped", [42601]], [[42601, 42601], "valid"], [[42602, 42602], "mapped", [42603]], [[42603, 42603], "valid"], [[42604, 42604], "mapped", [42605]], [[42605, 42607], "valid"], [[42608, 42611], "valid", [], "NV8"], [[42612, 42619], "valid"], [[42620, 42621], "valid"], [[42622, 42622], "valid", [], "NV8"], [[42623, 42623], "valid"], [[42624, 42624], "mapped", [42625]], [[42625, 42625], "valid"], [[42626, 42626], "mapped", [42627]], [[42627, 42627], "valid"], [[42628, 42628], "mapped", [42629]], [[42629, 42629], "valid"], [[42630, 42630], "mapped", [42631]], [[42631, 42631], "valid"], [[42632, 42632], "mapped", [42633]], [[42633, 42633], "valid"], [[42634, 42634], "mapped", [42635]], [[42635, 42635], "valid"], [[42636, 42636], "mapped", [42637]], [[42637, 42637], "valid"], [[42638, 42638], "mapped", [42639]], [[42639, 42639], "valid"], [[42640, 42640], "mapped", [42641]], [[42641, 42641], "valid"], [[42642, 42642], "mapped", [42643]], [[42643, 42643], "valid"], [[42644, 42644], "mapped", [42645]], [[42645, 42645], "valid"], [[42646, 42646], "mapped", [42647]], [[42647, 42647], "valid"], [[42648, 42648], "mapped", [42649]], [[42649, 42649], "valid"], [[42650, 42650], "mapped", [42651]], [[42651, 42651], "valid"], [[42652, 42652], "mapped", [1098]], [[42653, 42653], "mapped", [1100]], [[42654, 42654], "valid"], [[42655, 42655], "valid"], [[42656, 42725], "valid"], [[42726, 42735], "valid", [], "NV8"], [[42736, 42737], "valid"], [[42738, 42743], "valid", [], "NV8"], [[42744, 42751], "disallowed"], [[42752, 42774], "valid", [], "NV8"], [[42775, 42778], "valid"], [[42779, 42783], "valid"], [[42784, 42785], "valid", [], "NV8"], [[42786, 42786], "mapped", [42787]], [[42787, 42787], "valid"], [[42788, 42788], "mapped", [42789]], [[42789, 42789], "valid"], [[42790, 42790], "mapped", [42791]], [[42791, 42791], "valid"], [[42792, 42792], "mapped", [42793]], [[42793, 42793], "valid"], [[42794, 42794], "mapped", [42795]], [[42795, 42795], "valid"], [[42796, 42796], "mapped", [42797]], [[42797, 42797], "valid"], [[42798, 42798], "mapped", [42799]], [[42799, 42801], "valid"], [[42802, 42802], "mapped", [42803]], [[42803, 42803], "valid"], [[42804, 42804], "mapped", [42805]], [[42805, 42805], "valid"], [[42806, 42806], "mapped", [42807]], [[42807, 42807], "valid"], [[42808, 42808], "mapped", [42809]], [[42809, 42809], "valid"], [[42810, 42810], "mapped", [42811]], [[42811, 42811], "valid"], [[42812, 42812], "mapped", [42813]], [[42813, 42813], "valid"], [[42814, 42814], "mapped", [42815]], [[42815, 42815], "valid"], [[42816, 42816], "mapped", [42817]], [[42817, 42817], "valid"], [[42818, 42818], "mapped", [42819]], [[42819, 42819], "valid"], [[42820, 42820], "mapped", [42821]], [[42821, 42821], "valid"], [[42822, 42822], "mapped", [42823]], [[42823, 42823], "valid"], [[42824, 42824], "mapped", [42825]], [[42825, 42825], "valid"], [[42826, 42826], "mapped", [42827]], [[42827, 42827], "valid"], [[42828, 42828], "mapped", [42829]], [[42829, 42829], "valid"], [[42830, 42830], "mapped", [42831]], [[42831, 42831], "valid"], [[42832, 42832], "mapped", [42833]], [[42833, 42833], "valid"], [[42834, 42834], "mapped", [42835]], [[42835, 42835], "valid"], [[42836, 42836], "mapped", [42837]], [[42837, 42837], "valid"], [[42838, 42838], "mapped", [42839]], [[42839, 42839], "valid"], [[42840, 42840], "mapped", [42841]], [[42841, 42841], "valid"], [[42842, 42842], "mapped", [42843]], [[42843, 42843], "valid"], [[42844, 42844], "mapped", [42845]], [[42845, 42845], "valid"], [[42846, 42846], "mapped", [42847]], [[42847, 42847], "valid"], [[42848, 42848], "mapped", [42849]], [[42849, 42849], "valid"], [[42850, 42850], "mapped", [42851]], [[42851, 42851], "valid"], [[42852, 42852], "mapped", [42853]], [[42853, 42853], "valid"], [[42854, 42854], "mapped", [42855]], [[42855, 42855], "valid"], [[42856, 42856], "mapped", [42857]], [[42857, 42857], "valid"], [[42858, 42858], "mapped", [42859]], [[42859, 42859], "valid"], [[42860, 42860], "mapped", [42861]], [[42861, 42861], "valid"], [[42862, 42862], "mapped", [42863]], [[42863, 42863], "valid"], [[42864, 42864], "mapped", [42863]], [[42865, 42872], "valid"], [[42873, 42873], "mapped", [42874]], [[42874, 42874], "valid"], [[42875, 42875], "mapped", [42876]], [[42876, 42876], "valid"], [[42877, 42877], "mapped", [7545]], [[42878, 42878], "mapped", [42879]], [[42879, 42879], "valid"], [[42880, 42880], "mapped", [42881]], [[42881, 42881], "valid"], [[42882, 42882], "mapped", [42883]], [[42883, 42883], "valid"], [[42884, 42884], "mapped", [42885]], [[42885, 42885], "valid"], [[42886, 42886], "mapped", [42887]], [[42887, 42888], "valid"], [[42889, 42890], "valid", [], "NV8"], [[42891, 42891], "mapped", [42892]], [[42892, 42892], "valid"], [[42893, 42893], "mapped", [613]], [[42894, 42894], "valid"], [[42895, 42895], "valid"], [[42896, 42896], "mapped", [42897]], [[42897, 42897], "valid"], [[42898, 42898], "mapped", [42899]], [[42899, 42899], "valid"], [[42900, 42901], "valid"], [[42902, 42902], "mapped", [42903]], [[42903, 42903], "valid"], [[42904, 42904], "mapped", [42905]], [[42905, 42905], "valid"], [[42906, 42906], "mapped", [42907]], [[42907, 42907], "valid"], [[42908, 42908], "mapped", [42909]], [[42909, 42909], "valid"], [[42910, 42910], "mapped", [42911]], [[42911, 42911], "valid"], [[42912, 42912], "mapped", [42913]], [[42913, 42913], "valid"], [[42914, 42914], "mapped", [42915]], [[42915, 42915], "valid"], [[42916, 42916], "mapped", [42917]], [[42917, 42917], "valid"], [[42918, 42918], "mapped", [42919]], [[42919, 42919], "valid"], [[42920, 42920], "mapped", [42921]], [[42921, 42921], "valid"], [[42922, 42922], "mapped", [614]], [[42923, 42923], "mapped", [604]], [[42924, 42924], "mapped", [609]], [[42925, 42925], "mapped", [620]], [[42926, 42927], "disallowed"], [[42928, 42928], "mapped", [670]], [[42929, 42929], "mapped", [647]], [[42930, 42930], "mapped", [669]], [[42931, 42931], "mapped", [43859]], [[42932, 42932], "mapped", [42933]], [[42933, 42933], "valid"], [[42934, 42934], "mapped", [42935]], [[42935, 42935], "valid"], [[42936, 42998], "disallowed"], [[42999, 42999], "valid"], [[43e3, 43e3], "mapped", [295]], [[43001, 43001], "mapped", [339]], [[43002, 43002], "valid"], [[43003, 43007], "valid"], [[43008, 43047], "valid"], [[43048, 43051], "valid", [], "NV8"], [[43052, 43055], "disallowed"], [[43056, 43065], "valid", [], "NV8"], [[43066, 43071], "disallowed"], [[43072, 43123], "valid"], [[43124, 43127], "valid", [], "NV8"], [[43128, 43135], "disallowed"], [[43136, 43204], "valid"], [[43205, 43213], "disallowed"], [[43214, 43215], "valid", [], "NV8"], [[43216, 43225], "valid"], [[43226, 43231], "disallowed"], [[43232, 43255], "valid"], [[43256, 43258], "valid", [], "NV8"], [[43259, 43259], "valid"], [[43260, 43260], "valid", [], "NV8"], [[43261, 43261], "valid"], [[43262, 43263], "disallowed"], [[43264, 43309], "valid"], [[43310, 43311], "valid", [], "NV8"], [[43312, 43347], "valid"], [[43348, 43358], "disallowed"], [[43359, 43359], "valid", [], "NV8"], [[43360, 43388], "valid", [], "NV8"], [[43389, 43391], "disallowed"], [[43392, 43456], "valid"], [[43457, 43469], "valid", [], "NV8"], [[43470, 43470], "disallowed"], [[43471, 43481], "valid"], [[43482, 43485], "disallowed"], [[43486, 43487], "valid", [], "NV8"], [[43488, 43518], "valid"], [[43519, 43519], "disallowed"], [[43520, 43574], "valid"], [[43575, 43583], "disallowed"], [[43584, 43597], "valid"], [[43598, 43599], "disallowed"], [[43600, 43609], "valid"], [[43610, 43611], "disallowed"], [[43612, 43615], "valid", [], "NV8"], [[43616, 43638], "valid"], [[43639, 43641], "valid", [], "NV8"], [[43642, 43643], "valid"], [[43644, 43647], "valid"], [[43648, 43714], "valid"], [[43715, 43738], "disallowed"], [[43739, 43741], "valid"], [[43742, 43743], "valid", [], "NV8"], [[43744, 43759], "valid"], [[43760, 43761], "valid", [], "NV8"], [[43762, 43766], "valid"], [[43767, 43776], "disallowed"], [[43777, 43782], "valid"], [[43783, 43784], "disallowed"], [[43785, 43790], "valid"], [[43791, 43792], "disallowed"], [[43793, 43798], "valid"], [[43799, 43807], "disallowed"], [[43808, 43814], "valid"], [[43815, 43815], "disallowed"], [[43816, 43822], "valid"], [[43823, 43823], "disallowed"], [[43824, 43866], "valid"], [[43867, 43867], "valid", [], "NV8"], [[43868, 43868], "mapped", [42791]], [[43869, 43869], "mapped", [43831]], [[43870, 43870], "mapped", [619]], [[43871, 43871], "mapped", [43858]], [[43872, 43875], "valid"], [[43876, 43877], "valid"], [[43878, 43887], "disallowed"], [[43888, 43888], "mapped", [5024]], [[43889, 43889], "mapped", [5025]], [[43890, 43890], "mapped", [5026]], [[43891, 43891], "mapped", [5027]], [[43892, 43892], "mapped", [5028]], [[43893, 43893], "mapped", [5029]], [[43894, 43894], "mapped", [5030]], [[43895, 43895], "mapped", [5031]], [[43896, 43896], "mapped", [5032]], [[43897, 43897], "mapped", [5033]], [[43898, 43898], "mapped", [5034]], [[43899, 43899], "mapped", [5035]], [[43900, 43900], "mapped", [5036]], [[43901, 43901], "mapped", [5037]], [[43902, 43902], "mapped", [5038]], [[43903, 43903], "mapped", [5039]], [[43904, 43904], "mapped", [5040]], [[43905, 43905], "mapped", [5041]], [[43906, 43906], "mapped", [5042]], [[43907, 43907], "mapped", [5043]], [[43908, 43908], "mapped", [5044]], [[43909, 43909], "mapped", [5045]], [[43910, 43910], "mapped", [5046]], [[43911, 43911], "mapped", [5047]], [[43912, 43912], "mapped", [5048]], [[43913, 43913], "mapped", [5049]], [[43914, 43914], "mapped", [5050]], [[43915, 43915], "mapped", [5051]], [[43916, 43916], "mapped", [5052]], [[43917, 43917], "mapped", [5053]], [[43918, 43918], "mapped", [5054]], [[43919, 43919], "mapped", [5055]], [[43920, 43920], "mapped", [5056]], [[43921, 43921], "mapped", [5057]], [[43922, 43922], "mapped", [5058]], [[43923, 43923], "mapped", [5059]], [[43924, 43924], "mapped", [5060]], [[43925, 43925], "mapped", [5061]], [[43926, 43926], "mapped", [5062]], [[43927, 43927], "mapped", [5063]], [[43928, 43928], "mapped", [5064]], [[43929, 43929], "mapped", [5065]], [[43930, 43930], "mapped", [5066]], [[43931, 43931], "mapped", [5067]], [[43932, 43932], "mapped", [5068]], [[43933, 43933], "mapped", [5069]], [[43934, 43934], "mapped", [5070]], [[43935, 43935], "mapped", [5071]], [[43936, 43936], "mapped", [5072]], [[43937, 43937], "mapped", [5073]], [[43938, 43938], "mapped", [5074]], [[43939, 43939], "mapped", [5075]], [[43940, 43940], "mapped", [5076]], [[43941, 43941], "mapped", [5077]], [[43942, 43942], "mapped", [5078]], [[43943, 43943], "mapped", [5079]], [[43944, 43944], "mapped", [5080]], [[43945, 43945], "mapped", [5081]], [[43946, 43946], "mapped", [5082]], [[43947, 43947], "mapped", [5083]], [[43948, 43948], "mapped", [5084]], [[43949, 43949], "mapped", [5085]], [[43950, 43950], "mapped", [5086]], [[43951, 43951], "mapped", [5087]], [[43952, 43952], "mapped", [5088]], [[43953, 43953], "mapped", [5089]], [[43954, 43954], "mapped", [5090]], [[43955, 43955], "mapped", [5091]], [[43956, 43956], "mapped", [5092]], [[43957, 43957], "mapped", [5093]], [[43958, 43958], "mapped", [5094]], [[43959, 43959], "mapped", [5095]], [[43960, 43960], "mapped", [5096]], [[43961, 43961], "mapped", [5097]], [[43962, 43962], "mapped", [5098]], [[43963, 43963], "mapped", [5099]], [[43964, 43964], "mapped", [5100]], [[43965, 43965], "mapped", [5101]], [[43966, 43966], "mapped", [5102]], [[43967, 43967], "mapped", [5103]], [[43968, 44010], "valid"], [[44011, 44011], "valid", [], "NV8"], [[44012, 44013], "valid"], [[44014, 44015], "disallowed"], [[44016, 44025], "valid"], [[44026, 44031], "disallowed"], [[44032, 55203], "valid"], [[55204, 55215], "disallowed"], [[55216, 55238], "valid", [], "NV8"], [[55239, 55242], "disallowed"], [[55243, 55291], "valid", [], "NV8"], [[55292, 55295], "disallowed"], [[55296, 57343], "disallowed"], [[57344, 63743], "disallowed"], [[63744, 63744], "mapped", [35912]], [[63745, 63745], "mapped", [26356]], [[63746, 63746], "mapped", [36554]], [[63747, 63747], "mapped", [36040]], [[63748, 63748], "mapped", [28369]], [[63749, 63749], "mapped", [20018]], [[63750, 63750], "mapped", [21477]], [[63751, 63752], "mapped", [40860]], [[63753, 63753], "mapped", [22865]], [[63754, 63754], "mapped", [37329]], [[63755, 63755], "mapped", [21895]], [[63756, 63756], "mapped", [22856]], [[63757, 63757], "mapped", [25078]], [[63758, 63758], "mapped", [30313]], [[63759, 63759], "mapped", [32645]], [[63760, 63760], "mapped", [34367]], [[63761, 63761], "mapped", [34746]], [[63762, 63762], "mapped", [35064]], [[63763, 63763], "mapped", [37007]], [[63764, 63764], "mapped", [27138]], [[63765, 63765], "mapped", [27931]], [[63766, 63766], "mapped", [28889]], [[63767, 63767], "mapped", [29662]], [[63768, 63768], "mapped", [33853]], [[63769, 63769], "mapped", [37226]], [[63770, 63770], "mapped", [39409]], [[63771, 63771], "mapped", [20098]], [[63772, 63772], "mapped", [21365]], [[63773, 63773], "mapped", [27396]], [[63774, 63774], "mapped", [29211]], [[63775, 63775], "mapped", [34349]], [[63776, 63776], "mapped", [40478]], [[63777, 63777], "mapped", [23888]], [[63778, 63778], "mapped", [28651]], [[63779, 63779], "mapped", [34253]], [[63780, 63780], "mapped", [35172]], [[63781, 63781], "mapped", [25289]], [[63782, 63782], "mapped", [33240]], [[63783, 63783], "mapped", [34847]], [[63784, 63784], "mapped", [24266]], [[63785, 63785], "mapped", [26391]], [[63786, 63786], "mapped", [28010]], [[63787, 63787], "mapped", [29436]], [[63788, 63788], "mapped", [37070]], [[63789, 63789], "mapped", [20358]], [[63790, 63790], "mapped", [20919]], [[63791, 63791], "mapped", [21214]], [[63792, 63792], "mapped", [25796]], [[63793, 63793], "mapped", [27347]], [[63794, 63794], "mapped", [29200]], [[63795, 63795], "mapped", [30439]], [[63796, 63796], "mapped", [32769]], [[63797, 63797], "mapped", [34310]], [[63798, 63798], "mapped", [34396]], [[63799, 63799], "mapped", [36335]], [[63800, 63800], "mapped", [38706]], [[63801, 63801], "mapped", [39791]], [[63802, 63802], "mapped", [40442]], [[63803, 63803], "mapped", [30860]], [[63804, 63804], "mapped", [31103]], [[63805, 63805], "mapped", [32160]], [[63806, 63806], "mapped", [33737]], [[63807, 63807], "mapped", [37636]], [[63808, 63808], "mapped", [40575]], [[63809, 63809], "mapped", [35542]], [[63810, 63810], "mapped", [22751]], [[63811, 63811], "mapped", [24324]], [[63812, 63812], "mapped", [31840]], [[63813, 63813], "mapped", [32894]], [[63814, 63814], "mapped", [29282]], [[63815, 63815], "mapped", [30922]], [[63816, 63816], "mapped", [36034]], [[63817, 63817], "mapped", [38647]], [[63818, 63818], "mapped", [22744]], [[63819, 63819], "mapped", [23650]], [[63820, 63820], "mapped", [27155]], [[63821, 63821], "mapped", [28122]], [[63822, 63822], "mapped", [28431]], [[63823, 63823], "mapped", [32047]], [[63824, 63824], "mapped", [32311]], [[63825, 63825], "mapped", [38475]], [[63826, 63826], "mapped", [21202]], [[63827, 63827], "mapped", [32907]], [[63828, 63828], "mapped", [20956]], [[63829, 63829], "mapped", [20940]], [[63830, 63830], "mapped", [31260]], [[63831, 63831], "mapped", [32190]], [[63832, 63832], "mapped", [33777]], [[63833, 63833], "mapped", [38517]], [[63834, 63834], "mapped", [35712]], [[63835, 63835], "mapped", [25295]], [[63836, 63836], "mapped", [27138]], [[63837, 63837], "mapped", [35582]], [[63838, 63838], "mapped", [20025]], [[63839, 63839], "mapped", [23527]], [[63840, 63840], "mapped", [24594]], [[63841, 63841], "mapped", [29575]], [[63842, 63842], "mapped", [30064]], [[63843, 63843], "mapped", [21271]], [[63844, 63844], "mapped", [30971]], [[63845, 63845], "mapped", [20415]], [[63846, 63846], "mapped", [24489]], [[63847, 63847], "mapped", [19981]], [[63848, 63848], "mapped", [27852]], [[63849, 63849], "mapped", [25976]], [[63850, 63850], "mapped", [32034]], [[63851, 63851], "mapped", [21443]], [[63852, 63852], "mapped", [22622]], [[63853, 63853], "mapped", [30465]], [[63854, 63854], "mapped", [33865]], [[63855, 63855], "mapped", [35498]], [[63856, 63856], "mapped", [27578]], [[63857, 63857], "mapped", [36784]], [[63858, 63858], "mapped", [27784]], [[63859, 63859], "mapped", [25342]], [[63860, 63860], "mapped", [33509]], [[63861, 63861], "mapped", [25504]], [[63862, 63862], "mapped", [30053]], [[63863, 63863], "mapped", [20142]], [[63864, 63864], "mapped", [20841]], [[63865, 63865], "mapped", [20937]], [[63866, 63866], "mapped", [26753]], [[63867, 63867], "mapped", [31975]], [[63868, 63868], "mapped", [33391]], [[63869, 63869], "mapped", [35538]], [[63870, 63870], "mapped", [37327]], [[63871, 63871], "mapped", [21237]], [[63872, 63872], "mapped", [21570]], [[63873, 63873], "mapped", [22899]], [[63874, 63874], "mapped", [24300]], [[63875, 63875], "mapped", [26053]], [[63876, 63876], "mapped", [28670]], [[63877, 63877], "mapped", [31018]], [[63878, 63878], "mapped", [38317]], [[63879, 63879], "mapped", [39530]], [[63880, 63880], "mapped", [40599]], [[63881, 63881], "mapped", [40654]], [[63882, 63882], "mapped", [21147]], [[63883, 63883], "mapped", [26310]], [[63884, 63884], "mapped", [27511]], [[63885, 63885], "mapped", [36706]], [[63886, 63886], "mapped", [24180]], [[63887, 63887], "mapped", [24976]], [[63888, 63888], "mapped", [25088]], [[63889, 63889], "mapped", [25754]], [[63890, 63890], "mapped", [28451]], [[63891, 63891], "mapped", [29001]], [[63892, 63892], "mapped", [29833]], [[63893, 63893], "mapped", [31178]], [[63894, 63894], "mapped", [32244]], [[63895, 63895], "mapped", [32879]], [[63896, 63896], "mapped", [36646]], [[63897, 63897], "mapped", [34030]], [[63898, 63898], "mapped", [36899]], [[63899, 63899], "mapped", [37706]], [[63900, 63900], "mapped", [21015]], [[63901, 63901], "mapped", [21155]], [[63902, 63902], "mapped", [21693]], [[63903, 63903], "mapped", [28872]], [[63904, 63904], "mapped", [35010]], [[63905, 63905], "mapped", [35498]], [[63906, 63906], "mapped", [24265]], [[63907, 63907], "mapped", [24565]], [[63908, 63908], "mapped", [25467]], [[63909, 63909], "mapped", [27566]], [[63910, 63910], "mapped", [31806]], [[63911, 63911], "mapped", [29557]], [[63912, 63912], "mapped", [20196]], [[63913, 63913], "mapped", [22265]], [[63914, 63914], "mapped", [23527]], [[63915, 63915], "mapped", [23994]], [[63916, 63916], "mapped", [24604]], [[63917, 63917], "mapped", [29618]], [[63918, 63918], "mapped", [29801]], [[63919, 63919], "mapped", [32666]], [[63920, 63920], "mapped", [32838]], [[63921, 63921], "mapped", [37428]], [[63922, 63922], "mapped", [38646]], [[63923, 63923], "mapped", [38728]], [[63924, 63924], "mapped", [38936]], [[63925, 63925], "mapped", [20363]], [[63926, 63926], "mapped", [31150]], [[63927, 63927], "mapped", [37300]], [[63928, 63928], "mapped", [38584]], [[63929, 63929], "mapped", [24801]], [[63930, 63930], "mapped", [20102]], [[63931, 63931], "mapped", [20698]], [[63932, 63932], "mapped", [23534]], [[63933, 63933], "mapped", [23615]], [[63934, 63934], "mapped", [26009]], [[63935, 63935], "mapped", [27138]], [[63936, 63936], "mapped", [29134]], [[63937, 63937], "mapped", [30274]], [[63938, 63938], "mapped", [34044]], [[63939, 63939], "mapped", [36988]], [[63940, 63940], "mapped", [40845]], [[63941, 63941], "mapped", [26248]], [[63942, 63942], "mapped", [38446]], [[63943, 63943], "mapped", [21129]], [[63944, 63944], "mapped", [26491]], [[63945, 63945], "mapped", [26611]], [[63946, 63946], "mapped", [27969]], [[63947, 63947], "mapped", [28316]], [[63948, 63948], "mapped", [29705]], [[63949, 63949], "mapped", [30041]], [[63950, 63950], "mapped", [30827]], [[63951, 63951], "mapped", [32016]], [[63952, 63952], "mapped", [39006]], [[63953, 63953], "mapped", [20845]], [[63954, 63954], "mapped", [25134]], [[63955, 63955], "mapped", [38520]], [[63956, 63956], "mapped", [20523]], [[63957, 63957], "mapped", [23833]], [[63958, 63958], "mapped", [28138]], [[63959, 63959], "mapped", [36650]], [[63960, 63960], "mapped", [24459]], [[63961, 63961], "mapped", [24900]], [[63962, 63962], "mapped", [26647]], [[63963, 63963], "mapped", [29575]], [[63964, 63964], "mapped", [38534]], [[63965, 63965], "mapped", [21033]], [[63966, 63966], "mapped", [21519]], [[63967, 63967], "mapped", [23653]], [[63968, 63968], "mapped", [26131]], [[63969, 63969], "mapped", [26446]], [[63970, 63970], "mapped", [26792]], [[63971, 63971], "mapped", [27877]], [[63972, 63972], "mapped", [29702]], [[63973, 63973], "mapped", [30178]], [[63974, 63974], "mapped", [32633]], [[63975, 63975], "mapped", [35023]], [[63976, 63976], "mapped", [35041]], [[63977, 63977], "mapped", [37324]], [[63978, 63978], "mapped", [38626]], [[63979, 63979], "mapped", [21311]], [[63980, 63980], "mapped", [28346]], [[63981, 63981], "mapped", [21533]], [[63982, 63982], "mapped", [29136]], [[63983, 63983], "mapped", [29848]], [[63984, 63984], "mapped", [34298]], [[63985, 63985], "mapped", [38563]], [[63986, 63986], "mapped", [40023]], [[63987, 63987], "mapped", [40607]], [[63988, 63988], "mapped", [26519]], [[63989, 63989], "mapped", [28107]], [[63990, 63990], "mapped", [33256]], [[63991, 63991], "mapped", [31435]], [[63992, 63992], "mapped", [31520]], [[63993, 63993], "mapped", [31890]], [[63994, 63994], "mapped", [29376]], [[63995, 63995], "mapped", [28825]], [[63996, 63996], "mapped", [35672]], [[63997, 63997], "mapped", [20160]], [[63998, 63998], "mapped", [33590]], [[63999, 63999], "mapped", [21050]], [[64e3, 64e3], "mapped", [20999]], [[64001, 64001], "mapped", [24230]], [[64002, 64002], "mapped", [25299]], [[64003, 64003], "mapped", [31958]], [[64004, 64004], "mapped", [23429]], [[64005, 64005], "mapped", [27934]], [[64006, 64006], "mapped", [26292]], [[64007, 64007], "mapped", [36667]], [[64008, 64008], "mapped", [34892]], [[64009, 64009], "mapped", [38477]], [[64010, 64010], "mapped", [35211]], [[64011, 64011], "mapped", [24275]], [[64012, 64012], "mapped", [20800]], [[64013, 64013], "mapped", [21952]], [[64014, 64015], "valid"], [[64016, 64016], "mapped", [22618]], [[64017, 64017], "valid"], [[64018, 64018], "mapped", [26228]], [[64019, 64020], "valid"], [[64021, 64021], "mapped", [20958]], [[64022, 64022], "mapped", [29482]], [[64023, 64023], "mapped", [30410]], [[64024, 64024], "mapped", [31036]], [[64025, 64025], "mapped", [31070]], [[64026, 64026], "mapped", [31077]], [[64027, 64027], "mapped", [31119]], [[64028, 64028], "mapped", [38742]], [[64029, 64029], "mapped", [31934]], [[64030, 64030], "mapped", [32701]], [[64031, 64031], "valid"], [[64032, 64032], "mapped", [34322]], [[64033, 64033], "valid"], [[64034, 64034], "mapped", [35576]], [[64035, 64036], "valid"], [[64037, 64037], "mapped", [36920]], [[64038, 64038], "mapped", [37117]], [[64039, 64041], "valid"], [[64042, 64042], "mapped", [39151]], [[64043, 64043], "mapped", [39164]], [[64044, 64044], "mapped", [39208]], [[64045, 64045], "mapped", [40372]], [[64046, 64046], "mapped", [37086]], [[64047, 64047], "mapped", [38583]], [[64048, 64048], "mapped", [20398]], [[64049, 64049], "mapped", [20711]], [[64050, 64050], "mapped", [20813]], [[64051, 64051], "mapped", [21193]], [[64052, 64052], "mapped", [21220]], [[64053, 64053], "mapped", [21329]], [[64054, 64054], "mapped", [21917]], [[64055, 64055], "mapped", [22022]], [[64056, 64056], "mapped", [22120]], [[64057, 64057], "mapped", [22592]], [[64058, 64058], "mapped", [22696]], [[64059, 64059], "mapped", [23652]], [[64060, 64060], "mapped", [23662]], [[64061, 64061], "mapped", [24724]], [[64062, 64062], "mapped", [24936]], [[64063, 64063], "mapped", [24974]], [[64064, 64064], "mapped", [25074]], [[64065, 64065], "mapped", [25935]], [[64066, 64066], "mapped", [26082]], [[64067, 64067], "mapped", [26257]], [[64068, 64068], "mapped", [26757]], [[64069, 64069], "mapped", [28023]], [[64070, 64070], "mapped", [28186]], [[64071, 64071], "mapped", [28450]], [[64072, 64072], "mapped", [29038]], [[64073, 64073], "mapped", [29227]], [[64074, 64074], "mapped", [29730]], [[64075, 64075], "mapped", [30865]], [[64076, 64076], "mapped", [31038]], [[64077, 64077], "mapped", [31049]], [[64078, 64078], "mapped", [31048]], [[64079, 64079], "mapped", [31056]], [[64080, 64080], "mapped", [31062]], [[64081, 64081], "mapped", [31069]], [[64082, 64082], "mapped", [31117]], [[64083, 64083], "mapped", [31118]], [[64084, 64084], "mapped", [31296]], [[64085, 64085], "mapped", [31361]], [[64086, 64086], "mapped", [31680]], [[64087, 64087], "mapped", [32244]], [[64088, 64088], "mapped", [32265]], [[64089, 64089], "mapped", [32321]], [[64090, 64090], "mapped", [32626]], [[64091, 64091], "mapped", [32773]], [[64092, 64092], "mapped", [33261]], [[64093, 64094], "mapped", [33401]], [[64095, 64095], "mapped", [33879]], [[64096, 64096], "mapped", [35088]], [[64097, 64097], "mapped", [35222]], [[64098, 64098], "mapped", [35585]], [[64099, 64099], "mapped", [35641]], [[64100, 64100], "mapped", [36051]], [[64101, 64101], "mapped", [36104]], [[64102, 64102], "mapped", [36790]], [[64103, 64103], "mapped", [36920]], [[64104, 64104], "mapped", [38627]], [[64105, 64105], "mapped", [38911]], [[64106, 64106], "mapped", [38971]], [[64107, 64107], "mapped", [24693]], [[64108, 64108], "mapped", [148206]], [[64109, 64109], "mapped", [33304]], [[64110, 64111], "disallowed"], [[64112, 64112], "mapped", [20006]], [[64113, 64113], "mapped", [20917]], [[64114, 64114], "mapped", [20840]], [[64115, 64115], "mapped", [20352]], [[64116, 64116], "mapped", [20805]], [[64117, 64117], "mapped", [20864]], [[64118, 64118], "mapped", [21191]], [[64119, 64119], "mapped", [21242]], [[64120, 64120], "mapped", [21917]], [[64121, 64121], "mapped", [21845]], [[64122, 64122], "mapped", [21913]], [[64123, 64123], "mapped", [21986]], [[64124, 64124], "mapped", [22618]], [[64125, 64125], "mapped", [22707]], [[64126, 64126], "mapped", [22852]], [[64127, 64127], "mapped", [22868]], [[64128, 64128], "mapped", [23138]], [[64129, 64129], "mapped", [23336]], [[64130, 64130], "mapped", [24274]], [[64131, 64131], "mapped", [24281]], [[64132, 64132], "mapped", [24425]], [[64133, 64133], "mapped", [24493]], [[64134, 64134], "mapped", [24792]], [[64135, 64135], "mapped", [24910]], [[64136, 64136], "mapped", [24840]], [[64137, 64137], "mapped", [24974]], [[64138, 64138], "mapped", [24928]], [[64139, 64139], "mapped", [25074]], [[64140, 64140], "mapped", [25140]], [[64141, 64141], "mapped", [25540]], [[64142, 64142], "mapped", [25628]], [[64143, 64143], "mapped", [25682]], [[64144, 64144], "mapped", [25942]], [[64145, 64145], "mapped", [26228]], [[64146, 64146], "mapped", [26391]], [[64147, 64147], "mapped", [26395]], [[64148, 64148], "mapped", [26454]], [[64149, 64149], "mapped", [27513]], [[64150, 64150], "mapped", [27578]], [[64151, 64151], "mapped", [27969]], [[64152, 64152], "mapped", [28379]], [[64153, 64153], "mapped", [28363]], [[64154, 64154], "mapped", [28450]], [[64155, 64155], "mapped", [28702]], [[64156, 64156], "mapped", [29038]], [[64157, 64157], "mapped", [30631]], [[64158, 64158], "mapped", [29237]], [[64159, 64159], "mapped", [29359]], [[64160, 64160], "mapped", [29482]], [[64161, 64161], "mapped", [29809]], [[64162, 64162], "mapped", [29958]], [[64163, 64163], "mapped", [30011]], [[64164, 64164], "mapped", [30237]], [[64165, 64165], "mapped", [30239]], [[64166, 64166], "mapped", [30410]], [[64167, 64167], "mapped", [30427]], [[64168, 64168], "mapped", [30452]], [[64169, 64169], "mapped", [30538]], [[64170, 64170], "mapped", [30528]], [[64171, 64171], "mapped", [30924]], [[64172, 64172], "mapped", [31409]], [[64173, 64173], "mapped", [31680]], [[64174, 64174], "mapped", [31867]], [[64175, 64175], "mapped", [32091]], [[64176, 64176], "mapped", [32244]], [[64177, 64177], "mapped", [32574]], [[64178, 64178], "mapped", [32773]], [[64179, 64179], "mapped", [33618]], [[64180, 64180], "mapped", [33775]], [[64181, 64181], "mapped", [34681]], [[64182, 64182], "mapped", [35137]], [[64183, 64183], "mapped", [35206]], [[64184, 64184], "mapped", [35222]], [[64185, 64185], "mapped", [35519]], [[64186, 64186], "mapped", [35576]], [[64187, 64187], "mapped", [35531]], [[64188, 64188], "mapped", [35585]], [[64189, 64189], "mapped", [35582]], [[64190, 64190], "mapped", [35565]], [[64191, 64191], "mapped", [35641]], [[64192, 64192], "mapped", [35722]], [[64193, 64193], "mapped", [36104]], [[64194, 64194], "mapped", [36664]], [[64195, 64195], "mapped", [36978]], [[64196, 64196], "mapped", [37273]], [[64197, 64197], "mapped", [37494]], [[64198, 64198], "mapped", [38524]], [[64199, 64199], "mapped", [38627]], [[64200, 64200], "mapped", [38742]], [[64201, 64201], "mapped", [38875]], [[64202, 64202], "mapped", [38911]], [[64203, 64203], "mapped", [38923]], [[64204, 64204], "mapped", [38971]], [[64205, 64205], "mapped", [39698]], [[64206, 64206], "mapped", [40860]], [[64207, 64207], "mapped", [141386]], [[64208, 64208], "mapped", [141380]], [[64209, 64209], "mapped", [144341]], [[64210, 64210], "mapped", [15261]], [[64211, 64211], "mapped", [16408]], [[64212, 64212], "mapped", [16441]], [[64213, 64213], "mapped", [152137]], [[64214, 64214], "mapped", [154832]], [[64215, 64215], "mapped", [163539]], [[64216, 64216], "mapped", [40771]], [[64217, 64217], "mapped", [40846]], [[64218, 64255], "disallowed"], [[64256, 64256], "mapped", [102, 102]], [[64257, 64257], "mapped", [102, 105]], [[64258, 64258], "mapped", [102, 108]], [[64259, 64259], "mapped", [102, 102, 105]], [[64260, 64260], "mapped", [102, 102, 108]], [[64261, 64262], "mapped", [115, 116]], [[64263, 64274], "disallowed"], [[64275, 64275], "mapped", [1396, 1398]], [[64276, 64276], "mapped", [1396, 1381]], [[64277, 64277], "mapped", [1396, 1387]], [[64278, 64278], "mapped", [1406, 1398]], [[64279, 64279], "mapped", [1396, 1389]], [[64280, 64284], "disallowed"], [[64285, 64285], "mapped", [1497, 1460]], [[64286, 64286], "valid"], [[64287, 64287], "mapped", [1522, 1463]], [[64288, 64288], "mapped", [1506]], [[64289, 64289], "mapped", [1488]], [[64290, 64290], "mapped", [1491]], [[64291, 64291], "mapped", [1492]], [[64292, 64292], "mapped", [1499]], [[64293, 64293], "mapped", [1500]], [[64294, 64294], "mapped", [1501]], [[64295, 64295], "mapped", [1512]], [[64296, 64296], "mapped", [1514]], [[64297, 64297], "disallowed_STD3_mapped", [43]], [[64298, 64298], "mapped", [1513, 1473]], [[64299, 64299], "mapped", [1513, 1474]], [[64300, 64300], "mapped", [1513, 1468, 1473]], [[64301, 64301], "mapped", [1513, 1468, 1474]], [[64302, 64302], "mapped", [1488, 1463]], [[64303, 64303], "mapped", [1488, 1464]], [[64304, 64304], "mapped", [1488, 1468]], [[64305, 64305], "mapped", [1489, 1468]], [[64306, 64306], "mapped", [1490, 1468]], [[64307, 64307], "mapped", [1491, 1468]], [[64308, 64308], "mapped", [1492, 1468]], [[64309, 64309], "mapped", [1493, 1468]], [[64310, 64310], "mapped", [1494, 1468]], [[64311, 64311], "disallowed"], [[64312, 64312], "mapped", [1496, 1468]], [[64313, 64313], "mapped", [1497, 1468]], [[64314, 64314], "mapped", [1498, 1468]], [[64315, 64315], "mapped", [1499, 1468]], [[64316, 64316], "mapped", [1500, 1468]], [[64317, 64317], "disallowed"], [[64318, 64318], "mapped", [1502, 1468]], [[64319, 64319], "disallowed"], [[64320, 64320], "mapped", [1504, 1468]], [[64321, 64321], "mapped", [1505, 1468]], [[64322, 64322], "disallowed"], [[64323, 64323], "mapped", [1507, 1468]], [[64324, 64324], "mapped", [1508, 1468]], [[64325, 64325], "disallowed"], [[64326, 64326], "mapped", [1510, 1468]], [[64327, 64327], "mapped", [1511, 1468]], [[64328, 64328], "mapped", [1512, 1468]], [[64329, 64329], "mapped", [1513, 1468]], [[64330, 64330], "mapped", [1514, 1468]], [[64331, 64331], "mapped", [1493, 1465]], [[64332, 64332], "mapped", [1489, 1471]], [[64333, 64333], "mapped", [1499, 1471]], [[64334, 64334], "mapped", [1508, 1471]], [[64335, 64335], "mapped", [1488, 1500]], [[64336, 64337], "mapped", [1649]], [[64338, 64341], "mapped", [1659]], [[64342, 64345], "mapped", [1662]], [[64346, 64349], "mapped", [1664]], [[64350, 64353], "mapped", [1658]], [[64354, 64357], "mapped", [1663]], [[64358, 64361], "mapped", [1657]], [[64362, 64365], "mapped", [1700]], [[64366, 64369], "mapped", [1702]], [[64370, 64373], "mapped", [1668]], [[64374, 64377], "mapped", [1667]], [[64378, 64381], "mapped", [1670]], [[64382, 64385], "mapped", [1671]], [[64386, 64387], "mapped", [1677]], [[64388, 64389], "mapped", [1676]], [[64390, 64391], "mapped", [1678]], [[64392, 64393], "mapped", [1672]], [[64394, 64395], "mapped", [1688]], [[64396, 64397], "mapped", [1681]], [[64398, 64401], "mapped", [1705]], [[64402, 64405], "mapped", [1711]], [[64406, 64409], "mapped", [1715]], [[64410, 64413], "mapped", [1713]], [[64414, 64415], "mapped", [1722]], [[64416, 64419], "mapped", [1723]], [[64420, 64421], "mapped", [1728]], [[64422, 64425], "mapped", [1729]], [[64426, 64429], "mapped", [1726]], [[64430, 64431], "mapped", [1746]], [[64432, 64433], "mapped", [1747]], [[64434, 64449], "valid", [], "NV8"], [[64450, 64466], "disallowed"], [[64467, 64470], "mapped", [1709]], [[64471, 64472], "mapped", [1735]], [[64473, 64474], "mapped", [1734]], [[64475, 64476], "mapped", [1736]], [[64477, 64477], "mapped", [1735, 1652]], [[64478, 64479], "mapped", [1739]], [[64480, 64481], "mapped", [1733]], [[64482, 64483], "mapped", [1737]], [[64484, 64487], "mapped", [1744]], [[64488, 64489], "mapped", [1609]], [[64490, 64491], "mapped", [1574, 1575]], [[64492, 64493], "mapped", [1574, 1749]], [[64494, 64495], "mapped", [1574, 1608]], [[64496, 64497], "mapped", [1574, 1735]], [[64498, 64499], "mapped", [1574, 1734]], [[64500, 64501], "mapped", [1574, 1736]], [[64502, 64504], "mapped", [1574, 1744]], [[64505, 64507], "mapped", [1574, 1609]], [[64508, 64511], "mapped", [1740]], [[64512, 64512], "mapped", [1574, 1580]], [[64513, 64513], "mapped", [1574, 1581]], [[64514, 64514], "mapped", [1574, 1605]], [[64515, 64515], "mapped", [1574, 1609]], [[64516, 64516], "mapped", [1574, 1610]], [[64517, 64517], "mapped", [1576, 1580]], [[64518, 64518], "mapped", [1576, 1581]], [[64519, 64519], "mapped", [1576, 1582]], [[64520, 64520], "mapped", [1576, 1605]], [[64521, 64521], "mapped", [1576, 1609]], [[64522, 64522], "mapped", [1576, 1610]], [[64523, 64523], "mapped", [1578, 1580]], [[64524, 64524], "mapped", [1578, 1581]], [[64525, 64525], "mapped", [1578, 1582]], [[64526, 64526], "mapped", [1578, 1605]], [[64527, 64527], "mapped", [1578, 1609]], [[64528, 64528], "mapped", [1578, 1610]], [[64529, 64529], "mapped", [1579, 1580]], [[64530, 64530], "mapped", [1579, 1605]], [[64531, 64531], "mapped", [1579, 1609]], [[64532, 64532], "mapped", [1579, 1610]], [[64533, 64533], "mapped", [1580, 1581]], [[64534, 64534], "mapped", [1580, 1605]], [[64535, 64535], "mapped", [1581, 1580]], [[64536, 64536], "mapped", [1581, 1605]], [[64537, 64537], "mapped", [1582, 1580]], [[64538, 64538], "mapped", [1582, 1581]], [[64539, 64539], "mapped", [1582, 1605]], [[64540, 64540], "mapped", [1587, 1580]], [[64541, 64541], "mapped", [1587, 1581]], [[64542, 64542], "mapped", [1587, 1582]], [[64543, 64543], "mapped", [1587, 1605]], [[64544, 64544], "mapped", [1589, 1581]], [[64545, 64545], "mapped", [1589, 1605]], [[64546, 64546], "mapped", [1590, 1580]], [[64547, 64547], "mapped", [1590, 1581]], [[64548, 64548], "mapped", [1590, 1582]], [[64549, 64549], "mapped", [1590, 1605]], [[64550, 64550], "mapped", [1591, 1581]], [[64551, 64551], "mapped", [1591, 1605]], [[64552, 64552], "mapped", [1592, 1605]], [[64553, 64553], "mapped", [1593, 1580]], [[64554, 64554], "mapped", [1593, 1605]], [[64555, 64555], "mapped", [1594, 1580]], [[64556, 64556], "mapped", [1594, 1605]], [[64557, 64557], "mapped", [1601, 1580]], [[64558, 64558], "mapped", [1601, 1581]], [[64559, 64559], "mapped", [1601, 1582]], [[64560, 64560], "mapped", [1601, 1605]], [[64561, 64561], "mapped", [1601, 1609]], [[64562, 64562], "mapped", [1601, 1610]], [[64563, 64563], "mapped", [1602, 1581]], [[64564, 64564], "mapped", [1602, 1605]], [[64565, 64565], "mapped", [1602, 1609]], [[64566, 64566], "mapped", [1602, 1610]], [[64567, 64567], "mapped", [1603, 1575]], [[64568, 64568], "mapped", [1603, 1580]], [[64569, 64569], "mapped", [1603, 1581]], [[64570, 64570], "mapped", [1603, 1582]], [[64571, 64571], "mapped", [1603, 1604]], [[64572, 64572], "mapped", [1603, 1605]], [[64573, 64573], "mapped", [1603, 1609]], [[64574, 64574], "mapped", [1603, 1610]], [[64575, 64575], "mapped", [1604, 1580]], [[64576, 64576], "mapped", [1604, 1581]], [[64577, 64577], "mapped", [1604, 1582]], [[64578, 64578], "mapped", [1604, 1605]], [[64579, 64579], "mapped", [1604, 1609]], [[64580, 64580], "mapped", [1604, 1610]], [[64581, 64581], "mapped", [1605, 1580]], [[64582, 64582], "mapped", [1605, 1581]], [[64583, 64583], "mapped", [1605, 1582]], [[64584, 64584], "mapped", [1605, 1605]], [[64585, 64585], "mapped", [1605, 1609]], [[64586, 64586], "mapped", [1605, 1610]], [[64587, 64587], "mapped", [1606, 1580]], [[64588, 64588], "mapped", [1606, 1581]], [[64589, 64589], "mapped", [1606, 1582]], [[64590, 64590], "mapped", [1606, 1605]], [[64591, 64591], "mapped", [1606, 1609]], [[64592, 64592], "mapped", [1606, 1610]], [[64593, 64593], "mapped", [1607, 1580]], [[64594, 64594], "mapped", [1607, 1605]], [[64595, 64595], "mapped", [1607, 1609]], [[64596, 64596], "mapped", [1607, 1610]], [[64597, 64597], "mapped", [1610, 1580]], [[64598, 64598], "mapped", [1610, 1581]], [[64599, 64599], "mapped", [1610, 1582]], [[64600, 64600], "mapped", [1610, 1605]], [[64601, 64601], "mapped", [1610, 1609]], [[64602, 64602], "mapped", [1610, 1610]], [[64603, 64603], "mapped", [1584, 1648]], [[64604, 64604], "mapped", [1585, 1648]], [[64605, 64605], "mapped", [1609, 1648]], [[64606, 64606], "disallowed_STD3_mapped", [32, 1612, 1617]], [[64607, 64607], "disallowed_STD3_mapped", [32, 1613, 1617]], [[64608, 64608], "disallowed_STD3_mapped", [32, 1614, 1617]], [[64609, 64609], "disallowed_STD3_mapped", [32, 1615, 1617]], [[64610, 64610], "disallowed_STD3_mapped", [32, 1616, 1617]], [[64611, 64611], "disallowed_STD3_mapped", [32, 1617, 1648]], [[64612, 64612], "mapped", [1574, 1585]], [[64613, 64613], "mapped", [1574, 1586]], [[64614, 64614], "mapped", [1574, 1605]], [[64615, 64615], "mapped", [1574, 1606]], [[64616, 64616], "mapped", [1574, 1609]], [[64617, 64617], "mapped", [1574, 1610]], [[64618, 64618], "mapped", [1576, 1585]], [[64619, 64619], "mapped", [1576, 1586]], [[64620, 64620], "mapped", [1576, 1605]], [[64621, 64621], "mapped", [1576, 1606]], [[64622, 64622], "mapped", [1576, 1609]], [[64623, 64623], "mapped", [1576, 1610]], [[64624, 64624], "mapped", [1578, 1585]], [[64625, 64625], "mapped", [1578, 1586]], [[64626, 64626], "mapped", [1578, 1605]], [[64627, 64627], "mapped", [1578, 1606]], [[64628, 64628], "mapped", [1578, 1609]], [[64629, 64629], "mapped", [1578, 1610]], [[64630, 64630], "mapped", [1579, 1585]], [[64631, 64631], "mapped", [1579, 1586]], [[64632, 64632], "mapped", [1579, 1605]], [[64633, 64633], "mapped", [1579, 1606]], [[64634, 64634], "mapped", [1579, 1609]], [[64635, 64635], "mapped", [1579, 1610]], [[64636, 64636], "mapped", [1601, 1609]], [[64637, 64637], "mapped", [1601, 1610]], [[64638, 64638], "mapped", [1602, 1609]], [[64639, 64639], "mapped", [1602, 1610]], [[64640, 64640], "mapped", [1603, 1575]], [[64641, 64641], "mapped", [1603, 1604]], [[64642, 64642], "mapped", [1603, 1605]], [[64643, 64643], "mapped", [1603, 1609]], [[64644, 64644], "mapped", [1603, 1610]], [[64645, 64645], "mapped", [1604, 1605]], [[64646, 64646], "mapped", [1604, 1609]], [[64647, 64647], "mapped", [1604, 1610]], [[64648, 64648], "mapped", [1605, 1575]], [[64649, 64649], "mapped", [1605, 1605]], [[64650, 64650], "mapped", [1606, 1585]], [[64651, 64651], "mapped", [1606, 1586]], [[64652, 64652], "mapped", [1606, 1605]], [[64653, 64653], "mapped", [1606, 1606]], [[64654, 64654], "mapped", [1606, 1609]], [[64655, 64655], "mapped", [1606, 1610]], [[64656, 64656], "mapped", [1609, 1648]], [[64657, 64657], "mapped", [1610, 1585]], [[64658, 64658], "mapped", [1610, 1586]], [[64659, 64659], "mapped", [1610, 1605]], [[64660, 64660], "mapped", [1610, 1606]], [[64661, 64661], "mapped", [1610, 1609]], [[64662, 64662], "mapped", [1610, 1610]], [[64663, 64663], "mapped", [1574, 1580]], [[64664, 64664], "mapped", [1574, 1581]], [[64665, 64665], "mapped", [1574, 1582]], [[64666, 64666], "mapped", [1574, 1605]], [[64667, 64667], "mapped", [1574, 1607]], [[64668, 64668], "mapped", [1576, 1580]], [[64669, 64669], "mapped", [1576, 1581]], [[64670, 64670], "mapped", [1576, 1582]], [[64671, 64671], "mapped", [1576, 1605]], [[64672, 64672], "mapped", [1576, 1607]], [[64673, 64673], "mapped", [1578, 1580]], [[64674, 64674], "mapped", [1578, 1581]], [[64675, 64675], "mapped", [1578, 1582]], [[64676, 64676], "mapped", [1578, 1605]], [[64677, 64677], "mapped", [1578, 1607]], [[64678, 64678], "mapped", [1579, 1605]], [[64679, 64679], "mapped", [1580, 1581]], [[64680, 64680], "mapped", [1580, 1605]], [[64681, 64681], "mapped", [1581, 1580]], [[64682, 64682], "mapped", [1581, 1605]], [[64683, 64683], "mapped", [1582, 1580]], [[64684, 64684], "mapped", [1582, 1605]], [[64685, 64685], "mapped", [1587, 1580]], [[64686, 64686], "mapped", [1587, 1581]], [[64687, 64687], "mapped", [1587, 1582]], [[64688, 64688], "mapped", [1587, 1605]], [[64689, 64689], "mapped", [1589, 1581]], [[64690, 64690], "mapped", [1589, 1582]], [[64691, 64691], "mapped", [1589, 1605]], [[64692, 64692], "mapped", [1590, 1580]], [[64693, 64693], "mapped", [1590, 1581]], [[64694, 64694], "mapped", [1590, 1582]], [[64695, 64695], "mapped", [1590, 1605]], [[64696, 64696], "mapped", [1591, 1581]], [[64697, 64697], "mapped", [1592, 1605]], [[64698, 64698], "mapped", [1593, 1580]], [[64699, 64699], "mapped", [1593, 1605]], [[64700, 64700], "mapped", [1594, 1580]], [[64701, 64701], "mapped", [1594, 1605]], [[64702, 64702], "mapped", [1601, 1580]], [[64703, 64703], "mapped", [1601, 1581]], [[64704, 64704], "mapped", [1601, 1582]], [[64705, 64705], "mapped", [1601, 1605]], [[64706, 64706], "mapped", [1602, 1581]], [[64707, 64707], "mapped", [1602, 1605]], [[64708, 64708], "mapped", [1603, 1580]], [[64709, 64709], "mapped", [1603, 1581]], [[64710, 64710], "mapped", [1603, 1582]], [[64711, 64711], "mapped", [1603, 1604]], [[64712, 64712], "mapped", [1603, 1605]], [[64713, 64713], "mapped", [1604, 1580]], [[64714, 64714], "mapped", [1604, 1581]], [[64715, 64715], "mapped", [1604, 1582]], [[64716, 64716], "mapped", [1604, 1605]], [[64717, 64717], "mapped", [1604, 1607]], [[64718, 64718], "mapped", [1605, 1580]], [[64719, 64719], "mapped", [1605, 1581]], [[64720, 64720], "mapped", [1605, 1582]], [[64721, 64721], "mapped", [1605, 1605]], [[64722, 64722], "mapped", [1606, 1580]], [[64723, 64723], "mapped", [1606, 1581]], [[64724, 64724], "mapped", [1606, 1582]], [[64725, 64725], "mapped", [1606, 1605]], [[64726, 64726], "mapped", [1606, 1607]], [[64727, 64727], "mapped", [1607, 1580]], [[64728, 64728], "mapped", [1607, 1605]], [[64729, 64729], "mapped", [1607, 1648]], [[64730, 64730], "mapped", [1610, 1580]], [[64731, 64731], "mapped", [1610, 1581]], [[64732, 64732], "mapped", [1610, 1582]], [[64733, 64733], "mapped", [1610, 1605]], [[64734, 64734], "mapped", [1610, 1607]], [[64735, 64735], "mapped", [1574, 1605]], [[64736, 64736], "mapped", [1574, 1607]], [[64737, 64737], "mapped", [1576, 1605]], [[64738, 64738], "mapped", [1576, 1607]], [[64739, 64739], "mapped", [1578, 1605]], [[64740, 64740], "mapped", [1578, 1607]], [[64741, 64741], "mapped", [1579, 1605]], [[64742, 64742], "mapped", [1579, 1607]], [[64743, 64743], "mapped", [1587, 1605]], [[64744, 64744], "mapped", [1587, 1607]], [[64745, 64745], "mapped", [1588, 1605]], [[64746, 64746], "mapped", [1588, 1607]], [[64747, 64747], "mapped", [1603, 1604]], [[64748, 64748], "mapped", [1603, 1605]], [[64749, 64749], "mapped", [1604, 1605]], [[64750, 64750], "mapped", [1606, 1605]], [[64751, 64751], "mapped", [1606, 1607]], [[64752, 64752], "mapped", [1610, 1605]], [[64753, 64753], "mapped", [1610, 1607]], [[64754, 64754], "mapped", [1600, 1614, 1617]], [[64755, 64755], "mapped", [1600, 1615, 1617]], [[64756, 64756], "mapped", [1600, 1616, 1617]], [[64757, 64757], "mapped", [1591, 1609]], [[64758, 64758], "mapped", [1591, 1610]], [[64759, 64759], "mapped", [1593, 1609]], [[64760, 64760], "mapped", [1593, 1610]], [[64761, 64761], "mapped", [1594, 1609]], [[64762, 64762], "mapped", [1594, 1610]], [[64763, 64763], "mapped", [1587, 1609]], [[64764, 64764], "mapped", [1587, 1610]], [[64765, 64765], "mapped", [1588, 1609]], [[64766, 64766], "mapped", [1588, 1610]], [[64767, 64767], "mapped", [1581, 1609]], [[64768, 64768], "mapped", [1581, 1610]], [[64769, 64769], "mapped", [1580, 1609]], [[64770, 64770], "mapped", [1580, 1610]], [[64771, 64771], "mapped", [1582, 1609]], [[64772, 64772], "mapped", [1582, 1610]], [[64773, 64773], "mapped", [1589, 1609]], [[64774, 64774], "mapped", [1589, 1610]], [[64775, 64775], "mapped", [1590, 1609]], [[64776, 64776], "mapped", [1590, 1610]], [[64777, 64777], "mapped", [1588, 1580]], [[64778, 64778], "mapped", [1588, 1581]], [[64779, 64779], "mapped", [1588, 1582]], [[64780, 64780], "mapped", [1588, 1605]], [[64781, 64781], "mapped", [1588, 1585]], [[64782, 64782], "mapped", [1587, 1585]], [[64783, 64783], "mapped", [1589, 1585]], [[64784, 64784], "mapped", [1590, 1585]], [[64785, 64785], "mapped", [1591, 1609]], [[64786, 64786], "mapped", [1591, 1610]], [[64787, 64787], "mapped", [1593, 1609]], [[64788, 64788], "mapped", [1593, 1610]], [[64789, 64789], "mapped", [1594, 1609]], [[64790, 64790], "mapped", [1594, 1610]], [[64791, 64791], "mapped", [1587, 1609]], [[64792, 64792], "mapped", [1587, 1610]], [[64793, 64793], "mapped", [1588, 1609]], [[64794, 64794], "mapped", [1588, 1610]], [[64795, 64795], "mapped", [1581, 1609]], [[64796, 64796], "mapped", [1581, 1610]], [[64797, 64797], "mapped", [1580, 1609]], [[64798, 64798], "mapped", [1580, 1610]], [[64799, 64799], "mapped", [1582, 1609]], [[64800, 64800], "mapped", [1582, 1610]], [[64801, 64801], "mapped", [1589, 1609]], [[64802, 64802], "mapped", [1589, 1610]], [[64803, 64803], "mapped", [1590, 1609]], [[64804, 64804], "mapped", [1590, 1610]], [[64805, 64805], "mapped", [1588, 1580]], [[64806, 64806], "mapped", [1588, 1581]], [[64807, 64807], "mapped", [1588, 1582]], [[64808, 64808], "mapped", [1588, 1605]], [[64809, 64809], "mapped", [1588, 1585]], [[64810, 64810], "mapped", [1587, 1585]], [[64811, 64811], "mapped", [1589, 1585]], [[64812, 64812], "mapped", [1590, 1585]], [[64813, 64813], "mapped", [1588, 1580]], [[64814, 64814], "mapped", [1588, 1581]], [[64815, 64815], "mapped", [1588, 1582]], [[64816, 64816], "mapped", [1588, 1605]], [[64817, 64817], "mapped", [1587, 1607]], [[64818, 64818], "mapped", [1588, 1607]], [[64819, 64819], "mapped", [1591, 1605]], [[64820, 64820], "mapped", [1587, 1580]], [[64821, 64821], "mapped", [1587, 1581]], [[64822, 64822], "mapped", [1587, 1582]], [[64823, 64823], "mapped", [1588, 1580]], [[64824, 64824], "mapped", [1588, 1581]], [[64825, 64825], "mapped", [1588, 1582]], [[64826, 64826], "mapped", [1591, 1605]], [[64827, 64827], "mapped", [1592, 1605]], [[64828, 64829], "mapped", [1575, 1611]], [[64830, 64831], "valid", [], "NV8"], [[64832, 64847], "disallowed"], [[64848, 64848], "mapped", [1578, 1580, 1605]], [[64849, 64850], "mapped", [1578, 1581, 1580]], [[64851, 64851], "mapped", [1578, 1581, 1605]], [[64852, 64852], "mapped", [1578, 1582, 1605]], [[64853, 64853], "mapped", [1578, 1605, 1580]], [[64854, 64854], "mapped", [1578, 1605, 1581]], [[64855, 64855], "mapped", [1578, 1605, 1582]], [[64856, 64857], "mapped", [1580, 1605, 1581]], [[64858, 64858], "mapped", [1581, 1605, 1610]], [[64859, 64859], "mapped", [1581, 1605, 1609]], [[64860, 64860], "mapped", [1587, 1581, 1580]], [[64861, 64861], "mapped", [1587, 1580, 1581]], [[64862, 64862], "mapped", [1587, 1580, 1609]], [[64863, 64864], "mapped", [1587, 1605, 1581]], [[64865, 64865], "mapped", [1587, 1605, 1580]], [[64866, 64867], "mapped", [1587, 1605, 1605]], [[64868, 64869], "mapped", [1589, 1581, 1581]], [[64870, 64870], "mapped", [1589, 1605, 1605]], [[64871, 64872], "mapped", [1588, 1581, 1605]], [[64873, 64873], "mapped", [1588, 1580, 1610]], [[64874, 64875], "mapped", [1588, 1605, 1582]], [[64876, 64877], "mapped", [1588, 1605, 1605]], [[64878, 64878], "mapped", [1590, 1581, 1609]], [[64879, 64880], "mapped", [1590, 1582, 1605]], [[64881, 64882], "mapped", [1591, 1605, 1581]], [[64883, 64883], "mapped", [1591, 1605, 1605]], [[64884, 64884], "mapped", [1591, 1605, 1610]], [[64885, 64885], "mapped", [1593, 1580, 1605]], [[64886, 64887], "mapped", [1593, 1605, 1605]], [[64888, 64888], "mapped", [1593, 1605, 1609]], [[64889, 64889], "mapped", [1594, 1605, 1605]], [[64890, 64890], "mapped", [1594, 1605, 1610]], [[64891, 64891], "mapped", [1594, 1605, 1609]], [[64892, 64893], "mapped", [1601, 1582, 1605]], [[64894, 64894], "mapped", [1602, 1605, 1581]], [[64895, 64895], "mapped", [1602, 1605, 1605]], [[64896, 64896], "mapped", [1604, 1581, 1605]], [[64897, 64897], "mapped", [1604, 1581, 1610]], [[64898, 64898], "mapped", [1604, 1581, 1609]], [[64899, 64900], "mapped", [1604, 1580, 1580]], [[64901, 64902], "mapped", [1604, 1582, 1605]], [[64903, 64904], "mapped", [1604, 1605, 1581]], [[64905, 64905], "mapped", [1605, 1581, 1580]], [[64906, 64906], "mapped", [1605, 1581, 1605]], [[64907, 64907], "mapped", [1605, 1581, 1610]], [[64908, 64908], "mapped", [1605, 1580, 1581]], [[64909, 64909], "mapped", [1605, 1580, 1605]], [[64910, 64910], "mapped", [1605, 1582, 1580]], [[64911, 64911], "mapped", [1605, 1582, 1605]], [[64912, 64913], "disallowed"], [[64914, 64914], "mapped", [1605, 1580, 1582]], [[64915, 64915], "mapped", [1607, 1605, 1580]], [[64916, 64916], "mapped", [1607, 1605, 1605]], [[64917, 64917], "mapped", [1606, 1581, 1605]], [[64918, 64918], "mapped", [1606, 1581, 1609]], [[64919, 64920], "mapped", [1606, 1580, 1605]], [[64921, 64921], "mapped", [1606, 1580, 1609]], [[64922, 64922], "mapped", [1606, 1605, 1610]], [[64923, 64923], "mapped", [1606, 1605, 1609]], [[64924, 64925], "mapped", [1610, 1605, 1605]], [[64926, 64926], "mapped", [1576, 1582, 1610]], [[64927, 64927], "mapped", [1578, 1580, 1610]], [[64928, 64928], "mapped", [1578, 1580, 1609]], [[64929, 64929], "mapped", [1578, 1582, 1610]], [[64930, 64930], "mapped", [1578, 1582, 1609]], [[64931, 64931], "mapped", [1578, 1605, 1610]], [[64932, 64932], "mapped", [1578, 1605, 1609]], [[64933, 64933], "mapped", [1580, 1605, 1610]], [[64934, 64934], "mapped", [1580, 1581, 1609]], [[64935, 64935], "mapped", [1580, 1605, 1609]], [[64936, 64936], "mapped", [1587, 1582, 1609]], [[64937, 64937], "mapped", [1589, 1581, 1610]], [[64938, 64938], "mapped", [1588, 1581, 1610]], [[64939, 64939], "mapped", [1590, 1581, 1610]], [[64940, 64940], "mapped", [1604, 1580, 1610]], [[64941, 64941], "mapped", [1604, 1605, 1610]], [[64942, 64942], "mapped", [1610, 1581, 1610]], [[64943, 64943], "mapped", [1610, 1580, 1610]], [[64944, 64944], "mapped", [1610, 1605, 1610]], [[64945, 64945], "mapped", [1605, 1605, 1610]], [[64946, 64946], "mapped", [1602, 1605, 1610]], [[64947, 64947], "mapped", [1606, 1581, 1610]], [[64948, 64948], "mapped", [1602, 1605, 1581]], [[64949, 64949], "mapped", [1604, 1581, 1605]], [[64950, 64950], "mapped", [1593, 1605, 1610]], [[64951, 64951], "mapped", [1603, 1605, 1610]], [[64952, 64952], "mapped", [1606, 1580, 1581]], [[64953, 64953], "mapped", [1605, 1582, 1610]], [[64954, 64954], "mapped", [1604, 1580, 1605]], [[64955, 64955], "mapped", [1603, 1605, 1605]], [[64956, 64956], "mapped", [1604, 1580, 1605]], [[64957, 64957], "mapped", [1606, 1580, 1581]], [[64958, 64958], "mapped", [1580, 1581, 1610]], [[64959, 64959], "mapped", [1581, 1580, 1610]], [[64960, 64960], "mapped", [1605, 1580, 1610]], [[64961, 64961], "mapped", [1601, 1605, 1610]], [[64962, 64962], "mapped", [1576, 1581, 1610]], [[64963, 64963], "mapped", [1603, 1605, 1605]], [[64964, 64964], "mapped", [1593, 1580, 1605]], [[64965, 64965], "mapped", [1589, 1605, 1605]], [[64966, 64966], "mapped", [1587, 1582, 1610]], [[64967, 64967], "mapped", [1606, 1580, 1610]], [[64968, 64975], "disallowed"], [[64976, 65007], "disallowed"], [[65008, 65008], "mapped", [1589, 1604, 1746]], [[65009, 65009], "mapped", [1602, 1604, 1746]], [[65010, 65010], "mapped", [1575, 1604, 1604, 1607]], [[65011, 65011], "mapped", [1575, 1603, 1576, 1585]], [[65012, 65012], "mapped", [1605, 1581, 1605, 1583]], [[65013, 65013], "mapped", [1589, 1604, 1593, 1605]], [[65014, 65014], "mapped", [1585, 1587, 1608, 1604]], [[65015, 65015], "mapped", [1593, 1604, 1610, 1607]], [[65016, 65016], "mapped", [1608, 1587, 1604, 1605]], [[65017, 65017], "mapped", [1589, 1604, 1609]], [[65018, 65018], "disallowed_STD3_mapped", [1589, 1604, 1609, 32, 1575, 1604, 1604, 1607, 32, 1593, 1604, 1610, 1607, 32, 1608, 1587, 1604, 1605]], [[65019, 65019], "disallowed_STD3_mapped", [1580, 1604, 32, 1580, 1604, 1575, 1604, 1607]], [[65020, 65020], "mapped", [1585, 1740, 1575, 1604]], [[65021, 65021], "valid", [], "NV8"], [[65022, 65023], "disallowed"], [[65024, 65039], "ignored"], [[65040, 65040], "disallowed_STD3_mapped", [44]], [[65041, 65041], "mapped", [12289]], [[65042, 65042], "disallowed"], [[65043, 65043], "disallowed_STD3_mapped", [58]], [[65044, 65044], "disallowed_STD3_mapped", [59]], [[65045, 65045], "disallowed_STD3_mapped", [33]], [[65046, 65046], "disallowed_STD3_mapped", [63]], [[65047, 65047], "mapped", [12310]], [[65048, 65048], "mapped", [12311]], [[65049, 65049], "disallowed"], [[65050, 65055], "disallowed"], [[65056, 65059], "valid"], [[65060, 65062], "valid"], [[65063, 65069], "valid"], [[65070, 65071], "valid"], [[65072, 65072], "disallowed"], [[65073, 65073], "mapped", [8212]], [[65074, 65074], "mapped", [8211]], [[65075, 65076], "disallowed_STD3_mapped", [95]], [[65077, 65077], "disallowed_STD3_mapped", [40]], [[65078, 65078], "disallowed_STD3_mapped", [41]], [[65079, 65079], "disallowed_STD3_mapped", [123]], [[65080, 65080], "disallowed_STD3_mapped", [125]], [[65081, 65081], "mapped", [12308]], [[65082, 65082], "mapped", [12309]], [[65083, 65083], "mapped", [12304]], [[65084, 65084], "mapped", [12305]], [[65085, 65085], "mapped", [12298]], [[65086, 65086], "mapped", [12299]], [[65087, 65087], "mapped", [12296]], [[65088, 65088], "mapped", [12297]], [[65089, 65089], "mapped", [12300]], [[65090, 65090], "mapped", [12301]], [[65091, 65091], "mapped", [12302]], [[65092, 65092], "mapped", [12303]], [[65093, 65094], "valid", [], "NV8"], [[65095, 65095], "disallowed_STD3_mapped", [91]], [[65096, 65096], "disallowed_STD3_mapped", [93]], [[65097, 65100], "disallowed_STD3_mapped", [32, 773]], [[65101, 65103], "disallowed_STD3_mapped", [95]], [[65104, 65104], "disallowed_STD3_mapped", [44]], [[65105, 65105], "mapped", [12289]], [[65106, 65106], "disallowed"], [[65107, 65107], "disallowed"], [[65108, 65108], "disallowed_STD3_mapped", [59]], [[65109, 65109], "disallowed_STD3_mapped", [58]], [[65110, 65110], "disallowed_STD3_mapped", [63]], [[65111, 65111], "disallowed_STD3_mapped", [33]], [[65112, 65112], "mapped", [8212]], [[65113, 65113], "disallowed_STD3_mapped", [40]], [[65114, 65114], "disallowed_STD3_mapped", [41]], [[65115, 65115], "disallowed_STD3_mapped", [123]], [[65116, 65116], "disallowed_STD3_mapped", [125]], [[65117, 65117], "mapped", [12308]], [[65118, 65118], "mapped", [12309]], [[65119, 65119], "disallowed_STD3_mapped", [35]], [[65120, 65120], "disallowed_STD3_mapped", [38]], [[65121, 65121], "disallowed_STD3_mapped", [42]], [[65122, 65122], "disallowed_STD3_mapped", [43]], [[65123, 65123], "mapped", [45]], [[65124, 65124], "disallowed_STD3_mapped", [60]], [[65125, 65125], "disallowed_STD3_mapped", [62]], [[65126, 65126], "disallowed_STD3_mapped", [61]], [[65127, 65127], "disallowed"], [[65128, 65128], "disallowed_STD3_mapped", [92]], [[65129, 65129], "disallowed_STD3_mapped", [36]], [[65130, 65130], "disallowed_STD3_mapped", [37]], [[65131, 65131], "disallowed_STD3_mapped", [64]], [[65132, 65135], "disallowed"], [[65136, 65136], "disallowed_STD3_mapped", [32, 1611]], [[65137, 65137], "mapped", [1600, 1611]], [[65138, 65138], "disallowed_STD3_mapped", [32, 1612]], [[65139, 65139], "valid"], [[65140, 65140], "disallowed_STD3_mapped", [32, 1613]], [[65141, 65141], "disallowed"], [[65142, 65142], "disallowed_STD3_mapped", [32, 1614]], [[65143, 65143], "mapped", [1600, 1614]], [[65144, 65144], "disallowed_STD3_mapped", [32, 1615]], [[65145, 65145], "mapped", [1600, 1615]], [[65146, 65146], "disallowed_STD3_mapped", [32, 1616]], [[65147, 65147], "mapped", [1600, 1616]], [[65148, 65148], "disallowed_STD3_mapped", [32, 1617]], [[65149, 65149], "mapped", [1600, 1617]], [[65150, 65150], "disallowed_STD3_mapped", [32, 1618]], [[65151, 65151], "mapped", [1600, 1618]], [[65152, 65152], "mapped", [1569]], [[65153, 65154], "mapped", [1570]], [[65155, 65156], "mapped", [1571]], [[65157, 65158], "mapped", [1572]], [[65159, 65160], "mapped", [1573]], [[65161, 65164], "mapped", [1574]], [[65165, 65166], "mapped", [1575]], [[65167, 65170], "mapped", [1576]], [[65171, 65172], "mapped", [1577]], [[65173, 65176], "mapped", [1578]], [[65177, 65180], "mapped", [1579]], [[65181, 65184], "mapped", [1580]], [[65185, 65188], "mapped", [1581]], [[65189, 65192], "mapped", [1582]], [[65193, 65194], "mapped", [1583]], [[65195, 65196], "mapped", [1584]], [[65197, 65198], "mapped", [1585]], [[65199, 65200], "mapped", [1586]], [[65201, 65204], "mapped", [1587]], [[65205, 65208], "mapped", [1588]], [[65209, 65212], "mapped", [1589]], [[65213, 65216], "mapped", [1590]], [[65217, 65220], "mapped", [1591]], [[65221, 65224], "mapped", [1592]], [[65225, 65228], "mapped", [1593]], [[65229, 65232], "mapped", [1594]], [[65233, 65236], "mapped", [1601]], [[65237, 65240], "mapped", [1602]], [[65241, 65244], "mapped", [1603]], [[65245, 65248], "mapped", [1604]], [[65249, 65252], "mapped", [1605]], [[65253, 65256], "mapped", [1606]], [[65257, 65260], "mapped", [1607]], [[65261, 65262], "mapped", [1608]], [[65263, 65264], "mapped", [1609]], [[65265, 65268], "mapped", [1610]], [[65269, 65270], "mapped", [1604, 1570]], [[65271, 65272], "mapped", [1604, 1571]], [[65273, 65274], "mapped", [1604, 1573]], [[65275, 65276], "mapped", [1604, 1575]], [[65277, 65278], "disallowed"], [[65279, 65279], "ignored"], [[65280, 65280], "disallowed"], [[65281, 65281], "disallowed_STD3_mapped", [33]], [[65282, 65282], "disallowed_STD3_mapped", [34]], [[65283, 65283], "disallowed_STD3_mapped", [35]], [[65284, 65284], "disallowed_STD3_mapped", [36]], [[65285, 65285], "disallowed_STD3_mapped", [37]], [[65286, 65286], "disallowed_STD3_mapped", [38]], [[65287, 65287], "disallowed_STD3_mapped", [39]], [[65288, 65288], "disallowed_STD3_mapped", [40]], [[65289, 65289], "disallowed_STD3_mapped", [41]], [[65290, 65290], "disallowed_STD3_mapped", [42]], [[65291, 65291], "disallowed_STD3_mapped", [43]], [[65292, 65292], "disallowed_STD3_mapped", [44]], [[65293, 65293], "mapped", [45]], [[65294, 65294], "mapped", [46]], [[65295, 65295], "disallowed_STD3_mapped", [47]], [[65296, 65296], "mapped", [48]], [[65297, 65297], "mapped", [49]], [[65298, 65298], "mapped", [50]], [[65299, 65299], "mapped", [51]], [[65300, 65300], "mapped", [52]], [[65301, 65301], "mapped", [53]], [[65302, 65302], "mapped", [54]], [[65303, 65303], "mapped", [55]], [[65304, 65304], "mapped", [56]], [[65305, 65305], "mapped", [57]], [[65306, 65306], "disallowed_STD3_mapped", [58]], [[65307, 65307], "disallowed_STD3_mapped", [59]], [[65308, 65308], "disallowed_STD3_mapped", [60]], [[65309, 65309], "disallowed_STD3_mapped", [61]], [[65310, 65310], "disallowed_STD3_mapped", [62]], [[65311, 65311], "disallowed_STD3_mapped", [63]], [[65312, 65312], "disallowed_STD3_mapped", [64]], [[65313, 65313], "mapped", [97]], [[65314, 65314], "mapped", [98]], [[65315, 65315], "mapped", [99]], [[65316, 65316], "mapped", [100]], [[65317, 65317], "mapped", [101]], [[65318, 65318], "mapped", [102]], [[65319, 65319], "mapped", [103]], [[65320, 65320], "mapped", [104]], [[65321, 65321], "mapped", [105]], [[65322, 65322], "mapped", [106]], [[65323, 65323], "mapped", [107]], [[65324, 65324], "mapped", [108]], [[65325, 65325], "mapped", [109]], [[65326, 65326], "mapped", [110]], [[65327, 65327], "mapped", [111]], [[65328, 65328], "mapped", [112]], [[65329, 65329], "mapped", [113]], [[65330, 65330], "mapped", [114]], [[65331, 65331], "mapped", [115]], [[65332, 65332], "mapped", [116]], [[65333, 65333], "mapped", [117]], [[65334, 65334], "mapped", [118]], [[65335, 65335], "mapped", [119]], [[65336, 65336], "mapped", [120]], [[65337, 65337], "mapped", [121]], [[65338, 65338], "mapped", [122]], [[65339, 65339], "disallowed_STD3_mapped", [91]], [[65340, 65340], "disallowed_STD3_mapped", [92]], [[65341, 65341], "disallowed_STD3_mapped", [93]], [[65342, 65342], "disallowed_STD3_mapped", [94]], [[65343, 65343], "disallowed_STD3_mapped", [95]], [[65344, 65344], "disallowed_STD3_mapped", [96]], [[65345, 65345], "mapped", [97]], [[65346, 65346], "mapped", [98]], [[65347, 65347], "mapped", [99]], [[65348, 65348], "mapped", [100]], [[65349, 65349], "mapped", [101]], [[65350, 65350], "mapped", [102]], [[65351, 65351], "mapped", [103]], [[65352, 65352], "mapped", [104]], [[65353, 65353], "mapped", [105]], [[65354, 65354], "mapped", [106]], [[65355, 65355], "mapped", [107]], [[65356, 65356], "mapped", [108]], [[65357, 65357], "mapped", [109]], [[65358, 65358], "mapped", [110]], [[65359, 65359], "mapped", [111]], [[65360, 65360], "mapped", [112]], [[65361, 65361], "mapped", [113]], [[65362, 65362], "mapped", [114]], [[65363, 65363], "mapped", [115]], [[65364, 65364], "mapped", [116]], [[65365, 65365], "mapped", [117]], [[65366, 65366], "mapped", [118]], [[65367, 65367], "mapped", [119]], [[65368, 65368], "mapped", [120]], [[65369, 65369], "mapped", [121]], [[65370, 65370], "mapped", [122]], [[65371, 65371], "disallowed_STD3_mapped", [123]], [[65372, 65372], "disallowed_STD3_mapped", [124]], [[65373, 65373], "disallowed_STD3_mapped", [125]], [[65374, 65374], "disallowed_STD3_mapped", [126]], [[65375, 65375], "mapped", [10629]], [[65376, 65376], "mapped", [10630]], [[65377, 65377], "mapped", [46]], [[65378, 65378], "mapped", [12300]], [[65379, 65379], "mapped", [12301]], [[65380, 65380], "mapped", [12289]], [[65381, 65381], "mapped", [12539]], [[65382, 65382], "mapped", [12530]], [[65383, 65383], "mapped", [12449]], [[65384, 65384], "mapped", [12451]], [[65385, 65385], "mapped", [12453]], [[65386, 65386], "mapped", [12455]], [[65387, 65387], "mapped", [12457]], [[65388, 65388], "mapped", [12515]], [[65389, 65389], "mapped", [12517]], [[65390, 65390], "mapped", [12519]], [[65391, 65391], "mapped", [12483]], [[65392, 65392], "mapped", [12540]], [[65393, 65393], "mapped", [12450]], [[65394, 65394], "mapped", [12452]], [[65395, 65395], "mapped", [12454]], [[65396, 65396], "mapped", [12456]], [[65397, 65397], "mapped", [12458]], [[65398, 65398], "mapped", [12459]], [[65399, 65399], "mapped", [12461]], [[65400, 65400], "mapped", [12463]], [[65401, 65401], "mapped", [12465]], [[65402, 65402], "mapped", [12467]], [[65403, 65403], "mapped", [12469]], [[65404, 65404], "mapped", [12471]], [[65405, 65405], "mapped", [12473]], [[65406, 65406], "mapped", [12475]], [[65407, 65407], "mapped", [12477]], [[65408, 65408], "mapped", [12479]], [[65409, 65409], "mapped", [12481]], [[65410, 65410], "mapped", [12484]], [[65411, 65411], "mapped", [12486]], [[65412, 65412], "mapped", [12488]], [[65413, 65413], "mapped", [12490]], [[65414, 65414], "mapped", [12491]], [[65415, 65415], "mapped", [12492]], [[65416, 65416], "mapped", [12493]], [[65417, 65417], "mapped", [12494]], [[65418, 65418], "mapped", [12495]], [[65419, 65419], "mapped", [12498]], [[65420, 65420], "mapped", [12501]], [[65421, 65421], "mapped", [12504]], [[65422, 65422], "mapped", [12507]], [[65423, 65423], "mapped", [12510]], [[65424, 65424], "mapped", [12511]], [[65425, 65425], "mapped", [12512]], [[65426, 65426], "mapped", [12513]], [[65427, 65427], "mapped", [12514]], [[65428, 65428], "mapped", [12516]], [[65429, 65429], "mapped", [12518]], [[65430, 65430], "mapped", [12520]], [[65431, 65431], "mapped", [12521]], [[65432, 65432], "mapped", [12522]], [[65433, 65433], "mapped", [12523]], [[65434, 65434], "mapped", [12524]], [[65435, 65435], "mapped", [12525]], [[65436, 65436], "mapped", [12527]], [[65437, 65437], "mapped", [12531]], [[65438, 65438], "mapped", [12441]], [[65439, 65439], "mapped", [12442]], [[65440, 65440], "disallowed"], [[65441, 65441], "mapped", [4352]], [[65442, 65442], "mapped", [4353]], [[65443, 65443], "mapped", [4522]], [[65444, 65444], "mapped", [4354]], [[65445, 65445], "mapped", [4524]], [[65446, 65446], "mapped", [4525]], [[65447, 65447], "mapped", [4355]], [[65448, 65448], "mapped", [4356]], [[65449, 65449], "mapped", [4357]], [[65450, 65450], "mapped", [4528]], [[65451, 65451], "mapped", [4529]], [[65452, 65452], "mapped", [4530]], [[65453, 65453], "mapped", [4531]], [[65454, 65454], "mapped", [4532]], [[65455, 65455], "mapped", [4533]], [[65456, 65456], "mapped", [4378]], [[65457, 65457], "mapped", [4358]], [[65458, 65458], "mapped", [4359]], [[65459, 65459], "mapped", [4360]], [[65460, 65460], "mapped", [4385]], [[65461, 65461], "mapped", [4361]], [[65462, 65462], "mapped", [4362]], [[65463, 65463], "mapped", [4363]], [[65464, 65464], "mapped", [4364]], [[65465, 65465], "mapped", [4365]], [[65466, 65466], "mapped", [4366]], [[65467, 65467], "mapped", [4367]], [[65468, 65468], "mapped", [4368]], [[65469, 65469], "mapped", [4369]], [[65470, 65470], "mapped", [4370]], [[65471, 65473], "disallowed"], [[65474, 65474], "mapped", [4449]], [[65475, 65475], "mapped", [4450]], [[65476, 65476], "mapped", [4451]], [[65477, 65477], "mapped", [4452]], [[65478, 65478], "mapped", [4453]], [[65479, 65479], "mapped", [4454]], [[65480, 65481], "disallowed"], [[65482, 65482], "mapped", [4455]], [[65483, 65483], "mapped", [4456]], [[65484, 65484], "mapped", [4457]], [[65485, 65485], "mapped", [4458]], [[65486, 65486], "mapped", [4459]], [[65487, 65487], "mapped", [4460]], [[65488, 65489], "disallowed"], [[65490, 65490], "mapped", [4461]], [[65491, 65491], "mapped", [4462]], [[65492, 65492], "mapped", [4463]], [[65493, 65493], "mapped", [4464]], [[65494, 65494], "mapped", [4465]], [[65495, 65495], "mapped", [4466]], [[65496, 65497], "disallowed"], [[65498, 65498], "mapped", [4467]], [[65499, 65499], "mapped", [4468]], [[65500, 65500], "mapped", [4469]], [[65501, 65503], "disallowed"], [[65504, 65504], "mapped", [162]], [[65505, 65505], "mapped", [163]], [[65506, 65506], "mapped", [172]], [[65507, 65507], "disallowed_STD3_mapped", [32, 772]], [[65508, 65508], "mapped", [166]], [[65509, 65509], "mapped", [165]], [[65510, 65510], "mapped", [8361]], [[65511, 65511], "disallowed"], [[65512, 65512], "mapped", [9474]], [[65513, 65513], "mapped", [8592]], [[65514, 65514], "mapped", [8593]], [[65515, 65515], "mapped", [8594]], [[65516, 65516], "mapped", [8595]], [[65517, 65517], "mapped", [9632]], [[65518, 65518], "mapped", [9675]], [[65519, 65528], "disallowed"], [[65529, 65531], "disallowed"], [[65532, 65532], "disallowed"], [[65533, 65533], "disallowed"], [[65534, 65535], "disallowed"], [[65536, 65547], "valid"], [[65548, 65548], "disallowed"], [[65549, 65574], "valid"], [[65575, 65575], "disallowed"], [[65576, 65594], "valid"], [[65595, 65595], "disallowed"], [[65596, 65597], "valid"], [[65598, 65598], "disallowed"], [[65599, 65613], "valid"], [[65614, 65615], "disallowed"], [[65616, 65629], "valid"], [[65630, 65663], "disallowed"], [[65664, 65786], "valid"], [[65787, 65791], "disallowed"], [[65792, 65794], "valid", [], "NV8"], [[65795, 65798], "disallowed"], [[65799, 65843], "valid", [], "NV8"], [[65844, 65846], "disallowed"], [[65847, 65855], "valid", [], "NV8"], [[65856, 65930], "valid", [], "NV8"], [[65931, 65932], "valid", [], "NV8"], [[65933, 65935], "disallowed"], [[65936, 65947], "valid", [], "NV8"], [[65948, 65951], "disallowed"], [[65952, 65952], "valid", [], "NV8"], [[65953, 65999], "disallowed"], [[66e3, 66044], "valid", [], "NV8"], [[66045, 66045], "valid"], [[66046, 66175], "disallowed"], [[66176, 66204], "valid"], [[66205, 66207], "disallowed"], [[66208, 66256], "valid"], [[66257, 66271], "disallowed"], [[66272, 66272], "valid"], [[66273, 66299], "valid", [], "NV8"], [[66300, 66303], "disallowed"], [[66304, 66334], "valid"], [[66335, 66335], "valid"], [[66336, 66339], "valid", [], "NV8"], [[66340, 66351], "disallowed"], [[66352, 66368], "valid"], [[66369, 66369], "valid", [], "NV8"], [[66370, 66377], "valid"], [[66378, 66378], "valid", [], "NV8"], [[66379, 66383], "disallowed"], [[66384, 66426], "valid"], [[66427, 66431], "disallowed"], [[66432, 66461], "valid"], [[66462, 66462], "disallowed"], [[66463, 66463], "valid", [], "NV8"], [[66464, 66499], "valid"], [[66500, 66503], "disallowed"], [[66504, 66511], "valid"], [[66512, 66517], "valid", [], "NV8"], [[66518, 66559], "disallowed"], [[66560, 66560], "mapped", [66600]], [[66561, 66561], "mapped", [66601]], [[66562, 66562], "mapped", [66602]], [[66563, 66563], "mapped", [66603]], [[66564, 66564], "mapped", [66604]], [[66565, 66565], "mapped", [66605]], [[66566, 66566], "mapped", [66606]], [[66567, 66567], "mapped", [66607]], [[66568, 66568], "mapped", [66608]], [[66569, 66569], "mapped", [66609]], [[66570, 66570], "mapped", [66610]], [[66571, 66571], "mapped", [66611]], [[66572, 66572], "mapped", [66612]], [[66573, 66573], "mapped", [66613]], [[66574, 66574], "mapped", [66614]], [[66575, 66575], "mapped", [66615]], [[66576, 66576], "mapped", [66616]], [[66577, 66577], "mapped", [66617]], [[66578, 66578], "mapped", [66618]], [[66579, 66579], "mapped", [66619]], [[66580, 66580], "mapped", [66620]], [[66581, 66581], "mapped", [66621]], [[66582, 66582], "mapped", [66622]], [[66583, 66583], "mapped", [66623]], [[66584, 66584], "mapped", [66624]], [[66585, 66585], "mapped", [66625]], [[66586, 66586], "mapped", [66626]], [[66587, 66587], "mapped", [66627]], [[66588, 66588], "mapped", [66628]], [[66589, 66589], "mapped", [66629]], [[66590, 66590], "mapped", [66630]], [[66591, 66591], "mapped", [66631]], [[66592, 66592], "mapped", [66632]], [[66593, 66593], "mapped", [66633]], [[66594, 66594], "mapped", [66634]], [[66595, 66595], "mapped", [66635]], [[66596, 66596], "mapped", [66636]], [[66597, 66597], "mapped", [66637]], [[66598, 66598], "mapped", [66638]], [[66599, 66599], "mapped", [66639]], [[66600, 66637], "valid"], [[66638, 66717], "valid"], [[66718, 66719], "disallowed"], [[66720, 66729], "valid"], [[66730, 66815], "disallowed"], [[66816, 66855], "valid"], [[66856, 66863], "disallowed"], [[66864, 66915], "valid"], [[66916, 66926], "disallowed"], [[66927, 66927], "valid", [], "NV8"], [[66928, 67071], "disallowed"], [[67072, 67382], "valid"], [[67383, 67391], "disallowed"], [[67392, 67413], "valid"], [[67414, 67423], "disallowed"], [[67424, 67431], "valid"], [[67432, 67583], "disallowed"], [[67584, 67589], "valid"], [[67590, 67591], "disallowed"], [[67592, 67592], "valid"], [[67593, 67593], "disallowed"], [[67594, 67637], "valid"], [[67638, 67638], "disallowed"], [[67639, 67640], "valid"], [[67641, 67643], "disallowed"], [[67644, 67644], "valid"], [[67645, 67646], "disallowed"], [[67647, 67647], "valid"], [[67648, 67669], "valid"], [[67670, 67670], "disallowed"], [[67671, 67679], "valid", [], "NV8"], [[67680, 67702], "valid"], [[67703, 67711], "valid", [], "NV8"], [[67712, 67742], "valid"], [[67743, 67750], "disallowed"], [[67751, 67759], "valid", [], "NV8"], [[67760, 67807], "disallowed"], [[67808, 67826], "valid"], [[67827, 67827], "disallowed"], [[67828, 67829], "valid"], [[67830, 67834], "disallowed"], [[67835, 67839], "valid", [], "NV8"], [[67840, 67861], "valid"], [[67862, 67865], "valid", [], "NV8"], [[67866, 67867], "valid", [], "NV8"], [[67868, 67870], "disallowed"], [[67871, 67871], "valid", [], "NV8"], [[67872, 67897], "valid"], [[67898, 67902], "disallowed"], [[67903, 67903], "valid", [], "NV8"], [[67904, 67967], "disallowed"], [[67968, 68023], "valid"], [[68024, 68027], "disallowed"], [[68028, 68029], "valid", [], "NV8"], [[68030, 68031], "valid"], [[68032, 68047], "valid", [], "NV8"], [[68048, 68049], "disallowed"], [[68050, 68095], "valid", [], "NV8"], [[68096, 68099], "valid"], [[68100, 68100], "disallowed"], [[68101, 68102], "valid"], [[68103, 68107], "disallowed"], [[68108, 68115], "valid"], [[68116, 68116], "disallowed"], [[68117, 68119], "valid"], [[68120, 68120], "disallowed"], [[68121, 68147], "valid"], [[68148, 68151], "disallowed"], [[68152, 68154], "valid"], [[68155, 68158], "disallowed"], [[68159, 68159], "valid"], [[68160, 68167], "valid", [], "NV8"], [[68168, 68175], "disallowed"], [[68176, 68184], "valid", [], "NV8"], [[68185, 68191], "disallowed"], [[68192, 68220], "valid"], [[68221, 68223], "valid", [], "NV8"], [[68224, 68252], "valid"], [[68253, 68255], "valid", [], "NV8"], [[68256, 68287], "disallowed"], [[68288, 68295], "valid"], [[68296, 68296], "valid", [], "NV8"], [[68297, 68326], "valid"], [[68327, 68330], "disallowed"], [[68331, 68342], "valid", [], "NV8"], [[68343, 68351], "disallowed"], [[68352, 68405], "valid"], [[68406, 68408], "disallowed"], [[68409, 68415], "valid", [], "NV8"], [[68416, 68437], "valid"], [[68438, 68439], "disallowed"], [[68440, 68447], "valid", [], "NV8"], [[68448, 68466], "valid"], [[68467, 68471], "disallowed"], [[68472, 68479], "valid", [], "NV8"], [[68480, 68497], "valid"], [[68498, 68504], "disallowed"], [[68505, 68508], "valid", [], "NV8"], [[68509, 68520], "disallowed"], [[68521, 68527], "valid", [], "NV8"], [[68528, 68607], "disallowed"], [[68608, 68680], "valid"], [[68681, 68735], "disallowed"], [[68736, 68736], "mapped", [68800]], [[68737, 68737], "mapped", [68801]], [[68738, 68738], "mapped", [68802]], [[68739, 68739], "mapped", [68803]], [[68740, 68740], "mapped", [68804]], [[68741, 68741], "mapped", [68805]], [[68742, 68742], "mapped", [68806]], [[68743, 68743], "mapped", [68807]], [[68744, 68744], "mapped", [68808]], [[68745, 68745], "mapped", [68809]], [[68746, 68746], "mapped", [68810]], [[68747, 68747], "mapped", [68811]], [[68748, 68748], "mapped", [68812]], [[68749, 68749], "mapped", [68813]], [[68750, 68750], "mapped", [68814]], [[68751, 68751], "mapped", [68815]], [[68752, 68752], "mapped", [68816]], [[68753, 68753], "mapped", [68817]], [[68754, 68754], "mapped", [68818]], [[68755, 68755], "mapped", [68819]], [[68756, 68756], "mapped", [68820]], [[68757, 68757], "mapped", [68821]], [[68758, 68758], "mapped", [68822]], [[68759, 68759], "mapped", [68823]], [[68760, 68760], "mapped", [68824]], [[68761, 68761], "mapped", [68825]], [[68762, 68762], "mapped", [68826]], [[68763, 68763], "mapped", [68827]], [[68764, 68764], "mapped", [68828]], [[68765, 68765], "mapped", [68829]], [[68766, 68766], "mapped", [68830]], [[68767, 68767], "mapped", [68831]], [[68768, 68768], "mapped", [68832]], [[68769, 68769], "mapped", [68833]], [[68770, 68770], "mapped", [68834]], [[68771, 68771], "mapped", [68835]], [[68772, 68772], "mapped", [68836]], [[68773, 68773], "mapped", [68837]], [[68774, 68774], "mapped", [68838]], [[68775, 68775], "mapped", [68839]], [[68776, 68776], "mapped", [68840]], [[68777, 68777], "mapped", [68841]], [[68778, 68778], "mapped", [68842]], [[68779, 68779], "mapped", [68843]], [[68780, 68780], "mapped", [68844]], [[68781, 68781], "mapped", [68845]], [[68782, 68782], "mapped", [68846]], [[68783, 68783], "mapped", [68847]], [[68784, 68784], "mapped", [68848]], [[68785, 68785], "mapped", [68849]], [[68786, 68786], "mapped", [68850]], [[68787, 68799], "disallowed"], [[68800, 68850], "valid"], [[68851, 68857], "disallowed"], [[68858, 68863], "valid", [], "NV8"], [[68864, 69215], "disallowed"], [[69216, 69246], "valid", [], "NV8"], [[69247, 69631], "disallowed"], [[69632, 69702], "valid"], [[69703, 69709], "valid", [], "NV8"], [[69710, 69713], "disallowed"], [[69714, 69733], "valid", [], "NV8"], [[69734, 69743], "valid"], [[69744, 69758], "disallowed"], [[69759, 69759], "valid"], [[69760, 69818], "valid"], [[69819, 69820], "valid", [], "NV8"], [[69821, 69821], "disallowed"], [[69822, 69825], "valid", [], "NV8"], [[69826, 69839], "disallowed"], [[69840, 69864], "valid"], [[69865, 69871], "disallowed"], [[69872, 69881], "valid"], [[69882, 69887], "disallowed"], [[69888, 69940], "valid"], [[69941, 69941], "disallowed"], [[69942, 69951], "valid"], [[69952, 69955], "valid", [], "NV8"], [[69956, 69967], "disallowed"], [[69968, 70003], "valid"], [[70004, 70005], "valid", [], "NV8"], [[70006, 70006], "valid"], [[70007, 70015], "disallowed"], [[70016, 70084], "valid"], [[70085, 70088], "valid", [], "NV8"], [[70089, 70089], "valid", [], "NV8"], [[70090, 70092], "valid"], [[70093, 70093], "valid", [], "NV8"], [[70094, 70095], "disallowed"], [[70096, 70105], "valid"], [[70106, 70106], "valid"], [[70107, 70107], "valid", [], "NV8"], [[70108, 70108], "valid"], [[70109, 70111], "valid", [], "NV8"], [[70112, 70112], "disallowed"], [[70113, 70132], "valid", [], "NV8"], [[70133, 70143], "disallowed"], [[70144, 70161], "valid"], [[70162, 70162], "disallowed"], [[70163, 70199], "valid"], [[70200, 70205], "valid", [], "NV8"], [[70206, 70271], "disallowed"], [[70272, 70278], "valid"], [[70279, 70279], "disallowed"], [[70280, 70280], "valid"], [[70281, 70281], "disallowed"], [[70282, 70285], "valid"], [[70286, 70286], "disallowed"], [[70287, 70301], "valid"], [[70302, 70302], "disallowed"], [[70303, 70312], "valid"], [[70313, 70313], "valid", [], "NV8"], [[70314, 70319], "disallowed"], [[70320, 70378], "valid"], [[70379, 70383], "disallowed"], [[70384, 70393], "valid"], [[70394, 70399], "disallowed"], [[70400, 70400], "valid"], [[70401, 70403], "valid"], [[70404, 70404], "disallowed"], [[70405, 70412], "valid"], [[70413, 70414], "disallowed"], [[70415, 70416], "valid"], [[70417, 70418], "disallowed"], [[70419, 70440], "valid"], [[70441, 70441], "disallowed"], [[70442, 70448], "valid"], [[70449, 70449], "disallowed"], [[70450, 70451], "valid"], [[70452, 70452], "disallowed"], [[70453, 70457], "valid"], [[70458, 70459], "disallowed"], [[70460, 70468], "valid"], [[70469, 70470], "disallowed"], [[70471, 70472], "valid"], [[70473, 70474], "disallowed"], [[70475, 70477], "valid"], [[70478, 70479], "disallowed"], [[70480, 70480], "valid"], [[70481, 70486], "disallowed"], [[70487, 70487], "valid"], [[70488, 70492], "disallowed"], [[70493, 70499], "valid"], [[70500, 70501], "disallowed"], [[70502, 70508], "valid"], [[70509, 70511], "disallowed"], [[70512, 70516], "valid"], [[70517, 70783], "disallowed"], [[70784, 70853], "valid"], [[70854, 70854], "valid", [], "NV8"], [[70855, 70855], "valid"], [[70856, 70863], "disallowed"], [[70864, 70873], "valid"], [[70874, 71039], "disallowed"], [[71040, 71093], "valid"], [[71094, 71095], "disallowed"], [[71096, 71104], "valid"], [[71105, 71113], "valid", [], "NV8"], [[71114, 71127], "valid", [], "NV8"], [[71128, 71133], "valid"], [[71134, 71167], "disallowed"], [[71168, 71232], "valid"], [[71233, 71235], "valid", [], "NV8"], [[71236, 71236], "valid"], [[71237, 71247], "disallowed"], [[71248, 71257], "valid"], [[71258, 71295], "disallowed"], [[71296, 71351], "valid"], [[71352, 71359], "disallowed"], [[71360, 71369], "valid"], [[71370, 71423], "disallowed"], [[71424, 71449], "valid"], [[71450, 71452], "disallowed"], [[71453, 71467], "valid"], [[71468, 71471], "disallowed"], [[71472, 71481], "valid"], [[71482, 71487], "valid", [], "NV8"], [[71488, 71839], "disallowed"], [[71840, 71840], "mapped", [71872]], [[71841, 71841], "mapped", [71873]], [[71842, 71842], "mapped", [71874]], [[71843, 71843], "mapped", [71875]], [[71844, 71844], "mapped", [71876]], [[71845, 71845], "mapped", [71877]], [[71846, 71846], "mapped", [71878]], [[71847, 71847], "mapped", [71879]], [[71848, 71848], "mapped", [71880]], [[71849, 71849], "mapped", [71881]], [[71850, 71850], "mapped", [71882]], [[71851, 71851], "mapped", [71883]], [[71852, 71852], "mapped", [71884]], [[71853, 71853], "mapped", [71885]], [[71854, 71854], "mapped", [71886]], [[71855, 71855], "mapped", [71887]], [[71856, 71856], "mapped", [71888]], [[71857, 71857], "mapped", [71889]], [[71858, 71858], "mapped", [71890]], [[71859, 71859], "mapped", [71891]], [[71860, 71860], "mapped", [71892]], [[71861, 71861], "mapped", [71893]], [[71862, 71862], "mapped", [71894]], [[71863, 71863], "mapped", [71895]], [[71864, 71864], "mapped", [71896]], [[71865, 71865], "mapped", [71897]], [[71866, 71866], "mapped", [71898]], [[71867, 71867], "mapped", [71899]], [[71868, 71868], "mapped", [71900]], [[71869, 71869], "mapped", [71901]], [[71870, 71870], "mapped", [71902]], [[71871, 71871], "mapped", [71903]], [[71872, 71913], "valid"], [[71914, 71922], "valid", [], "NV8"], [[71923, 71934], "disallowed"], [[71935, 71935], "valid"], [[71936, 72383], "disallowed"], [[72384, 72440], "valid"], [[72441, 73727], "disallowed"], [[73728, 74606], "valid"], [[74607, 74648], "valid"], [[74649, 74649], "valid"], [[74650, 74751], "disallowed"], [[74752, 74850], "valid", [], "NV8"], [[74851, 74862], "valid", [], "NV8"], [[74863, 74863], "disallowed"], [[74864, 74867], "valid", [], "NV8"], [[74868, 74868], "valid", [], "NV8"], [[74869, 74879], "disallowed"], [[74880, 75075], "valid"], [[75076, 77823], "disallowed"], [[77824, 78894], "valid"], [[78895, 82943], "disallowed"], [[82944, 83526], "valid"], [[83527, 92159], "disallowed"], [[92160, 92728], "valid"], [[92729, 92735], "disallowed"], [[92736, 92766], "valid"], [[92767, 92767], "disallowed"], [[92768, 92777], "valid"], [[92778, 92781], "disallowed"], [[92782, 92783], "valid", [], "NV8"], [[92784, 92879], "disallowed"], [[92880, 92909], "valid"], [[92910, 92911], "disallowed"], [[92912, 92916], "valid"], [[92917, 92917], "valid", [], "NV8"], [[92918, 92927], "disallowed"], [[92928, 92982], "valid"], [[92983, 92991], "valid", [], "NV8"], [[92992, 92995], "valid"], [[92996, 92997], "valid", [], "NV8"], [[92998, 93007], "disallowed"], [[93008, 93017], "valid"], [[93018, 93018], "disallowed"], [[93019, 93025], "valid", [], "NV8"], [[93026, 93026], "disallowed"], [[93027, 93047], "valid"], [[93048, 93052], "disallowed"], [[93053, 93071], "valid"], [[93072, 93951], "disallowed"], [[93952, 94020], "valid"], [[94021, 94031], "disallowed"], [[94032, 94078], "valid"], [[94079, 94094], "disallowed"], [[94095, 94111], "valid"], [[94112, 110591], "disallowed"], [[110592, 110593], "valid"], [[110594, 113663], "disallowed"], [[113664, 113770], "valid"], [[113771, 113775], "disallowed"], [[113776, 113788], "valid"], [[113789, 113791], "disallowed"], [[113792, 113800], "valid"], [[113801, 113807], "disallowed"], [[113808, 113817], "valid"], [[113818, 113819], "disallowed"], [[113820, 113820], "valid", [], "NV8"], [[113821, 113822], "valid"], [[113823, 113823], "valid", [], "NV8"], [[113824, 113827], "ignored"], [[113828, 118783], "disallowed"], [[118784, 119029], "valid", [], "NV8"], [[119030, 119039], "disallowed"], [[119040, 119078], "valid", [], "NV8"], [[119079, 119080], "disallowed"], [[119081, 119081], "valid", [], "NV8"], [[119082, 119133], "valid", [], "NV8"], [[119134, 119134], "mapped", [119127, 119141]], [[119135, 119135], "mapped", [119128, 119141]], [[119136, 119136], "mapped", [119128, 119141, 119150]], [[119137, 119137], "mapped", [119128, 119141, 119151]], [[119138, 119138], "mapped", [119128, 119141, 119152]], [[119139, 119139], "mapped", [119128, 119141, 119153]], [[119140, 119140], "mapped", [119128, 119141, 119154]], [[119141, 119154], "valid", [], "NV8"], [[119155, 119162], "disallowed"], [[119163, 119226], "valid", [], "NV8"], [[119227, 119227], "mapped", [119225, 119141]], [[119228, 119228], "mapped", [119226, 119141]], [[119229, 119229], "mapped", [119225, 119141, 119150]], [[119230, 119230], "mapped", [119226, 119141, 119150]], [[119231, 119231], "mapped", [119225, 119141, 119151]], [[119232, 119232], "mapped", [119226, 119141, 119151]], [[119233, 119261], "valid", [], "NV8"], [[119262, 119272], "valid", [], "NV8"], [[119273, 119295], "disallowed"], [[119296, 119365], "valid", [], "NV8"], [[119366, 119551], "disallowed"], [[119552, 119638], "valid", [], "NV8"], [[119639, 119647], "disallowed"], [[119648, 119665], "valid", [], "NV8"], [[119666, 119807], "disallowed"], [[119808, 119808], "mapped", [97]], [[119809, 119809], "mapped", [98]], [[119810, 119810], "mapped", [99]], [[119811, 119811], "mapped", [100]], [[119812, 119812], "mapped", [101]], [[119813, 119813], "mapped", [102]], [[119814, 119814], "mapped", [103]], [[119815, 119815], "mapped", [104]], [[119816, 119816], "mapped", [105]], [[119817, 119817], "mapped", [106]], [[119818, 119818], "mapped", [107]], [[119819, 119819], "mapped", [108]], [[119820, 119820], "mapped", [109]], [[119821, 119821], "mapped", [110]], [[119822, 119822], "mapped", [111]], [[119823, 119823], "mapped", [112]], [[119824, 119824], "mapped", [113]], [[119825, 119825], "mapped", [114]], [[119826, 119826], "mapped", [115]], [[119827, 119827], "mapped", [116]], [[119828, 119828], "mapped", [117]], [[119829, 119829], "mapped", [118]], [[119830, 119830], "mapped", [119]], [[119831, 119831], "mapped", [120]], [[119832, 119832], "mapped", [121]], [[119833, 119833], "mapped", [122]], [[119834, 119834], "mapped", [97]], [[119835, 119835], "mapped", [98]], [[119836, 119836], "mapped", [99]], [[119837, 119837], "mapped", [100]], [[119838, 119838], "mapped", [101]], [[119839, 119839], "mapped", [102]], [[119840, 119840], "mapped", [103]], [[119841, 119841], "mapped", [104]], [[119842, 119842], "mapped", [105]], [[119843, 119843], "mapped", [106]], [[119844, 119844], "mapped", [107]], [[119845, 119845], "mapped", [108]], [[119846, 119846], "mapped", [109]], [[119847, 119847], "mapped", [110]], [[119848, 119848], "mapped", [111]], [[119849, 119849], "mapped", [112]], [[119850, 119850], "mapped", [113]], [[119851, 119851], "mapped", [114]], [[119852, 119852], "mapped", [115]], [[119853, 119853], "mapped", [116]], [[119854, 119854], "mapped", [117]], [[119855, 119855], "mapped", [118]], [[119856, 119856], "mapped", [119]], [[119857, 119857], "mapped", [120]], [[119858, 119858], "mapped", [121]], [[119859, 119859], "mapped", [122]], [[119860, 119860], "mapped", [97]], [[119861, 119861], "mapped", [98]], [[119862, 119862], "mapped", [99]], [[119863, 119863], "mapped", [100]], [[119864, 119864], "mapped", [101]], [[119865, 119865], "mapped", [102]], [[119866, 119866], "mapped", [103]], [[119867, 119867], "mapped", [104]], [[119868, 119868], "mapped", [105]], [[119869, 119869], "mapped", [106]], [[119870, 119870], "mapped", [107]], [[119871, 119871], "mapped", [108]], [[119872, 119872], "mapped", [109]], [[119873, 119873], "mapped", [110]], [[119874, 119874], "mapped", [111]], [[119875, 119875], "mapped", [112]], [[119876, 119876], "mapped", [113]], [[119877, 119877], "mapped", [114]], [[119878, 119878], "mapped", [115]], [[119879, 119879], "mapped", [116]], [[119880, 119880], "mapped", [117]], [[119881, 119881], "mapped", [118]], [[119882, 119882], "mapped", [119]], [[119883, 119883], "mapped", [120]], [[119884, 119884], "mapped", [121]], [[119885, 119885], "mapped", [122]], [[119886, 119886], "mapped", [97]], [[119887, 119887], "mapped", [98]], [[119888, 119888], "mapped", [99]], [[119889, 119889], "mapped", [100]], [[119890, 119890], "mapped", [101]], [[119891, 119891], "mapped", [102]], [[119892, 119892], "mapped", [103]], [[119893, 119893], "disallowed"], [[119894, 119894], "mapped", [105]], [[119895, 119895], "mapped", [106]], [[119896, 119896], "mapped", [107]], [[119897, 119897], "mapped", [108]], [[119898, 119898], "mapped", [109]], [[119899, 119899], "mapped", [110]], [[119900, 119900], "mapped", [111]], [[119901, 119901], "mapped", [112]], [[119902, 119902], "mapped", [113]], [[119903, 119903], "mapped", [114]], [[119904, 119904], "mapped", [115]], [[119905, 119905], "mapped", [116]], [[119906, 119906], "mapped", [117]], [[119907, 119907], "mapped", [118]], [[119908, 119908], "mapped", [119]], [[119909, 119909], "mapped", [120]], [[119910, 119910], "mapped", [121]], [[119911, 119911], "mapped", [122]], [[119912, 119912], "mapped", [97]], [[119913, 119913], "mapped", [98]], [[119914, 119914], "mapped", [99]], [[119915, 119915], "mapped", [100]], [[119916, 119916], "mapped", [101]], [[119917, 119917], "mapped", [102]], [[119918, 119918], "mapped", [103]], [[119919, 119919], "mapped", [104]], [[119920, 119920], "mapped", [105]], [[119921, 119921], "mapped", [106]], [[119922, 119922], "mapped", [107]], [[119923, 119923], "mapped", [108]], [[119924, 119924], "mapped", [109]], [[119925, 119925], "mapped", [110]], [[119926, 119926], "mapped", [111]], [[119927, 119927], "mapped", [112]], [[119928, 119928], "mapped", [113]], [[119929, 119929], "mapped", [114]], [[119930, 119930], "mapped", [115]], [[119931, 119931], "mapped", [116]], [[119932, 119932], "mapped", [117]], [[119933, 119933], "mapped", [118]], [[119934, 119934], "mapped", [119]], [[119935, 119935], "mapped", [120]], [[119936, 119936], "mapped", [121]], [[119937, 119937], "mapped", [122]], [[119938, 119938], "mapped", [97]], [[119939, 119939], "mapped", [98]], [[119940, 119940], "mapped", [99]], [[119941, 119941], "mapped", [100]], [[119942, 119942], "mapped", [101]], [[119943, 119943], "mapped", [102]], [[119944, 119944], "mapped", [103]], [[119945, 119945], "mapped", [104]], [[119946, 119946], "mapped", [105]], [[119947, 119947], "mapped", [106]], [[119948, 119948], "mapped", [107]], [[119949, 119949], "mapped", [108]], [[119950, 119950], "mapped", [109]], [[119951, 119951], "mapped", [110]], [[119952, 119952], "mapped", [111]], [[119953, 119953], "mapped", [112]], [[119954, 119954], "mapped", [113]], [[119955, 119955], "mapped", [114]], [[119956, 119956], "mapped", [115]], [[119957, 119957], "mapped", [116]], [[119958, 119958], "mapped", [117]], [[119959, 119959], "mapped", [118]], [[119960, 119960], "mapped", [119]], [[119961, 119961], "mapped", [120]], [[119962, 119962], "mapped", [121]], [[119963, 119963], "mapped", [122]], [[119964, 119964], "mapped", [97]], [[119965, 119965], "disallowed"], [[119966, 119966], "mapped", [99]], [[119967, 119967], "mapped", [100]], [[119968, 119969], "disallowed"], [[119970, 119970], "mapped", [103]], [[119971, 119972], "disallowed"], [[119973, 119973], "mapped", [106]], [[119974, 119974], "mapped", [107]], [[119975, 119976], "disallowed"], [[119977, 119977], "mapped", [110]], [[119978, 119978], "mapped", [111]], [[119979, 119979], "mapped", [112]], [[119980, 119980], "mapped", [113]], [[119981, 119981], "disallowed"], [[119982, 119982], "mapped", [115]], [[119983, 119983], "mapped", [116]], [[119984, 119984], "mapped", [117]], [[119985, 119985], "mapped", [118]], [[119986, 119986], "mapped", [119]], [[119987, 119987], "mapped", [120]], [[119988, 119988], "mapped", [121]], [[119989, 119989], "mapped", [122]], [[119990, 119990], "mapped", [97]], [[119991, 119991], "mapped", [98]], [[119992, 119992], "mapped", [99]], [[119993, 119993], "mapped", [100]], [[119994, 119994], "disallowed"], [[119995, 119995], "mapped", [102]], [[119996, 119996], "disallowed"], [[119997, 119997], "mapped", [104]], [[119998, 119998], "mapped", [105]], [[119999, 119999], "mapped", [106]], [[12e4, 12e4], "mapped", [107]], [[120001, 120001], "mapped", [108]], [[120002, 120002], "mapped", [109]], [[120003, 120003], "mapped", [110]], [[120004, 120004], "disallowed"], [[120005, 120005], "mapped", [112]], [[120006, 120006], "mapped", [113]], [[120007, 120007], "mapped", [114]], [[120008, 120008], "mapped", [115]], [[120009, 120009], "mapped", [116]], [[120010, 120010], "mapped", [117]], [[120011, 120011], "mapped", [118]], [[120012, 120012], "mapped", [119]], [[120013, 120013], "mapped", [120]], [[120014, 120014], "mapped", [121]], [[120015, 120015], "mapped", [122]], [[120016, 120016], "mapped", [97]], [[120017, 120017], "mapped", [98]], [[120018, 120018], "mapped", [99]], [[120019, 120019], "mapped", [100]], [[120020, 120020], "mapped", [101]], [[120021, 120021], "mapped", [102]], [[120022, 120022], "mapped", [103]], [[120023, 120023], "mapped", [104]], [[120024, 120024], "mapped", [105]], [[120025, 120025], "mapped", [106]], [[120026, 120026], "mapped", [107]], [[120027, 120027], "mapped", [108]], [[120028, 120028], "mapped", [109]], [[120029, 120029], "mapped", [110]], [[120030, 120030], "mapped", [111]], [[120031, 120031], "mapped", [112]], [[120032, 120032], "mapped", [113]], [[120033, 120033], "mapped", [114]], [[120034, 120034], "mapped", [115]], [[120035, 120035], "mapped", [116]], [[120036, 120036], "mapped", [117]], [[120037, 120037], "mapped", [118]], [[120038, 120038], "mapped", [119]], [[120039, 120039], "mapped", [120]], [[120040, 120040], "mapped", [121]], [[120041, 120041], "mapped", [122]], [[120042, 120042], "mapped", [97]], [[120043, 120043], "mapped", [98]], [[120044, 120044], "mapped", [99]], [[120045, 120045], "mapped", [100]], [[120046, 120046], "mapped", [101]], [[120047, 120047], "mapped", [102]], [[120048, 120048], "mapped", [103]], [[120049, 120049], "mapped", [104]], [[120050, 120050], "mapped", [105]], [[120051, 120051], "mapped", [106]], [[120052, 120052], "mapped", [107]], [[120053, 120053], "mapped", [108]], [[120054, 120054], "mapped", [109]], [[120055, 120055], "mapped", [110]], [[120056, 120056], "mapped", [111]], [[120057, 120057], "mapped", [112]], [[120058, 120058], "mapped", [113]], [[120059, 120059], "mapped", [114]], [[120060, 120060], "mapped", [115]], [[120061, 120061], "mapped", [116]], [[120062, 120062], "mapped", [117]], [[120063, 120063], "mapped", [118]], [[120064, 120064], "mapped", [119]], [[120065, 120065], "mapped", [120]], [[120066, 120066], "mapped", [121]], [[120067, 120067], "mapped", [122]], [[120068, 120068], "mapped", [97]], [[120069, 120069], "mapped", [98]], [[120070, 120070], "disallowed"], [[120071, 120071], "mapped", [100]], [[120072, 120072], "mapped", [101]], [[120073, 120073], "mapped", [102]], [[120074, 120074], "mapped", [103]], [[120075, 120076], "disallowed"], [[120077, 120077], "mapped", [106]], [[120078, 120078], "mapped", [107]], [[120079, 120079], "mapped", [108]], [[120080, 120080], "mapped", [109]], [[120081, 120081], "mapped", [110]], [[120082, 120082], "mapped", [111]], [[120083, 120083], "mapped", [112]], [[120084, 120084], "mapped", [113]], [[120085, 120085], "disallowed"], [[120086, 120086], "mapped", [115]], [[120087, 120087], "mapped", [116]], [[120088, 120088], "mapped", [117]], [[120089, 120089], "mapped", [118]], [[120090, 120090], "mapped", [119]], [[120091, 120091], "mapped", [120]], [[120092, 120092], "mapped", [121]], [[120093, 120093], "disallowed"], [[120094, 120094], "mapped", [97]], [[120095, 120095], "mapped", [98]], [[120096, 120096], "mapped", [99]], [[120097, 120097], "mapped", [100]], [[120098, 120098], "mapped", [101]], [[120099, 120099], "mapped", [102]], [[120100, 120100], "mapped", [103]], [[120101, 120101], "mapped", [104]], [[120102, 120102], "mapped", [105]], [[120103, 120103], "mapped", [106]], [[120104, 120104], "mapped", [107]], [[120105, 120105], "mapped", [108]], [[120106, 120106], "mapped", [109]], [[120107, 120107], "mapped", [110]], [[120108, 120108], "mapped", [111]], [[120109, 120109], "mapped", [112]], [[120110, 120110], "mapped", [113]], [[120111, 120111], "mapped", [114]], [[120112, 120112], "mapped", [115]], [[120113, 120113], "mapped", [116]], [[120114, 120114], "mapped", [117]], [[120115, 120115], "mapped", [118]], [[120116, 120116], "mapped", [119]], [[120117, 120117], "mapped", [120]], [[120118, 120118], "mapped", [121]], [[120119, 120119], "mapped", [122]], [[120120, 120120], "mapped", [97]], [[120121, 120121], "mapped", [98]], [[120122, 120122], "disallowed"], [[120123, 120123], "mapped", [100]], [[120124, 120124], "mapped", [101]], [[120125, 120125], "mapped", [102]], [[120126, 120126], "mapped", [103]], [[120127, 120127], "disallowed"], [[120128, 120128], "mapped", [105]], [[120129, 120129], "mapped", [106]], [[120130, 120130], "mapped", [107]], [[120131, 120131], "mapped", [108]], [[120132, 120132], "mapped", [109]], [[120133, 120133], "disallowed"], [[120134, 120134], "mapped", [111]], [[120135, 120137], "disallowed"], [[120138, 120138], "mapped", [115]], [[120139, 120139], "mapped", [116]], [[120140, 120140], "mapped", [117]], [[120141, 120141], "mapped", [118]], [[120142, 120142], "mapped", [119]], [[120143, 120143], "mapped", [120]], [[120144, 120144], "mapped", [121]], [[120145, 120145], "disallowed"], [[120146, 120146], "mapped", [97]], [[120147, 120147], "mapped", [98]], [[120148, 120148], "mapped", [99]], [[120149, 120149], "mapped", [100]], [[120150, 120150], "mapped", [101]], [[120151, 120151], "mapped", [102]], [[120152, 120152], "mapped", [103]], [[120153, 120153], "mapped", [104]], [[120154, 120154], "mapped", [105]], [[120155, 120155], "mapped", [106]], [[120156, 120156], "mapped", [107]], [[120157, 120157], "mapped", [108]], [[120158, 120158], "mapped", [109]], [[120159, 120159], "mapped", [110]], [[120160, 120160], "mapped", [111]], [[120161, 120161], "mapped", [112]], [[120162, 120162], "mapped", [113]], [[120163, 120163], "mapped", [114]], [[120164, 120164], "mapped", [115]], [[120165, 120165], "mapped", [116]], [[120166, 120166], "mapped", [117]], [[120167, 120167], "mapped", [118]], [[120168, 120168], "mapped", [119]], [[120169, 120169], "mapped", [120]], [[120170, 120170], "mapped", [121]], [[120171, 120171], "mapped", [122]], [[120172, 120172], "mapped", [97]], [[120173, 120173], "mapped", [98]], [[120174, 120174], "mapped", [99]], [[120175, 120175], "mapped", [100]], [[120176, 120176], "mapped", [101]], [[120177, 120177], "mapped", [102]], [[120178, 120178], "mapped", [103]], [[120179, 120179], "mapped", [104]], [[120180, 120180], "mapped", [105]], [[120181, 120181], "mapped", [106]], [[120182, 120182], "mapped", [107]], [[120183, 120183], "mapped", [108]], [[120184, 120184], "mapped", [109]], [[120185, 120185], "mapped", [110]], [[120186, 120186], "mapped", [111]], [[120187, 120187], "mapped", [112]], [[120188, 120188], "mapped", [113]], [[120189, 120189], "mapped", [114]], [[120190, 120190], "mapped", [115]], [[120191, 120191], "mapped", [116]], [[120192, 120192], "mapped", [117]], [[120193, 120193], "mapped", [118]], [[120194, 120194], "mapped", [119]], [[120195, 120195], "mapped", [120]], [[120196, 120196], "mapped", [121]], [[120197, 120197], "mapped", [122]], [[120198, 120198], "mapped", [97]], [[120199, 120199], "mapped", [98]], [[120200, 120200], "mapped", [99]], [[120201, 120201], "mapped", [100]], [[120202, 120202], "mapped", [101]], [[120203, 120203], "mapped", [102]], [[120204, 120204], "mapped", [103]], [[120205, 120205], "mapped", [104]], [[120206, 120206], "mapped", [105]], [[120207, 120207], "mapped", [106]], [[120208, 120208], "mapped", [107]], [[120209, 120209], "mapped", [108]], [[120210, 120210], "mapped", [109]], [[120211, 120211], "mapped", [110]], [[120212, 120212], "mapped", [111]], [[120213, 120213], "mapped", [112]], [[120214, 120214], "mapped", [113]], [[120215, 120215], "mapped", [114]], [[120216, 120216], "mapped", [115]], [[120217, 120217], "mapped", [116]], [[120218, 120218], "mapped", [117]], [[120219, 120219], "mapped", [118]], [[120220, 120220], "mapped", [119]], [[120221, 120221], "mapped", [120]], [[120222, 120222], "mapped", [121]], [[120223, 120223], "mapped", [122]], [[120224, 120224], "mapped", [97]], [[120225, 120225], "mapped", [98]], [[120226, 120226], "mapped", [99]], [[120227, 120227], "mapped", [100]], [[120228, 120228], "mapped", [101]], [[120229, 120229], "mapped", [102]], [[120230, 120230], "mapped", [103]], [[120231, 120231], "mapped", [104]], [[120232, 120232], "mapped", [105]], [[120233, 120233], "mapped", [106]], [[120234, 120234], "mapped", [107]], [[120235, 120235], "mapped", [108]], [[120236, 120236], "mapped", [109]], [[120237, 120237], "mapped", [110]], [[120238, 120238], "mapped", [111]], [[120239, 120239], "mapped", [112]], [[120240, 120240], "mapped", [113]], [[120241, 120241], "mapped", [114]], [[120242, 120242], "mapped", [115]], [[120243, 120243], "mapped", [116]], [[120244, 120244], "mapped", [117]], [[120245, 120245], "mapped", [118]], [[120246, 120246], "mapped", [119]], [[120247, 120247], "mapped", [120]], [[120248, 120248], "mapped", [121]], [[120249, 120249], "mapped", [122]], [[120250, 120250], "mapped", [97]], [[120251, 120251], "mapped", [98]], [[120252, 120252], "mapped", [99]], [[120253, 120253], "mapped", [100]], [[120254, 120254], "mapped", [101]], [[120255, 120255], "mapped", [102]], [[120256, 120256], "mapped", [103]], [[120257, 120257], "mapped", [104]], [[120258, 120258], "mapped", [105]], [[120259, 120259], "mapped", [106]], [[120260, 120260], "mapped", [107]], [[120261, 120261], "mapped", [108]], [[120262, 120262], "mapped", [109]], [[120263, 120263], "mapped", [110]], [[120264, 120264], "mapped", [111]], [[120265, 120265], "mapped", [112]], [[120266, 120266], "mapped", [113]], [[120267, 120267], "mapped", [114]], [[120268, 120268], "mapped", [115]], [[120269, 120269], "mapped", [116]], [[120270, 120270], "mapped", [117]], [[120271, 120271], "mapped", [118]], [[120272, 120272], "mapped", [119]], [[120273, 120273], "mapped", [120]], [[120274, 120274], "mapped", [121]], [[120275, 120275], "mapped", [122]], [[120276, 120276], "mapped", [97]], [[120277, 120277], "mapped", [98]], [[120278, 120278], "mapped", [99]], [[120279, 120279], "mapped", [100]], [[120280, 120280], "mapped", [101]], [[120281, 120281], "mapped", [102]], [[120282, 120282], "mapped", [103]], [[120283, 120283], "mapped", [104]], [[120284, 120284], "mapped", [105]], [[120285, 120285], "mapped", [106]], [[120286, 120286], "mapped", [107]], [[120287, 120287], "mapped", [108]], [[120288, 120288], "mapped", [109]], [[120289, 120289], "mapped", [110]], [[120290, 120290], "mapped", [111]], [[120291, 120291], "mapped", [112]], [[120292, 120292], "mapped", [113]], [[120293, 120293], "mapped", [114]], [[120294, 120294], "mapped", [115]], [[120295, 120295], "mapped", [116]], [[120296, 120296], "mapped", [117]], [[120297, 120297], "mapped", [118]], [[120298, 120298], "mapped", [119]], [[120299, 120299], "mapped", [120]], [[120300, 120300], "mapped", [121]], [[120301, 120301], "mapped", [122]], [[120302, 120302], "mapped", [97]], [[120303, 120303], "mapped", [98]], [[120304, 120304], "mapped", [99]], [[120305, 120305], "mapped", [100]], [[120306, 120306], "mapped", [101]], [[120307, 120307], "mapped", [102]], [[120308, 120308], "mapped", [103]], [[120309, 120309], "mapped", [104]], [[120310, 120310], "mapped", [105]], [[120311, 120311], "mapped", [106]], [[120312, 120312], "mapped", [107]], [[120313, 120313], "mapped", [108]], [[120314, 120314], "mapped", [109]], [[120315, 120315], "mapped", [110]], [[120316, 120316], "mapped", [111]], [[120317, 120317], "mapped", [112]], [[120318, 120318], "mapped", [113]], [[120319, 120319], "mapped", [114]], [[120320, 120320], "mapped", [115]], [[120321, 120321], "mapped", [116]], [[120322, 120322], "mapped", [117]], [[120323, 120323], "mapped", [118]], [[120324, 120324], "mapped", [119]], [[120325, 120325], "mapped", [120]], [[120326, 120326], "mapped", [121]], [[120327, 120327], "mapped", [122]], [[120328, 120328], "mapped", [97]], [[120329, 120329], "mapped", [98]], [[120330, 120330], "mapped", [99]], [[120331, 120331], "mapped", [100]], [[120332, 120332], "mapped", [101]], [[120333, 120333], "mapped", [102]], [[120334, 120334], "mapped", [103]], [[120335, 120335], "mapped", [104]], [[120336, 120336], "mapped", [105]], [[120337, 120337], "mapped", [106]], [[120338, 120338], "mapped", [107]], [[120339, 120339], "mapped", [108]], [[120340, 120340], "mapped", [109]], [[120341, 120341], "mapped", [110]], [[120342, 120342], "mapped", [111]], [[120343, 120343], "mapped", [112]], [[120344, 120344], "mapped", [113]], [[120345, 120345], "mapped", [114]], [[120346, 120346], "mapped", [115]], [[120347, 120347], "mapped", [116]], [[120348, 120348], "mapped", [117]], [[120349, 120349], "mapped", [118]], [[120350, 120350], "mapped", [119]], [[120351, 120351], "mapped", [120]], [[120352, 120352], "mapped", [121]], [[120353, 120353], "mapped", [122]], [[120354, 120354], "mapped", [97]], [[120355, 120355], "mapped", [98]], [[120356, 120356], "mapped", [99]], [[120357, 120357], "mapped", [100]], [[120358, 120358], "mapped", [101]], [[120359, 120359], "mapped", [102]], [[120360, 120360], "mapped", [103]], [[120361, 120361], "mapped", [104]], [[120362, 120362], "mapped", [105]], [[120363, 120363], "mapped", [106]], [[120364, 120364], "mapped", [107]], [[120365, 120365], "mapped", [108]], [[120366, 120366], "mapped", [109]], [[120367, 120367], "mapped", [110]], [[120368, 120368], "mapped", [111]], [[120369, 120369], "mapped", [112]], [[120370, 120370], "mapped", [113]], [[120371, 120371], "mapped", [114]], [[120372, 120372], "mapped", [115]], [[120373, 120373], "mapped", [116]], [[120374, 120374], "mapped", [117]], [[120375, 120375], "mapped", [118]], [[120376, 120376], "mapped", [119]], [[120377, 120377], "mapped", [120]], [[120378, 120378], "mapped", [121]], [[120379, 120379], "mapped", [122]], [[120380, 120380], "mapped", [97]], [[120381, 120381], "mapped", [98]], [[120382, 120382], "mapped", [99]], [[120383, 120383], "mapped", [100]], [[120384, 120384], "mapped", [101]], [[120385, 120385], "mapped", [102]], [[120386, 120386], "mapped", [103]], [[120387, 120387], "mapped", [104]], [[120388, 120388], "mapped", [105]], [[120389, 120389], "mapped", [106]], [[120390, 120390], "mapped", [107]], [[120391, 120391], "mapped", [108]], [[120392, 120392], "mapped", [109]], [[120393, 120393], "mapped", [110]], [[120394, 120394], "mapped", [111]], [[120395, 120395], "mapped", [112]], [[120396, 120396], "mapped", [113]], [[120397, 120397], "mapped", [114]], [[120398, 120398], "mapped", [115]], [[120399, 120399], "mapped", [116]], [[120400, 120400], "mapped", [117]], [[120401, 120401], "mapped", [118]], [[120402, 120402], "mapped", [119]], [[120403, 120403], "mapped", [120]], [[120404, 120404], "mapped", [121]], [[120405, 120405], "mapped", [122]], [[120406, 120406], "mapped", [97]], [[120407, 120407], "mapped", [98]], [[120408, 120408], "mapped", [99]], [[120409, 120409], "mapped", [100]], [[120410, 120410], "mapped", [101]], [[120411, 120411], "mapped", [102]], [[120412, 120412], "mapped", [103]], [[120413, 120413], "mapped", [104]], [[120414, 120414], "mapped", [105]], [[120415, 120415], "mapped", [106]], [[120416, 120416], "mapped", [107]], [[120417, 120417], "mapped", [108]], [[120418, 120418], "mapped", [109]], [[120419, 120419], "mapped", [110]], [[120420, 120420], "mapped", [111]], [[120421, 120421], "mapped", [112]], [[120422, 120422], "mapped", [113]], [[120423, 120423], "mapped", [114]], [[120424, 120424], "mapped", [115]], [[120425, 120425], "mapped", [116]], [[120426, 120426], "mapped", [117]], [[120427, 120427], "mapped", [118]], [[120428, 120428], "mapped", [119]], [[120429, 120429], "mapped", [120]], [[120430, 120430], "mapped", [121]], [[120431, 120431], "mapped", [122]], [[120432, 120432], "mapped", [97]], [[120433, 120433], "mapped", [98]], [[120434, 120434], "mapped", [99]], [[120435, 120435], "mapped", [100]], [[120436, 120436], "mapped", [101]], [[120437, 120437], "mapped", [102]], [[120438, 120438], "mapped", [103]], [[120439, 120439], "mapped", [104]], [[120440, 120440], "mapped", [105]], [[120441, 120441], "mapped", [106]], [[120442, 120442], "mapped", [107]], [[120443, 120443], "mapped", [108]], [[120444, 120444], "mapped", [109]], [[120445, 120445], "mapped", [110]], [[120446, 120446], "mapped", [111]], [[120447, 120447], "mapped", [112]], [[120448, 120448], "mapped", [113]], [[120449, 120449], "mapped", [114]], [[120450, 120450], "mapped", [115]], [[120451, 120451], "mapped", [116]], [[120452, 120452], "mapped", [117]], [[120453, 120453], "mapped", [118]], [[120454, 120454], "mapped", [119]], [[120455, 120455], "mapped", [120]], [[120456, 120456], "mapped", [121]], [[120457, 120457], "mapped", [122]], [[120458, 120458], "mapped", [97]], [[120459, 120459], "mapped", [98]], [[120460, 120460], "mapped", [99]], [[120461, 120461], "mapped", [100]], [[120462, 120462], "mapped", [101]], [[120463, 120463], "mapped", [102]], [[120464, 120464], "mapped", [103]], [[120465, 120465], "mapped", [104]], [[120466, 120466], "mapped", [105]], [[120467, 120467], "mapped", [106]], [[120468, 120468], "mapped", [107]], [[120469, 120469], "mapped", [108]], [[120470, 120470], "mapped", [109]], [[120471, 120471], "mapped", [110]], [[120472, 120472], "mapped", [111]], [[120473, 120473], "mapped", [112]], [[120474, 120474], "mapped", [113]], [[120475, 120475], "mapped", [114]], [[120476, 120476], "mapped", [115]], [[120477, 120477], "mapped", [116]], [[120478, 120478], "mapped", [117]], [[120479, 120479], "mapped", [118]], [[120480, 120480], "mapped", [119]], [[120481, 120481], "mapped", [120]], [[120482, 120482], "mapped", [121]], [[120483, 120483], "mapped", [122]], [[120484, 120484], "mapped", [305]], [[120485, 120485], "mapped", [567]], [[120486, 120487], "disallowed"], [[120488, 120488], "mapped", [945]], [[120489, 120489], "mapped", [946]], [[120490, 120490], "mapped", [947]], [[120491, 120491], "mapped", [948]], [[120492, 120492], "mapped", [949]], [[120493, 120493], "mapped", [950]], [[120494, 120494], "mapped", [951]], [[120495, 120495], "mapped", [952]], [[120496, 120496], "mapped", [953]], [[120497, 120497], "mapped", [954]], [[120498, 120498], "mapped", [955]], [[120499, 120499], "mapped", [956]], [[120500, 120500], "mapped", [957]], [[120501, 120501], "mapped", [958]], [[120502, 120502], "mapped", [959]], [[120503, 120503], "mapped", [960]], [[120504, 120504], "mapped", [961]], [[120505, 120505], "mapped", [952]], [[120506, 120506], "mapped", [963]], [[120507, 120507], "mapped", [964]], [[120508, 120508], "mapped", [965]], [[120509, 120509], "mapped", [966]], [[120510, 120510], "mapped", [967]], [[120511, 120511], "mapped", [968]], [[120512, 120512], "mapped", [969]], [[120513, 120513], "mapped", [8711]], [[120514, 120514], "mapped", [945]], [[120515, 120515], "mapped", [946]], [[120516, 120516], "mapped", [947]], [[120517, 120517], "mapped", [948]], [[120518, 120518], "mapped", [949]], [[120519, 120519], "mapped", [950]], [[120520, 120520], "mapped", [951]], [[120521, 120521], "mapped", [952]], [[120522, 120522], "mapped", [953]], [[120523, 120523], "mapped", [954]], [[120524, 120524], "mapped", [955]], [[120525, 120525], "mapped", [956]], [[120526, 120526], "mapped", [957]], [[120527, 120527], "mapped", [958]], [[120528, 120528], "mapped", [959]], [[120529, 120529], "mapped", [960]], [[120530, 120530], "mapped", [961]], [[120531, 120532], "mapped", [963]], [[120533, 120533], "mapped", [964]], [[120534, 120534], "mapped", [965]], [[120535, 120535], "mapped", [966]], [[120536, 120536], "mapped", [967]], [[120537, 120537], "mapped", [968]], [[120538, 120538], "mapped", [969]], [[120539, 120539], "mapped", [8706]], [[120540, 120540], "mapped", [949]], [[120541, 120541], "mapped", [952]], [[120542, 120542], "mapped", [954]], [[120543, 120543], "mapped", [966]], [[120544, 120544], "mapped", [961]], [[120545, 120545], "mapped", [960]], [[120546, 120546], "mapped", [945]], [[120547, 120547], "mapped", [946]], [[120548, 120548], "mapped", [947]], [[120549, 120549], "mapped", [948]], [[120550, 120550], "mapped", [949]], [[120551, 120551], "mapped", [950]], [[120552, 120552], "mapped", [951]], [[120553, 120553], "mapped", [952]], [[120554, 120554], "mapped", [953]], [[120555, 120555], "mapped", [954]], [[120556, 120556], "mapped", [955]], [[120557, 120557], "mapped", [956]], [[120558, 120558], "mapped", [957]], [[120559, 120559], "mapped", [958]], [[120560, 120560], "mapped", [959]], [[120561, 120561], "mapped", [960]], [[120562, 120562], "mapped", [961]], [[120563, 120563], "mapped", [952]], [[120564, 120564], "mapped", [963]], [[120565, 120565], "mapped", [964]], [[120566, 120566], "mapped", [965]], [[120567, 120567], "mapped", [966]], [[120568, 120568], "mapped", [967]], [[120569, 120569], "mapped", [968]], [[120570, 120570], "mapped", [969]], [[120571, 120571], "mapped", [8711]], [[120572, 120572], "mapped", [945]], [[120573, 120573], "mapped", [946]], [[120574, 120574], "mapped", [947]], [[120575, 120575], "mapped", [948]], [[120576, 120576], "mapped", [949]], [[120577, 120577], "mapped", [950]], [[120578, 120578], "mapped", [951]], [[120579, 120579], "mapped", [952]], [[120580, 120580], "mapped", [953]], [[120581, 120581], "mapped", [954]], [[120582, 120582], "mapped", [955]], [[120583, 120583], "mapped", [956]], [[120584, 120584], "mapped", [957]], [[120585, 120585], "mapped", [958]], [[120586, 120586], "mapped", [959]], [[120587, 120587], "mapped", [960]], [[120588, 120588], "mapped", [961]], [[120589, 120590], "mapped", [963]], [[120591, 120591], "mapped", [964]], [[120592, 120592], "mapped", [965]], [[120593, 120593], "mapped", [966]], [[120594, 120594], "mapped", [967]], [[120595, 120595], "mapped", [968]], [[120596, 120596], "mapped", [969]], [[120597, 120597], "mapped", [8706]], [[120598, 120598], "mapped", [949]], [[120599, 120599], "mapped", [952]], [[120600, 120600], "mapped", [954]], [[120601, 120601], "mapped", [966]], [[120602, 120602], "mapped", [961]], [[120603, 120603], "mapped", [960]], [[120604, 120604], "mapped", [945]], [[120605, 120605], "mapped", [946]], [[120606, 120606], "mapped", [947]], [[120607, 120607], "mapped", [948]], [[120608, 120608], "mapped", [949]], [[120609, 120609], "mapped", [950]], [[120610, 120610], "mapped", [951]], [[120611, 120611], "mapped", [952]], [[120612, 120612], "mapped", [953]], [[120613, 120613], "mapped", [954]], [[120614, 120614], "mapped", [955]], [[120615, 120615], "mapped", [956]], [[120616, 120616], "mapped", [957]], [[120617, 120617], "mapped", [958]], [[120618, 120618], "mapped", [959]], [[120619, 120619], "mapped", [960]], [[120620, 120620], "mapped", [961]], [[120621, 120621], "mapped", [952]], [[120622, 120622], "mapped", [963]], [[120623, 120623], "mapped", [964]], [[120624, 120624], "mapped", [965]], [[120625, 120625], "mapped", [966]], [[120626, 120626], "mapped", [967]], [[120627, 120627], "mapped", [968]], [[120628, 120628], "mapped", [969]], [[120629, 120629], "mapped", [8711]], [[120630, 120630], "mapped", [945]], [[120631, 120631], "mapped", [946]], [[120632, 120632], "mapped", [947]], [[120633, 120633], "mapped", [948]], [[120634, 120634], "mapped", [949]], [[120635, 120635], "mapped", [950]], [[120636, 120636], "mapped", [951]], [[120637, 120637], "mapped", [952]], [[120638, 120638], "mapped", [953]], [[120639, 120639], "mapped", [954]], [[120640, 120640], "mapped", [955]], [[120641, 120641], "mapped", [956]], [[120642, 120642], "mapped", [957]], [[120643, 120643], "mapped", [958]], [[120644, 120644], "mapped", [959]], [[120645, 120645], "mapped", [960]], [[120646, 120646], "mapped", [961]], [[120647, 120648], "mapped", [963]], [[120649, 120649], "mapped", [964]], [[120650, 120650], "mapped", [965]], [[120651, 120651], "mapped", [966]], [[120652, 120652], "mapped", [967]], [[120653, 120653], "mapped", [968]], [[120654, 120654], "mapped", [969]], [[120655, 120655], "mapped", [8706]], [[120656, 120656], "mapped", [949]], [[120657, 120657], "mapped", [952]], [[120658, 120658], "mapped", [954]], [[120659, 120659], "mapped", [966]], [[120660, 120660], "mapped", [961]], [[120661, 120661], "mapped", [960]], [[120662, 120662], "mapped", [945]], [[120663, 120663], "mapped", [946]], [[120664, 120664], "mapped", [947]], [[120665, 120665], "mapped", [948]], [[120666, 120666], "mapped", [949]], [[120667, 120667], "mapped", [950]], [[120668, 120668], "mapped", [951]], [[120669, 120669], "mapped", [952]], [[120670, 120670], "mapped", [953]], [[120671, 120671], "mapped", [954]], [[120672, 120672], "mapped", [955]], [[120673, 120673], "mapped", [956]], [[120674, 120674], "mapped", [957]], [[120675, 120675], "mapped", [958]], [[120676, 120676], "mapped", [959]], [[120677, 120677], "mapped", [960]], [[120678, 120678], "mapped", [961]], [[120679, 120679], "mapped", [952]], [[120680, 120680], "mapped", [963]], [[120681, 120681], "mapped", [964]], [[120682, 120682], "mapped", [965]], [[120683, 120683], "mapped", [966]], [[120684, 120684], "mapped", [967]], [[120685, 120685], "mapped", [968]], [[120686, 120686], "mapped", [969]], [[120687, 120687], "mapped", [8711]], [[120688, 120688], "mapped", [945]], [[120689, 120689], "mapped", [946]], [[120690, 120690], "mapped", [947]], [[120691, 120691], "mapped", [948]], [[120692, 120692], "mapped", [949]], [[120693, 120693], "mapped", [950]], [[120694, 120694], "mapped", [951]], [[120695, 120695], "mapped", [952]], [[120696, 120696], "mapped", [953]], [[120697, 120697], "mapped", [954]], [[120698, 120698], "mapped", [955]], [[120699, 120699], "mapped", [956]], [[120700, 120700], "mapped", [957]], [[120701, 120701], "mapped", [958]], [[120702, 120702], "mapped", [959]], [[120703, 120703], "mapped", [960]], [[120704, 120704], "mapped", [961]], [[120705, 120706], "mapped", [963]], [[120707, 120707], "mapped", [964]], [[120708, 120708], "mapped", [965]], [[120709, 120709], "mapped", [966]], [[120710, 120710], "mapped", [967]], [[120711, 120711], "mapped", [968]], [[120712, 120712], "mapped", [969]], [[120713, 120713], "mapped", [8706]], [[120714, 120714], "mapped", [949]], [[120715, 120715], "mapped", [952]], [[120716, 120716], "mapped", [954]], [[120717, 120717], "mapped", [966]], [[120718, 120718], "mapped", [961]], [[120719, 120719], "mapped", [960]], [[120720, 120720], "mapped", [945]], [[120721, 120721], "mapped", [946]], [[120722, 120722], "mapped", [947]], [[120723, 120723], "mapped", [948]], [[120724, 120724], "mapped", [949]], [[120725, 120725], "mapped", [950]], [[120726, 120726], "mapped", [951]], [[120727, 120727], "mapped", [952]], [[120728, 120728], "mapped", [953]], [[120729, 120729], "mapped", [954]], [[120730, 120730], "mapped", [955]], [[120731, 120731], "mapped", [956]], [[120732, 120732], "mapped", [957]], [[120733, 120733], "mapped", [958]], [[120734, 120734], "mapped", [959]], [[120735, 120735], "mapped", [960]], [[120736, 120736], "mapped", [961]], [[120737, 120737], "mapped", [952]], [[120738, 120738], "mapped", [963]], [[120739, 120739], "mapped", [964]], [[120740, 120740], "mapped", [965]], [[120741, 120741], "mapped", [966]], [[120742, 120742], "mapped", [967]], [[120743, 120743], "mapped", [968]], [[120744, 120744], "mapped", [969]], [[120745, 120745], "mapped", [8711]], [[120746, 120746], "mapped", [945]], [[120747, 120747], "mapped", [946]], [[120748, 120748], "mapped", [947]], [[120749, 120749], "mapped", [948]], [[120750, 120750], "mapped", [949]], [[120751, 120751], "mapped", [950]], [[120752, 120752], "mapped", [951]], [[120753, 120753], "mapped", [952]], [[120754, 120754], "mapped", [953]], [[120755, 120755], "mapped", [954]], [[120756, 120756], "mapped", [955]], [[120757, 120757], "mapped", [956]], [[120758, 120758], "mapped", [957]], [[120759, 120759], "mapped", [958]], [[120760, 120760], "mapped", [959]], [[120761, 120761], "mapped", [960]], [[120762, 120762], "mapped", [961]], [[120763, 120764], "mapped", [963]], [[120765, 120765], "mapped", [964]], [[120766, 120766], "mapped", [965]], [[120767, 120767], "mapped", [966]], [[120768, 120768], "mapped", [967]], [[120769, 120769], "mapped", [968]], [[120770, 120770], "mapped", [969]], [[120771, 120771], "mapped", [8706]], [[120772, 120772], "mapped", [949]], [[120773, 120773], "mapped", [952]], [[120774, 120774], "mapped", [954]], [[120775, 120775], "mapped", [966]], [[120776, 120776], "mapped", [961]], [[120777, 120777], "mapped", [960]], [[120778, 120779], "mapped", [989]], [[120780, 120781], "disallowed"], [[120782, 120782], "mapped", [48]], [[120783, 120783], "mapped", [49]], [[120784, 120784], "mapped", [50]], [[120785, 120785], "mapped", [51]], [[120786, 120786], "mapped", [52]], [[120787, 120787], "mapped", [53]], [[120788, 120788], "mapped", [54]], [[120789, 120789], "mapped", [55]], [[120790, 120790], "mapped", [56]], [[120791, 120791], "mapped", [57]], [[120792, 120792], "mapped", [48]], [[120793, 120793], "mapped", [49]], [[120794, 120794], "mapped", [50]], [[120795, 120795], "mapped", [51]], [[120796, 120796], "mapped", [52]], [[120797, 120797], "mapped", [53]], [[120798, 120798], "mapped", [54]], [[120799, 120799], "mapped", [55]], [[120800, 120800], "mapped", [56]], [[120801, 120801], "mapped", [57]], [[120802, 120802], "mapped", [48]], [[120803, 120803], "mapped", [49]], [[120804, 120804], "mapped", [50]], [[120805, 120805], "mapped", [51]], [[120806, 120806], "mapped", [52]], [[120807, 120807], "mapped", [53]], [[120808, 120808], "mapped", [54]], [[120809, 120809], "mapped", [55]], [[120810, 120810], "mapped", [56]], [[120811, 120811], "mapped", [57]], [[120812, 120812], "mapped", [48]], [[120813, 120813], "mapped", [49]], [[120814, 120814], "mapped", [50]], [[120815, 120815], "mapped", [51]], [[120816, 120816], "mapped", [52]], [[120817, 120817], "mapped", [53]], [[120818, 120818], "mapped", [54]], [[120819, 120819], "mapped", [55]], [[120820, 120820], "mapped", [56]], [[120821, 120821], "mapped", [57]], [[120822, 120822], "mapped", [48]], [[120823, 120823], "mapped", [49]], [[120824, 120824], "mapped", [50]], [[120825, 120825], "mapped", [51]], [[120826, 120826], "mapped", [52]], [[120827, 120827], "mapped", [53]], [[120828, 120828], "mapped", [54]], [[120829, 120829], "mapped", [55]], [[120830, 120830], "mapped", [56]], [[120831, 120831], "mapped", [57]], [[120832, 121343], "valid", [], "NV8"], [[121344, 121398], "valid"], [[121399, 121402], "valid", [], "NV8"], [[121403, 121452], "valid"], [[121453, 121460], "valid", [], "NV8"], [[121461, 121461], "valid"], [[121462, 121475], "valid", [], "NV8"], [[121476, 121476], "valid"], [[121477, 121483], "valid", [], "NV8"], [[121484, 121498], "disallowed"], [[121499, 121503], "valid"], [[121504, 121504], "disallowed"], [[121505, 121519], "valid"], [[121520, 124927], "disallowed"], [[124928, 125124], "valid"], [[125125, 125126], "disallowed"], [[125127, 125135], "valid", [], "NV8"], [[125136, 125142], "valid"], [[125143, 126463], "disallowed"], [[126464, 126464], "mapped", [1575]], [[126465, 126465], "mapped", [1576]], [[126466, 126466], "mapped", [1580]], [[126467, 126467], "mapped", [1583]], [[126468, 126468], "disallowed"], [[126469, 126469], "mapped", [1608]], [[126470, 126470], "mapped", [1586]], [[126471, 126471], "mapped", [1581]], [[126472, 126472], "mapped", [1591]], [[126473, 126473], "mapped", [1610]], [[126474, 126474], "mapped", [1603]], [[126475, 126475], "mapped", [1604]], [[126476, 126476], "mapped", [1605]], [[126477, 126477], "mapped", [1606]], [[126478, 126478], "mapped", [1587]], [[126479, 126479], "mapped", [1593]], [[126480, 126480], "mapped", [1601]], [[126481, 126481], "mapped", [1589]], [[126482, 126482], "mapped", [1602]], [[126483, 126483], "mapped", [1585]], [[126484, 126484], "mapped", [1588]], [[126485, 126485], "mapped", [1578]], [[126486, 126486], "mapped", [1579]], [[126487, 126487], "mapped", [1582]], [[126488, 126488], "mapped", [1584]], [[126489, 126489], "mapped", [1590]], [[126490, 126490], "mapped", [1592]], [[126491, 126491], "mapped", [1594]], [[126492, 126492], "mapped", [1646]], [[126493, 126493], "mapped", [1722]], [[126494, 126494], "mapped", [1697]], [[126495, 126495], "mapped", [1647]], [[126496, 126496], "disallowed"], [[126497, 126497], "mapped", [1576]], [[126498, 126498], "mapped", [1580]], [[126499, 126499], "disallowed"], [[126500, 126500], "mapped", [1607]], [[126501, 126502], "disallowed"], [[126503, 126503], "mapped", [1581]], [[126504, 126504], "disallowed"], [[126505, 126505], "mapped", [1610]], [[126506, 126506], "mapped", [1603]], [[126507, 126507], "mapped", [1604]], [[126508, 126508], "mapped", [1605]], [[126509, 126509], "mapped", [1606]], [[126510, 126510], "mapped", [1587]], [[126511, 126511], "mapped", [1593]], [[126512, 126512], "mapped", [1601]], [[126513, 126513], "mapped", [1589]], [[126514, 126514], "mapped", [1602]], [[126515, 126515], "disallowed"], [[126516, 126516], "mapped", [1588]], [[126517, 126517], "mapped", [1578]], [[126518, 126518], "mapped", [1579]], [[126519, 126519], "mapped", [1582]], [[126520, 126520], "disallowed"], [[126521, 126521], "mapped", [1590]], [[126522, 126522], "disallowed"], [[126523, 126523], "mapped", [1594]], [[126524, 126529], "disallowed"], [[126530, 126530], "mapped", [1580]], [[126531, 126534], "disallowed"], [[126535, 126535], "mapped", [1581]], [[126536, 126536], "disallowed"], [[126537, 126537], "mapped", [1610]], [[126538, 126538], "disallowed"], [[126539, 126539], "mapped", [1604]], [[126540, 126540], "disallowed"], [[126541, 126541], "mapped", [1606]], [[126542, 126542], "mapped", [1587]], [[126543, 126543], "mapped", [1593]], [[126544, 126544], "disallowed"], [[126545, 126545], "mapped", [1589]], [[126546, 126546], "mapped", [1602]], [[126547, 126547], "disallowed"], [[126548, 126548], "mapped", [1588]], [[126549, 126550], "disallowed"], [[126551, 126551], "mapped", [1582]], [[126552, 126552], "disallowed"], [[126553, 126553], "mapped", [1590]], [[126554, 126554], "disallowed"], [[126555, 126555], "mapped", [1594]], [[126556, 126556], "disallowed"], [[126557, 126557], "mapped", [1722]], [[126558, 126558], "disallowed"], [[126559, 126559], "mapped", [1647]], [[126560, 126560], "disallowed"], [[126561, 126561], "mapped", [1576]], [[126562, 126562], "mapped", [1580]], [[126563, 126563], "disallowed"], [[126564, 126564], "mapped", [1607]], [[126565, 126566], "disallowed"], [[126567, 126567], "mapped", [1581]], [[126568, 126568], "mapped", [1591]], [[126569, 126569], "mapped", [1610]], [[126570, 126570], "mapped", [1603]], [[126571, 126571], "disallowed"], [[126572, 126572], "mapped", [1605]], [[126573, 126573], "mapped", [1606]], [[126574, 126574], "mapped", [1587]], [[126575, 126575], "mapped", [1593]], [[126576, 126576], "mapped", [1601]], [[126577, 126577], "mapped", [1589]], [[126578, 126578], "mapped", [1602]], [[126579, 126579], "disallowed"], [[126580, 126580], "mapped", [1588]], [[126581, 126581], "mapped", [1578]], [[126582, 126582], "mapped", [1579]], [[126583, 126583], "mapped", [1582]], [[126584, 126584], "disallowed"], [[126585, 126585], "mapped", [1590]], [[126586, 126586], "mapped", [1592]], [[126587, 126587], "mapped", [1594]], [[126588, 126588], "mapped", [1646]], [[126589, 126589], "disallowed"], [[126590, 126590], "mapped", [1697]], [[126591, 126591], "disallowed"], [[126592, 126592], "mapped", [1575]], [[126593, 126593], "mapped", [1576]], [[126594, 126594], "mapped", [1580]], [[126595, 126595], "mapped", [1583]], [[126596, 126596], "mapped", [1607]], [[126597, 126597], "mapped", [1608]], [[126598, 126598], "mapped", [1586]], [[126599, 126599], "mapped", [1581]], [[126600, 126600], "mapped", [1591]], [[126601, 126601], "mapped", [1610]], [[126602, 126602], "disallowed"], [[126603, 126603], "mapped", [1604]], [[126604, 126604], "mapped", [1605]], [[126605, 126605], "mapped", [1606]], [[126606, 126606], "mapped", [1587]], [[126607, 126607], "mapped", [1593]], [[126608, 126608], "mapped", [1601]], [[126609, 126609], "mapped", [1589]], [[126610, 126610], "mapped", [1602]], [[126611, 126611], "mapped", [1585]], [[126612, 126612], "mapped", [1588]], [[126613, 126613], "mapped", [1578]], [[126614, 126614], "mapped", [1579]], [[126615, 126615], "mapped", [1582]], [[126616, 126616], "mapped", [1584]], [[126617, 126617], "mapped", [1590]], [[126618, 126618], "mapped", [1592]], [[126619, 126619], "mapped", [1594]], [[126620, 126624], "disallowed"], [[126625, 126625], "mapped", [1576]], [[126626, 126626], "mapped", [1580]], [[126627, 126627], "mapped", [1583]], [[126628, 126628], "disallowed"], [[126629, 126629], "mapped", [1608]], [[126630, 126630], "mapped", [1586]], [[126631, 126631], "mapped", [1581]], [[126632, 126632], "mapped", [1591]], [[126633, 126633], "mapped", [1610]], [[126634, 126634], "disallowed"], [[126635, 126635], "mapped", [1604]], [[126636, 126636], "mapped", [1605]], [[126637, 126637], "mapped", [1606]], [[126638, 126638], "mapped", [1587]], [[126639, 126639], "mapped", [1593]], [[126640, 126640], "mapped", [1601]], [[126641, 126641], "mapped", [1589]], [[126642, 126642], "mapped", [1602]], [[126643, 126643], "mapped", [1585]], [[126644, 126644], "mapped", [1588]], [[126645, 126645], "mapped", [1578]], [[126646, 126646], "mapped", [1579]], [[126647, 126647], "mapped", [1582]], [[126648, 126648], "mapped", [1584]], [[126649, 126649], "mapped", [1590]], [[126650, 126650], "mapped", [1592]], [[126651, 126651], "mapped", [1594]], [[126652, 126703], "disallowed"], [[126704, 126705], "valid", [], "NV8"], [[126706, 126975], "disallowed"], [[126976, 127019], "valid", [], "NV8"], [[127020, 127023], "disallowed"], [[127024, 127123], "valid", [], "NV8"], [[127124, 127135], "disallowed"], [[127136, 127150], "valid", [], "NV8"], [[127151, 127152], "disallowed"], [[127153, 127166], "valid", [], "NV8"], [[127167, 127167], "valid", [], "NV8"], [[127168, 127168], "disallowed"], [[127169, 127183], "valid", [], "NV8"], [[127184, 127184], "disallowed"], [[127185, 127199], "valid", [], "NV8"], [[127200, 127221], "valid", [], "NV8"], [[127222, 127231], "disallowed"], [[127232, 127232], "disallowed"], [[127233, 127233], "disallowed_STD3_mapped", [48, 44]], [[127234, 127234], "disallowed_STD3_mapped", [49, 44]], [[127235, 127235], "disallowed_STD3_mapped", [50, 44]], [[127236, 127236], "disallowed_STD3_mapped", [51, 44]], [[127237, 127237], "disallowed_STD3_mapped", [52, 44]], [[127238, 127238], "disallowed_STD3_mapped", [53, 44]], [[127239, 127239], "disallowed_STD3_mapped", [54, 44]], [[127240, 127240], "disallowed_STD3_mapped", [55, 44]], [[127241, 127241], "disallowed_STD3_mapped", [56, 44]], [[127242, 127242], "disallowed_STD3_mapped", [57, 44]], [[127243, 127244], "valid", [], "NV8"], [[127245, 127247], "disallowed"], [[127248, 127248], "disallowed_STD3_mapped", [40, 97, 41]], [[127249, 127249], "disallowed_STD3_mapped", [40, 98, 41]], [[127250, 127250], "disallowed_STD3_mapped", [40, 99, 41]], [[127251, 127251], "disallowed_STD3_mapped", [40, 100, 41]], [[127252, 127252], "disallowed_STD3_mapped", [40, 101, 41]], [[127253, 127253], "disallowed_STD3_mapped", [40, 102, 41]], [[127254, 127254], "disallowed_STD3_mapped", [40, 103, 41]], [[127255, 127255], "disallowed_STD3_mapped", [40, 104, 41]], [[127256, 127256], "disallowed_STD3_mapped", [40, 105, 41]], [[127257, 127257], "disallowed_STD3_mapped", [40, 106, 41]], [[127258, 127258], "disallowed_STD3_mapped", [40, 107, 41]], [[127259, 127259], "disallowed_STD3_mapped", [40, 108, 41]], [[127260, 127260], "disallowed_STD3_mapped", [40, 109, 41]], [[127261, 127261], "disallowed_STD3_mapped", [40, 110, 41]], [[127262, 127262], "disallowed_STD3_mapped", [40, 111, 41]], [[127263, 127263], "disallowed_STD3_mapped", [40, 112, 41]], [[127264, 127264], "disallowed_STD3_mapped", [40, 113, 41]], [[127265, 127265], "disallowed_STD3_mapped", [40, 114, 41]], [[127266, 127266], "disallowed_STD3_mapped", [40, 115, 41]], [[127267, 127267], "disallowed_STD3_mapped", [40, 116, 41]], [[127268, 127268], "disallowed_STD3_mapped", [40, 117, 41]], [[127269, 127269], "disallowed_STD3_mapped", [40, 118, 41]], [[127270, 127270], "disallowed_STD3_mapped", [40, 119, 41]], [[127271, 127271], "disallowed_STD3_mapped", [40, 120, 41]], [[127272, 127272], "disallowed_STD3_mapped", [40, 121, 41]], [[127273, 127273], "disallowed_STD3_mapped", [40, 122, 41]], [[127274, 127274], "mapped", [12308, 115, 12309]], [[127275, 127275], "mapped", [99]], [[127276, 127276], "mapped", [114]], [[127277, 127277], "mapped", [99, 100]], [[127278, 127278], "mapped", [119, 122]], [[127279, 127279], "disallowed"], [[127280, 127280], "mapped", [97]], [[127281, 127281], "mapped", [98]], [[127282, 127282], "mapped", [99]], [[127283, 127283], "mapped", [100]], [[127284, 127284], "mapped", [101]], [[127285, 127285], "mapped", [102]], [[127286, 127286], "mapped", [103]], [[127287, 127287], "mapped", [104]], [[127288, 127288], "mapped", [105]], [[127289, 127289], "mapped", [106]], [[127290, 127290], "mapped", [107]], [[127291, 127291], "mapped", [108]], [[127292, 127292], "mapped", [109]], [[127293, 127293], "mapped", [110]], [[127294, 127294], "mapped", [111]], [[127295, 127295], "mapped", [112]], [[127296, 127296], "mapped", [113]], [[127297, 127297], "mapped", [114]], [[127298, 127298], "mapped", [115]], [[127299, 127299], "mapped", [116]], [[127300, 127300], "mapped", [117]], [[127301, 127301], "mapped", [118]], [[127302, 127302], "mapped", [119]], [[127303, 127303], "mapped", [120]], [[127304, 127304], "mapped", [121]], [[127305, 127305], "mapped", [122]], [[127306, 127306], "mapped", [104, 118]], [[127307, 127307], "mapped", [109, 118]], [[127308, 127308], "mapped", [115, 100]], [[127309, 127309], "mapped", [115, 115]], [[127310, 127310], "mapped", [112, 112, 118]], [[127311, 127311], "mapped", [119, 99]], [[127312, 127318], "valid", [], "NV8"], [[127319, 127319], "valid", [], "NV8"], [[127320, 127326], "valid", [], "NV8"], [[127327, 127327], "valid", [], "NV8"], [[127328, 127337], "valid", [], "NV8"], [[127338, 127338], "mapped", [109, 99]], [[127339, 127339], "mapped", [109, 100]], [[127340, 127343], "disallowed"], [[127344, 127352], "valid", [], "NV8"], [[127353, 127353], "valid", [], "NV8"], [[127354, 127354], "valid", [], "NV8"], [[127355, 127356], "valid", [], "NV8"], [[127357, 127358], "valid", [], "NV8"], [[127359, 127359], "valid", [], "NV8"], [[127360, 127369], "valid", [], "NV8"], [[127370, 127373], "valid", [], "NV8"], [[127374, 127375], "valid", [], "NV8"], [[127376, 127376], "mapped", [100, 106]], [[127377, 127386], "valid", [], "NV8"], [[127387, 127461], "disallowed"], [[127462, 127487], "valid", [], "NV8"], [[127488, 127488], "mapped", [12411, 12363]], [[127489, 127489], "mapped", [12467, 12467]], [[127490, 127490], "mapped", [12469]], [[127491, 127503], "disallowed"], [[127504, 127504], "mapped", [25163]], [[127505, 127505], "mapped", [23383]], [[127506, 127506], "mapped", [21452]], [[127507, 127507], "mapped", [12487]], [[127508, 127508], "mapped", [20108]], [[127509, 127509], "mapped", [22810]], [[127510, 127510], "mapped", [35299]], [[127511, 127511], "mapped", [22825]], [[127512, 127512], "mapped", [20132]], [[127513, 127513], "mapped", [26144]], [[127514, 127514], "mapped", [28961]], [[127515, 127515], "mapped", [26009]], [[127516, 127516], "mapped", [21069]], [[127517, 127517], "mapped", [24460]], [[127518, 127518], "mapped", [20877]], [[127519, 127519], "mapped", [26032]], [[127520, 127520], "mapped", [21021]], [[127521, 127521], "mapped", [32066]], [[127522, 127522], "mapped", [29983]], [[127523, 127523], "mapped", [36009]], [[127524, 127524], "mapped", [22768]], [[127525, 127525], "mapped", [21561]], [[127526, 127526], "mapped", [28436]], [[127527, 127527], "mapped", [25237]], [[127528, 127528], "mapped", [25429]], [[127529, 127529], "mapped", [19968]], [[127530, 127530], "mapped", [19977]], [[127531, 127531], "mapped", [36938]], [[127532, 127532], "mapped", [24038]], [[127533, 127533], "mapped", [20013]], [[127534, 127534], "mapped", [21491]], [[127535, 127535], "mapped", [25351]], [[127536, 127536], "mapped", [36208]], [[127537, 127537], "mapped", [25171]], [[127538, 127538], "mapped", [31105]], [[127539, 127539], "mapped", [31354]], [[127540, 127540], "mapped", [21512]], [[127541, 127541], "mapped", [28288]], [[127542, 127542], "mapped", [26377]], [[127543, 127543], "mapped", [26376]], [[127544, 127544], "mapped", [30003]], [[127545, 127545], "mapped", [21106]], [[127546, 127546], "mapped", [21942]], [[127547, 127551], "disallowed"], [[127552, 127552], "mapped", [12308, 26412, 12309]], [[127553, 127553], "mapped", [12308, 19977, 12309]], [[127554, 127554], "mapped", [12308, 20108, 12309]], [[127555, 127555], "mapped", [12308, 23433, 12309]], [[127556, 127556], "mapped", [12308, 28857, 12309]], [[127557, 127557], "mapped", [12308, 25171, 12309]], [[127558, 127558], "mapped", [12308, 30423, 12309]], [[127559, 127559], "mapped", [12308, 21213, 12309]], [[127560, 127560], "mapped", [12308, 25943, 12309]], [[127561, 127567], "disallowed"], [[127568, 127568], "mapped", [24471]], [[127569, 127569], "mapped", [21487]], [[127570, 127743], "disallowed"], [[127744, 127776], "valid", [], "NV8"], [[127777, 127788], "valid", [], "NV8"], [[127789, 127791], "valid", [], "NV8"], [[127792, 127797], "valid", [], "NV8"], [[127798, 127798], "valid", [], "NV8"], [[127799, 127868], "valid", [], "NV8"], [[127869, 127869], "valid", [], "NV8"], [[127870, 127871], "valid", [], "NV8"], [[127872, 127891], "valid", [], "NV8"], [[127892, 127903], "valid", [], "NV8"], [[127904, 127940], "valid", [], "NV8"], [[127941, 127941], "valid", [], "NV8"], [[127942, 127946], "valid", [], "NV8"], [[127947, 127950], "valid", [], "NV8"], [[127951, 127955], "valid", [], "NV8"], [[127956, 127967], "valid", [], "NV8"], [[127968, 127984], "valid", [], "NV8"], [[127985, 127991], "valid", [], "NV8"], [[127992, 127999], "valid", [], "NV8"], [[128e3, 128062], "valid", [], "NV8"], [[128063, 128063], "valid", [], "NV8"], [[128064, 128064], "valid", [], "NV8"], [[128065, 128065], "valid", [], "NV8"], [[128066, 128247], "valid", [], "NV8"], [[128248, 128248], "valid", [], "NV8"], [[128249, 128252], "valid", [], "NV8"], [[128253, 128254], "valid", [], "NV8"], [[128255, 128255], "valid", [], "NV8"], [[128256, 128317], "valid", [], "NV8"], [[128318, 128319], "valid", [], "NV8"], [[128320, 128323], "valid", [], "NV8"], [[128324, 128330], "valid", [], "NV8"], [[128331, 128335], "valid", [], "NV8"], [[128336, 128359], "valid", [], "NV8"], [[128360, 128377], "valid", [], "NV8"], [[128378, 128378], "disallowed"], [[128379, 128419], "valid", [], "NV8"], [[128420, 128420], "disallowed"], [[128421, 128506], "valid", [], "NV8"], [[128507, 128511], "valid", [], "NV8"], [[128512, 128512], "valid", [], "NV8"], [[128513, 128528], "valid", [], "NV8"], [[128529, 128529], "valid", [], "NV8"], [[128530, 128532], "valid", [], "NV8"], [[128533, 128533], "valid", [], "NV8"], [[128534, 128534], "valid", [], "NV8"], [[128535, 128535], "valid", [], "NV8"], [[128536, 128536], "valid", [], "NV8"], [[128537, 128537], "valid", [], "NV8"], [[128538, 128538], "valid", [], "NV8"], [[128539, 128539], "valid", [], "NV8"], [[128540, 128542], "valid", [], "NV8"], [[128543, 128543], "valid", [], "NV8"], [[128544, 128549], "valid", [], "NV8"], [[128550, 128551], "valid", [], "NV8"], [[128552, 128555], "valid", [], "NV8"], [[128556, 128556], "valid", [], "NV8"], [[128557, 128557], "valid", [], "NV8"], [[128558, 128559], "valid", [], "NV8"], [[128560, 128563], "valid", [], "NV8"], [[128564, 128564], "valid", [], "NV8"], [[128565, 128576], "valid", [], "NV8"], [[128577, 128578], "valid", [], "NV8"], [[128579, 128580], "valid", [], "NV8"], [[128581, 128591], "valid", [], "NV8"], [[128592, 128639], "valid", [], "NV8"], [[128640, 128709], "valid", [], "NV8"], [[128710, 128719], "valid", [], "NV8"], [[128720, 128720], "valid", [], "NV8"], [[128721, 128735], "disallowed"], [[128736, 128748], "valid", [], "NV8"], [[128749, 128751], "disallowed"], [[128752, 128755], "valid", [], "NV8"], [[128756, 128767], "disallowed"], [[128768, 128883], "valid", [], "NV8"], [[128884, 128895], "disallowed"], [[128896, 128980], "valid", [], "NV8"], [[128981, 129023], "disallowed"], [[129024, 129035], "valid", [], "NV8"], [[129036, 129039], "disallowed"], [[129040, 129095], "valid", [], "NV8"], [[129096, 129103], "disallowed"], [[129104, 129113], "valid", [], "NV8"], [[129114, 129119], "disallowed"], [[129120, 129159], "valid", [], "NV8"], [[129160, 129167], "disallowed"], [[129168, 129197], "valid", [], "NV8"], [[129198, 129295], "disallowed"], [[129296, 129304], "valid", [], "NV8"], [[129305, 129407], "disallowed"], [[129408, 129412], "valid", [], "NV8"], [[129413, 129471], "disallowed"], [[129472, 129472], "valid", [], "NV8"], [[129473, 131069], "disallowed"], [[131070, 131071], "disallowed"], [[131072, 173782], "valid"], [[173783, 173823], "disallowed"], [[173824, 177972], "valid"], [[177973, 177983], "disallowed"], [[177984, 178205], "valid"], [[178206, 178207], "disallowed"], [[178208, 183969], "valid"], [[183970, 194559], "disallowed"], [[194560, 194560], "mapped", [20029]], [[194561, 194561], "mapped", [20024]], [[194562, 194562], "mapped", [20033]], [[194563, 194563], "mapped", [131362]], [[194564, 194564], "mapped", [20320]], [[194565, 194565], "mapped", [20398]], [[194566, 194566], "mapped", [20411]], [[194567, 194567], "mapped", [20482]], [[194568, 194568], "mapped", [20602]], [[194569, 194569], "mapped", [20633]], [[194570, 194570], "mapped", [20711]], [[194571, 194571], "mapped", [20687]], [[194572, 194572], "mapped", [13470]], [[194573, 194573], "mapped", [132666]], [[194574, 194574], "mapped", [20813]], [[194575, 194575], "mapped", [20820]], [[194576, 194576], "mapped", [20836]], [[194577, 194577], "mapped", [20855]], [[194578, 194578], "mapped", [132380]], [[194579, 194579], "mapped", [13497]], [[194580, 194580], "mapped", [20839]], [[194581, 194581], "mapped", [20877]], [[194582, 194582], "mapped", [132427]], [[194583, 194583], "mapped", [20887]], [[194584, 194584], "mapped", [20900]], [[194585, 194585], "mapped", [20172]], [[194586, 194586], "mapped", [20908]], [[194587, 194587], "mapped", [20917]], [[194588, 194588], "mapped", [168415]], [[194589, 194589], "mapped", [20981]], [[194590, 194590], "mapped", [20995]], [[194591, 194591], "mapped", [13535]], [[194592, 194592], "mapped", [21051]], [[194593, 194593], "mapped", [21062]], [[194594, 194594], "mapped", [21106]], [[194595, 194595], "mapped", [21111]], [[194596, 194596], "mapped", [13589]], [[194597, 194597], "mapped", [21191]], [[194598, 194598], "mapped", [21193]], [[194599, 194599], "mapped", [21220]], [[194600, 194600], "mapped", [21242]], [[194601, 194601], "mapped", [21253]], [[194602, 194602], "mapped", [21254]], [[194603, 194603], "mapped", [21271]], [[194604, 194604], "mapped", [21321]], [[194605, 194605], "mapped", [21329]], [[194606, 194606], "mapped", [21338]], [[194607, 194607], "mapped", [21363]], [[194608, 194608], "mapped", [21373]], [[194609, 194611], "mapped", [21375]], [[194612, 194612], "mapped", [133676]], [[194613, 194613], "mapped", [28784]], [[194614, 194614], "mapped", [21450]], [[194615, 194615], "mapped", [21471]], [[194616, 194616], "mapped", [133987]], [[194617, 194617], "mapped", [21483]], [[194618, 194618], "mapped", [21489]], [[194619, 194619], "mapped", [21510]], [[194620, 194620], "mapped", [21662]], [[194621, 194621], "mapped", [21560]], [[194622, 194622], "mapped", [21576]], [[194623, 194623], "mapped", [21608]], [[194624, 194624], "mapped", [21666]], [[194625, 194625], "mapped", [21750]], [[194626, 194626], "mapped", [21776]], [[194627, 194627], "mapped", [21843]], [[194628, 194628], "mapped", [21859]], [[194629, 194630], "mapped", [21892]], [[194631, 194631], "mapped", [21913]], [[194632, 194632], "mapped", [21931]], [[194633, 194633], "mapped", [21939]], [[194634, 194634], "mapped", [21954]], [[194635, 194635], "mapped", [22294]], [[194636, 194636], "mapped", [22022]], [[194637, 194637], "mapped", [22295]], [[194638, 194638], "mapped", [22097]], [[194639, 194639], "mapped", [22132]], [[194640, 194640], "mapped", [20999]], [[194641, 194641], "mapped", [22766]], [[194642, 194642], "mapped", [22478]], [[194643, 194643], "mapped", [22516]], [[194644, 194644], "mapped", [22541]], [[194645, 194645], "mapped", [22411]], [[194646, 194646], "mapped", [22578]], [[194647, 194647], "mapped", [22577]], [[194648, 194648], "mapped", [22700]], [[194649, 194649], "mapped", [136420]], [[194650, 194650], "mapped", [22770]], [[194651, 194651], "mapped", [22775]], [[194652, 194652], "mapped", [22790]], [[194653, 194653], "mapped", [22810]], [[194654, 194654], "mapped", [22818]], [[194655, 194655], "mapped", [22882]], [[194656, 194656], "mapped", [136872]], [[194657, 194657], "mapped", [136938]], [[194658, 194658], "mapped", [23020]], [[194659, 194659], "mapped", [23067]], [[194660, 194660], "mapped", [23079]], [[194661, 194661], "mapped", [23e3]], [[194662, 194662], "mapped", [23142]], [[194663, 194663], "mapped", [14062]], [[194664, 194664], "disallowed"], [[194665, 194665], "mapped", [23304]], [[194666, 194667], "mapped", [23358]], [[194668, 194668], "mapped", [137672]], [[194669, 194669], "mapped", [23491]], [[194670, 194670], "mapped", [23512]], [[194671, 194671], "mapped", [23527]], [[194672, 194672], "mapped", [23539]], [[194673, 194673], "mapped", [138008]], [[194674, 194674], "mapped", [23551]], [[194675, 194675], "mapped", [23558]], [[194676, 194676], "disallowed"], [[194677, 194677], "mapped", [23586]], [[194678, 194678], "mapped", [14209]], [[194679, 194679], "mapped", [23648]], [[194680, 194680], "mapped", [23662]], [[194681, 194681], "mapped", [23744]], [[194682, 194682], "mapped", [23693]], [[194683, 194683], "mapped", [138724]], [[194684, 194684], "mapped", [23875]], [[194685, 194685], "mapped", [138726]], [[194686, 194686], "mapped", [23918]], [[194687, 194687], "mapped", [23915]], [[194688, 194688], "mapped", [23932]], [[194689, 194689], "mapped", [24033]], [[194690, 194690], "mapped", [24034]], [[194691, 194691], "mapped", [14383]], [[194692, 194692], "mapped", [24061]], [[194693, 194693], "mapped", [24104]], [[194694, 194694], "mapped", [24125]], [[194695, 194695], "mapped", [24169]], [[194696, 194696], "mapped", [14434]], [[194697, 194697], "mapped", [139651]], [[194698, 194698], "mapped", [14460]], [[194699, 194699], "mapped", [24240]], [[194700, 194700], "mapped", [24243]], [[194701, 194701], "mapped", [24246]], [[194702, 194702], "mapped", [24266]], [[194703, 194703], "mapped", [172946]], [[194704, 194704], "mapped", [24318]], [[194705, 194706], "mapped", [140081]], [[194707, 194707], "mapped", [33281]], [[194708, 194709], "mapped", [24354]], [[194710, 194710], "mapped", [14535]], [[194711, 194711], "mapped", [144056]], [[194712, 194712], "mapped", [156122]], [[194713, 194713], "mapped", [24418]], [[194714, 194714], "mapped", [24427]], [[194715, 194715], "mapped", [14563]], [[194716, 194716], "mapped", [24474]], [[194717, 194717], "mapped", [24525]], [[194718, 194718], "mapped", [24535]], [[194719, 194719], "mapped", [24569]], [[194720, 194720], "mapped", [24705]], [[194721, 194721], "mapped", [14650]], [[194722, 194722], "mapped", [14620]], [[194723, 194723], "mapped", [24724]], [[194724, 194724], "mapped", [141012]], [[194725, 194725], "mapped", [24775]], [[194726, 194726], "mapped", [24904]], [[194727, 194727], "mapped", [24908]], [[194728, 194728], "mapped", [24910]], [[194729, 194729], "mapped", [24908]], [[194730, 194730], "mapped", [24954]], [[194731, 194731], "mapped", [24974]], [[194732, 194732], "mapped", [25010]], [[194733, 194733], "mapped", [24996]], [[194734, 194734], "mapped", [25007]], [[194735, 194735], "mapped", [25054]], [[194736, 194736], "mapped", [25074]], [[194737, 194737], "mapped", [25078]], [[194738, 194738], "mapped", [25104]], [[194739, 194739], "mapped", [25115]], [[194740, 194740], "mapped", [25181]], [[194741, 194741], "mapped", [25265]], [[194742, 194742], "mapped", [25300]], [[194743, 194743], "mapped", [25424]], [[194744, 194744], "mapped", [142092]], [[194745, 194745], "mapped", [25405]], [[194746, 194746], "mapped", [25340]], [[194747, 194747], "mapped", [25448]], [[194748, 194748], "mapped", [25475]], [[194749, 194749], "mapped", [25572]], [[194750, 194750], "mapped", [142321]], [[194751, 194751], "mapped", [25634]], [[194752, 194752], "mapped", [25541]], [[194753, 194753], "mapped", [25513]], [[194754, 194754], "mapped", [14894]], [[194755, 194755], "mapped", [25705]], [[194756, 194756], "mapped", [25726]], [[194757, 194757], "mapped", [25757]], [[194758, 194758], "mapped", [25719]], [[194759, 194759], "mapped", [14956]], [[194760, 194760], "mapped", [25935]], [[194761, 194761], "mapped", [25964]], [[194762, 194762], "mapped", [143370]], [[194763, 194763], "mapped", [26083]], [[194764, 194764], "mapped", [26360]], [[194765, 194765], "mapped", [26185]], [[194766, 194766], "mapped", [15129]], [[194767, 194767], "mapped", [26257]], [[194768, 194768], "mapped", [15112]], [[194769, 194769], "mapped", [15076]], [[194770, 194770], "mapped", [20882]], [[194771, 194771], "mapped", [20885]], [[194772, 194772], "mapped", [26368]], [[194773, 194773], "mapped", [26268]], [[194774, 194774], "mapped", [32941]], [[194775, 194775], "mapped", [17369]], [[194776, 194776], "mapped", [26391]], [[194777, 194777], "mapped", [26395]], [[194778, 194778], "mapped", [26401]], [[194779, 194779], "mapped", [26462]], [[194780, 194780], "mapped", [26451]], [[194781, 194781], "mapped", [144323]], [[194782, 194782], "mapped", [15177]], [[194783, 194783], "mapped", [26618]], [[194784, 194784], "mapped", [26501]], [[194785, 194785], "mapped", [26706]], [[194786, 194786], "mapped", [26757]], [[194787, 194787], "mapped", [144493]], [[194788, 194788], "mapped", [26766]], [[194789, 194789], "mapped", [26655]], [[194790, 194790], "mapped", [26900]], [[194791, 194791], "mapped", [15261]], [[194792, 194792], "mapped", [26946]], [[194793, 194793], "mapped", [27043]], [[194794, 194794], "mapped", [27114]], [[194795, 194795], "mapped", [27304]], [[194796, 194796], "mapped", [145059]], [[194797, 194797], "mapped", [27355]], [[194798, 194798], "mapped", [15384]], [[194799, 194799], "mapped", [27425]], [[194800, 194800], "mapped", [145575]], [[194801, 194801], "mapped", [27476]], [[194802, 194802], "mapped", [15438]], [[194803, 194803], "mapped", [27506]], [[194804, 194804], "mapped", [27551]], [[194805, 194805], "mapped", [27578]], [[194806, 194806], "mapped", [27579]], [[194807, 194807], "mapped", [146061]], [[194808, 194808], "mapped", [138507]], [[194809, 194809], "mapped", [146170]], [[194810, 194810], "mapped", [27726]], [[194811, 194811], "mapped", [146620]], [[194812, 194812], "mapped", [27839]], [[194813, 194813], "mapped", [27853]], [[194814, 194814], "mapped", [27751]], [[194815, 194815], "mapped", [27926]], [[194816, 194816], "mapped", [27966]], [[194817, 194817], "mapped", [28023]], [[194818, 194818], "mapped", [27969]], [[194819, 194819], "mapped", [28009]], [[194820, 194820], "mapped", [28024]], [[194821, 194821], "mapped", [28037]], [[194822, 194822], "mapped", [146718]], [[194823, 194823], "mapped", [27956]], [[194824, 194824], "mapped", [28207]], [[194825, 194825], "mapped", [28270]], [[194826, 194826], "mapped", [15667]], [[194827, 194827], "mapped", [28363]], [[194828, 194828], "mapped", [28359]], [[194829, 194829], "mapped", [147153]], [[194830, 194830], "mapped", [28153]], [[194831, 194831], "mapped", [28526]], [[194832, 194832], "mapped", [147294]], [[194833, 194833], "mapped", [147342]], [[194834, 194834], "mapped", [28614]], [[194835, 194835], "mapped", [28729]], [[194836, 194836], "mapped", [28702]], [[194837, 194837], "mapped", [28699]], [[194838, 194838], "mapped", [15766]], [[194839, 194839], "mapped", [28746]], [[194840, 194840], "mapped", [28797]], [[194841, 194841], "mapped", [28791]], [[194842, 194842], "mapped", [28845]], [[194843, 194843], "mapped", [132389]], [[194844, 194844], "mapped", [28997]], [[194845, 194845], "mapped", [148067]], [[194846, 194846], "mapped", [29084]], [[194847, 194847], "disallowed"], [[194848, 194848], "mapped", [29224]], [[194849, 194849], "mapped", [29237]], [[194850, 194850], "mapped", [29264]], [[194851, 194851], "mapped", [149e3]], [[194852, 194852], "mapped", [29312]], [[194853, 194853], "mapped", [29333]], [[194854, 194854], "mapped", [149301]], [[194855, 194855], "mapped", [149524]], [[194856, 194856], "mapped", [29562]], [[194857, 194857], "mapped", [29579]], [[194858, 194858], "mapped", [16044]], [[194859, 194859], "mapped", [29605]], [[194860, 194861], "mapped", [16056]], [[194862, 194862], "mapped", [29767]], [[194863, 194863], "mapped", [29788]], [[194864, 194864], "mapped", [29809]], [[194865, 194865], "mapped", [29829]], [[194866, 194866], "mapped", [29898]], [[194867, 194867], "mapped", [16155]], [[194868, 194868], "mapped", [29988]], [[194869, 194869], "mapped", [150582]], [[194870, 194870], "mapped", [30014]], [[194871, 194871], "mapped", [150674]], [[194872, 194872], "mapped", [30064]], [[194873, 194873], "mapped", [139679]], [[194874, 194874], "mapped", [30224]], [[194875, 194875], "mapped", [151457]], [[194876, 194876], "mapped", [151480]], [[194877, 194877], "mapped", [151620]], [[194878, 194878], "mapped", [16380]], [[194879, 194879], "mapped", [16392]], [[194880, 194880], "mapped", [30452]], [[194881, 194881], "mapped", [151795]], [[194882, 194882], "mapped", [151794]], [[194883, 194883], "mapped", [151833]], [[194884, 194884], "mapped", [151859]], [[194885, 194885], "mapped", [30494]], [[194886, 194887], "mapped", [30495]], [[194888, 194888], "mapped", [30538]], [[194889, 194889], "mapped", [16441]], [[194890, 194890], "mapped", [30603]], [[194891, 194891], "mapped", [16454]], [[194892, 194892], "mapped", [16534]], [[194893, 194893], "mapped", [152605]], [[194894, 194894], "mapped", [30798]], [[194895, 194895], "mapped", [30860]], [[194896, 194896], "mapped", [30924]], [[194897, 194897], "mapped", [16611]], [[194898, 194898], "mapped", [153126]], [[194899, 194899], "mapped", [31062]], [[194900, 194900], "mapped", [153242]], [[194901, 194901], "mapped", [153285]], [[194902, 194902], "mapped", [31119]], [[194903, 194903], "mapped", [31211]], [[194904, 194904], "mapped", [16687]], [[194905, 194905], "mapped", [31296]], [[194906, 194906], "mapped", [31306]], [[194907, 194907], "mapped", [31311]], [[194908, 194908], "mapped", [153980]], [[194909, 194910], "mapped", [154279]], [[194911, 194911], "disallowed"], [[194912, 194912], "mapped", [16898]], [[194913, 194913], "mapped", [154539]], [[194914, 194914], "mapped", [31686]], [[194915, 194915], "mapped", [31689]], [[194916, 194916], "mapped", [16935]], [[194917, 194917], "mapped", [154752]], [[194918, 194918], "mapped", [31954]], [[194919, 194919], "mapped", [17056]], [[194920, 194920], "mapped", [31976]], [[194921, 194921], "mapped", [31971]], [[194922, 194922], "mapped", [32e3]], [[194923, 194923], "mapped", [155526]], [[194924, 194924], "mapped", [32099]], [[194925, 194925], "mapped", [17153]], [[194926, 194926], "mapped", [32199]], [[194927, 194927], "mapped", [32258]], [[194928, 194928], "mapped", [32325]], [[194929, 194929], "mapped", [17204]], [[194930, 194930], "mapped", [156200]], [[194931, 194931], "mapped", [156231]], [[194932, 194932], "mapped", [17241]], [[194933, 194933], "mapped", [156377]], [[194934, 194934], "mapped", [32634]], [[194935, 194935], "mapped", [156478]], [[194936, 194936], "mapped", [32661]], [[194937, 194937], "mapped", [32762]], [[194938, 194938], "mapped", [32773]], [[194939, 194939], "mapped", [156890]], [[194940, 194940], "mapped", [156963]], [[194941, 194941], "mapped", [32864]], [[194942, 194942], "mapped", [157096]], [[194943, 194943], "mapped", [32880]], [[194944, 194944], "mapped", [144223]], [[194945, 194945], "mapped", [17365]], [[194946, 194946], "mapped", [32946]], [[194947, 194947], "mapped", [33027]], [[194948, 194948], "mapped", [17419]], [[194949, 194949], "mapped", [33086]], [[194950, 194950], "mapped", [23221]], [[194951, 194951], "mapped", [157607]], [[194952, 194952], "mapped", [157621]], [[194953, 194953], "mapped", [144275]], [[194954, 194954], "mapped", [144284]], [[194955, 194955], "mapped", [33281]], [[194956, 194956], "mapped", [33284]], [[194957, 194957], "mapped", [36766]], [[194958, 194958], "mapped", [17515]], [[194959, 194959], "mapped", [33425]], [[194960, 194960], "mapped", [33419]], [[194961, 194961], "mapped", [33437]], [[194962, 194962], "mapped", [21171]], [[194963, 194963], "mapped", [33457]], [[194964, 194964], "mapped", [33459]], [[194965, 194965], "mapped", [33469]], [[194966, 194966], "mapped", [33510]], [[194967, 194967], "mapped", [158524]], [[194968, 194968], "mapped", [33509]], [[194969, 194969], "mapped", [33565]], [[194970, 194970], "mapped", [33635]], [[194971, 194971], "mapped", [33709]], [[194972, 194972], "mapped", [33571]], [[194973, 194973], "mapped", [33725]], [[194974, 194974], "mapped", [33767]], [[194975, 194975], "mapped", [33879]], [[194976, 194976], "mapped", [33619]], [[194977, 194977], "mapped", [33738]], [[194978, 194978], "mapped", [33740]], [[194979, 194979], "mapped", [33756]], [[194980, 194980], "mapped", [158774]], [[194981, 194981], "mapped", [159083]], [[194982, 194982], "mapped", [158933]], [[194983, 194983], "mapped", [17707]], [[194984, 194984], "mapped", [34033]], [[194985, 194985], "mapped", [34035]], [[194986, 194986], "mapped", [34070]], [[194987, 194987], "mapped", [160714]], [[194988, 194988], "mapped", [34148]], [[194989, 194989], "mapped", [159532]], [[194990, 194990], "mapped", [17757]], [[194991, 194991], "mapped", [17761]], [[194992, 194992], "mapped", [159665]], [[194993, 194993], "mapped", [159954]], [[194994, 194994], "mapped", [17771]], [[194995, 194995], "mapped", [34384]], [[194996, 194996], "mapped", [34396]], [[194997, 194997], "mapped", [34407]], [[194998, 194998], "mapped", [34409]], [[194999, 194999], "mapped", [34473]], [[195e3, 195e3], "mapped", [34440]], [[195001, 195001], "mapped", [34574]], [[195002, 195002], "mapped", [34530]], [[195003, 195003], "mapped", [34681]], [[195004, 195004], "mapped", [34600]], [[195005, 195005], "mapped", [34667]], [[195006, 195006], "mapped", [34694]], [[195007, 195007], "disallowed"], [[195008, 195008], "mapped", [34785]], [[195009, 195009], "mapped", [34817]], [[195010, 195010], "mapped", [17913]], [[195011, 195011], "mapped", [34912]], [[195012, 195012], "mapped", [34915]], [[195013, 195013], "mapped", [161383]], [[195014, 195014], "mapped", [35031]], [[195015, 195015], "mapped", [35038]], [[195016, 195016], "mapped", [17973]], [[195017, 195017], "mapped", [35066]], [[195018, 195018], "mapped", [13499]], [[195019, 195019], "mapped", [161966]], [[195020, 195020], "mapped", [162150]], [[195021, 195021], "mapped", [18110]], [[195022, 195022], "mapped", [18119]], [[195023, 195023], "mapped", [35488]], [[195024, 195024], "mapped", [35565]], [[195025, 195025], "mapped", [35722]], [[195026, 195026], "mapped", [35925]], [[195027, 195027], "mapped", [162984]], [[195028, 195028], "mapped", [36011]], [[195029, 195029], "mapped", [36033]], [[195030, 195030], "mapped", [36123]], [[195031, 195031], "mapped", [36215]], [[195032, 195032], "mapped", [163631]], [[195033, 195033], "mapped", [133124]], [[195034, 195034], "mapped", [36299]], [[195035, 195035], "mapped", [36284]], [[195036, 195036], "mapped", [36336]], [[195037, 195037], "mapped", [133342]], [[195038, 195038], "mapped", [36564]], [[195039, 195039], "mapped", [36664]], [[195040, 195040], "mapped", [165330]], [[195041, 195041], "mapped", [165357]], [[195042, 195042], "mapped", [37012]], [[195043, 195043], "mapped", [37105]], [[195044, 195044], "mapped", [37137]], [[195045, 195045], "mapped", [165678]], [[195046, 195046], "mapped", [37147]], [[195047, 195047], "mapped", [37432]], [[195048, 195048], "mapped", [37591]], [[195049, 195049], "mapped", [37592]], [[195050, 195050], "mapped", [37500]], [[195051, 195051], "mapped", [37881]], [[195052, 195052], "mapped", [37909]], [[195053, 195053], "mapped", [166906]], [[195054, 195054], "mapped", [38283]], [[195055, 195055], "mapped", [18837]], [[195056, 195056], "mapped", [38327]], [[195057, 195057], "mapped", [167287]], [[195058, 195058], "mapped", [18918]], [[195059, 195059], "mapped", [38595]], [[195060, 195060], "mapped", [23986]], [[195061, 195061], "mapped", [38691]], [[195062, 195062], "mapped", [168261]], [[195063, 195063], "mapped", [168474]], [[195064, 195064], "mapped", [19054]], [[195065, 195065], "mapped", [19062]], [[195066, 195066], "mapped", [38880]], [[195067, 195067], "mapped", [168970]], [[195068, 195068], "mapped", [19122]], [[195069, 195069], "mapped", [169110]], [[195070, 195071], "mapped", [38923]], [[195072, 195072], "mapped", [38953]], [[195073, 195073], "mapped", [169398]], [[195074, 195074], "mapped", [39138]], [[195075, 195075], "mapped", [19251]], [[195076, 195076], "mapped", [39209]], [[195077, 195077], "mapped", [39335]], [[195078, 195078], "mapped", [39362]], [[195079, 195079], "mapped", [39422]], [[195080, 195080], "mapped", [19406]], [[195081, 195081], "mapped", [170800]], [[195082, 195082], "mapped", [39698]], [[195083, 195083], "mapped", [4e4]], [[195084, 195084], "mapped", [40189]], [[195085, 195085], "mapped", [19662]], [[195086, 195086], "mapped", [19693]], [[195087, 195087], "mapped", [40295]], [[195088, 195088], "mapped", [172238]], [[195089, 195089], "mapped", [19704]], [[195090, 195090], "mapped", [172293]], [[195091, 195091], "mapped", [172558]], [[195092, 195092], "mapped", [172689]], [[195093, 195093], "mapped", [40635]], [[195094, 195094], "mapped", [19798]], [[195095, 195095], "mapped", [40697]], [[195096, 195096], "mapped", [40702]], [[195097, 195097], "mapped", [40709]], [[195098, 195098], "mapped", [40719]], [[195099, 195099], "mapped", [40726]], [[195100, 195100], "mapped", [40763]], [[195101, 195101], "mapped", [173568]], [[195102, 196605], "disallowed"], [[196606, 196607], "disallowed"], [[196608, 262141], "disallowed"], [[262142, 262143], "disallowed"], [[262144, 327677], "disallowed"], [[327678, 327679], "disallowed"], [[327680, 393213], "disallowed"], [[393214, 393215], "disallowed"], [[393216, 458749], "disallowed"], [[458750, 458751], "disallowed"], [[458752, 524285], "disallowed"], [[524286, 524287], "disallowed"], [[524288, 589821], "disallowed"], [[589822, 589823], "disallowed"], [[589824, 655357], "disallowed"], [[655358, 655359], "disallowed"], [[655360, 720893], "disallowed"], [[720894, 720895], "disallowed"], [[720896, 786429], "disallowed"], [[786430, 786431], "disallowed"], [[786432, 851965], "disallowed"], [[851966, 851967], "disallowed"], [[851968, 917501], "disallowed"], [[917502, 917503], "disallowed"], [[917504, 917504], "disallowed"], [[917505, 917505], "disallowed"], [[917506, 917535], "disallowed"], [[917536, 917631], "disallowed"], [[917632, 917759], "disallowed"], [[917760, 917999], "ignored"], [[918e3, 983037], "disallowed"], [[983038, 983039], "disallowed"], [[983040, 1048573], "disallowed"], [[1048574, 1048575], "disallowed"], [[1048576, 1114109], "disallowed"], [[1114110, 1114111], "disallowed"]];
  }
});

// node_modules/tr46/index.js
var require_tr46 = __commonJS({
  "node_modules/tr46/index.js"(exports2, module2) {
    "use strict";
    var punycode = require("punycode");
    var mappingTable = require_mappingTable();
    var PROCESSING_OPTIONS = {
      TRANSITIONAL: 0,
      NONTRANSITIONAL: 1
    };
    function normalize(str) {
      return str.split("\0").map(function(s) {
        return s.normalize("NFC");
      }).join("\0");
    }
    function findStatus(val) {
      var start = 0;
      var end = mappingTable.length - 1;
      while (start <= end) {
        var mid = Math.floor((start + end) / 2);
        var target = mappingTable[mid];
        if (target[0][0] <= val && target[0][1] >= val) {
          return target;
        } else if (target[0][0] > val) {
          end = mid - 1;
        } else {
          start = mid + 1;
        }
      }
      return null;
    }
    var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
    function countSymbols(string) {
      return string.replace(regexAstralSymbols, "_").length;
    }
    function mapChars(domain_name, useSTD3, processing_option) {
      var hasError = false;
      var processed = "";
      var len = countSymbols(domain_name);
      for (var i = 0; i < len; ++i) {
        var codePoint = domain_name.codePointAt(i);
        var status = findStatus(codePoint);
        switch (status[1]) {
          case "disallowed":
            hasError = true;
            processed += String.fromCodePoint(codePoint);
            break;
          case "ignored":
            break;
          case "mapped":
            processed += String.fromCodePoint.apply(String, status[2]);
            break;
          case "deviation":
            if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) {
              processed += String.fromCodePoint.apply(String, status[2]);
            } else {
              processed += String.fromCodePoint(codePoint);
            }
            break;
          case "valid":
            processed += String.fromCodePoint(codePoint);
            break;
          case "disallowed_STD3_mapped":
            if (useSTD3) {
              hasError = true;
              processed += String.fromCodePoint(codePoint);
            } else {
              processed += String.fromCodePoint.apply(String, status[2]);
            }
            break;
          case "disallowed_STD3_valid":
            if (useSTD3) {
              hasError = true;
            }
            processed += String.fromCodePoint(codePoint);
            break;
        }
      }
      return {
        string: processed,
        error: hasError
      };
    }
    var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/;
    function validateLabel(label, processing_option) {
      if (label.substr(0, 4) === "xn--") {
        label = punycode.toUnicode(label);
        processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL;
      }
      var error = false;
      if (normalize(label) !== label || label[3] === "-" && label[4] === "-" || label[0] === "-" || label[label.length - 1] === "-" || label.indexOf(".") !== -1 || label.search(combiningMarksRegex) === 0) {
        error = true;
      }
      var len = countSymbols(label);
      for (var i = 0; i < len; ++i) {
        var status = findStatus(label.codePointAt(i));
        if (processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid" || processing === PROCESSING_OPTIONS.NONTRANSITIONAL && status[1] !== "valid" && status[1] !== "deviation") {
          error = true;
          break;
        }
      }
      return {
        label,
        error
      };
    }
    function processing(domain_name, useSTD3, processing_option) {
      var result = mapChars(domain_name, useSTD3, processing_option);
      result.string = normalize(result.string);
      var labels = result.string.split(".");
      for (var i = 0; i < labels.length; ++i) {
        try {
          var validation = validateLabel(labels[i]);
          labels[i] = validation.label;
          result.error = result.error || validation.error;
        } catch (e) {
          result.error = true;
        }
      }
      return {
        string: labels.join("."),
        error: result.error
      };
    }
    module2.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) {
      var result = processing(domain_name, useSTD3, processing_option);
      var labels = result.string.split(".");
      labels = labels.map(function(l) {
        try {
          return punycode.toASCII(l);
        } catch (e) {
          result.error = true;
          return l;
        }
      });
      if (verifyDnsLength) {
        var total = labels.slice(0, labels.length - 1).join(".").length;
        if (total.length > 253 || total.length === 0) {
          result.error = true;
        }
        for (var i = 0; i < labels.length; ++i) {
          if (labels.length > 63 || labels.length === 0) {
            result.error = true;
            break;
          }
        }
      }
      if (result.error) return null;
      return labels.join(".");
    };
    module2.exports.toUnicode = function(domain_name, useSTD3) {
      var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL);
      return {
        domain: result.string,
        error: result.error
      };
    };
    module2.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS;
  }
});

// node_modules/whatwg-url/lib/url-state-machine.js
var require_url_state_machine = __commonJS({
  "node_modules/whatwg-url/lib/url-state-machine.js"(exports2, module2) {
    "use strict";
    var punycode = require("punycode");
    var tr46 = require_tr46();
    var specialSchemes = {
      ftp: 21,
      file: null,
      gopher: 70,
      http: 80,
      https: 443,
      ws: 80,
      wss: 443
    };
    var failure = Symbol("failure");
    function countSymbols(str) {
      return punycode.ucs2.decode(str).length;
    }
    function at(input, idx) {
      const c = input[idx];
      return isNaN(c) ? void 0 : String.fromCodePoint(c);
    }
    function isASCIIDigit(c) {
      return c >= 48 && c <= 57;
    }
    function isASCIIAlpha(c) {
      return c >= 65 && c <= 90 || c >= 97 && c <= 122;
    }
    function isASCIIAlphanumeric(c) {
      return isASCIIAlpha(c) || isASCIIDigit(c);
    }
    function isASCIIHex(c) {
      return isASCIIDigit(c) || c >= 65 && c <= 70 || c >= 97 && c <= 102;
    }
    function isSingleDot(buffer) {
      return buffer === "." || buffer.toLowerCase() === "%2e";
    }
    function isDoubleDot(buffer) {
      buffer = buffer.toLowerCase();
      return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e";
    }
    function isWindowsDriveLetterCodePoints(cp1, cp2) {
      return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124);
    }
    function isWindowsDriveLetterString(string) {
      return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|");
    }
    function isNormalizedWindowsDriveLetterString(string) {
      return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":";
    }
    function containsForbiddenHostCodePoint(string) {
      return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1;
    }
    function containsForbiddenHostCodePointExcludingPercent(string) {
      return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1;
    }
    function isSpecialScheme(scheme) {
      return specialSchemes[scheme] !== void 0;
    }
    function isSpecial(url) {
      return isSpecialScheme(url.scheme);
    }
    function defaultPort(scheme) {
      return specialSchemes[scheme];
    }
    function percentEncode(c) {
      let hex = c.toString(16).toUpperCase();
      if (hex.length === 1) {
        hex = "0" + hex;
      }
      return "%" + hex;
    }
    function utf8PercentEncode(c) {
      const buf = new Buffer(c);
      let str = "";
      for (let i = 0; i < buf.length; ++i) {
        str += percentEncode(buf[i]);
      }
      return str;
    }
    function utf8PercentDecode(str) {
      const input = new Buffer(str);
      const output = [];
      for (let i = 0; i < input.length; ++i) {
        if (input[i] !== 37) {
          output.push(input[i]);
        } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) {
          output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16));
          i += 2;
        } else {
          output.push(input[i]);
        }
      }
      return new Buffer(output).toString();
    }
    function isC0ControlPercentEncode(c) {
      return c <= 31 || c > 126;
    }
    var extraPathPercentEncodeSet = /* @__PURE__ */ new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]);
    function isPathPercentEncode(c) {
      return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c);
    }
    var extraUserinfoPercentEncodeSet = /* @__PURE__ */ new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]);
    function isUserinfoPercentEncode(c) {
      return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c);
    }
    function percentEncodeChar(c, encodeSetPredicate) {
      const cStr = String.fromCodePoint(c);
      if (encodeSetPredicate(c)) {
        return utf8PercentEncode(cStr);
      }
      return cStr;
    }
    function parseIPv4Number(input) {
      let R = 10;
      if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") {
        input = input.substring(2);
        R = 16;
      } else if (input.length >= 2 && input.charAt(0) === "0") {
        input = input.substring(1);
        R = 8;
      }
      if (input === "") {
        return 0;
      }
      const regex = R === 10 ? /[^0-9]/ : R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/;
      if (regex.test(input)) {
        return failure;
      }
      return parseInt(input, R);
    }
    function parseIPv4(input) {
      const parts = input.split(".");
      if (parts[parts.length - 1] === "") {
        if (parts.length > 1) {
          parts.pop();
        }
      }
      if (parts.length > 4) {
        return input;
      }
      const numbers = [];
      for (const part of parts) {
        if (part === "") {
          return input;
        }
        const n = parseIPv4Number(part);
        if (n === failure) {
          return input;
        }
        numbers.push(n);
      }
      for (let i = 0; i < numbers.length - 1; ++i) {
        if (numbers[i] > 255) {
          return failure;
        }
      }
      if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) {
        return failure;
      }
      let ipv4 = numbers.pop();
      let counter = 0;
      for (const n of numbers) {
        ipv4 += n * Math.pow(256, 3 - counter);
        ++counter;
      }
      return ipv4;
    }
    function serializeIPv4(address) {
      let output = "";
      let n = address;
      for (let i = 1; i <= 4; ++i) {
        output = String(n % 256) + output;
        if (i !== 4) {
          output = "." + output;
        }
        n = Math.floor(n / 256);
      }
      return output;
    }
    function parseIPv6(input) {
      const address = [0, 0, 0, 0, 0, 0, 0, 0];
      let pieceIndex = 0;
      let compress = null;
      let pointer = 0;
      input = punycode.ucs2.decode(input);
      if (input[pointer] === 58) {
        if (input[pointer + 1] !== 58) {
          return failure;
        }
        pointer += 2;
        ++pieceIndex;
        compress = pieceIndex;
      }
      while (pointer < input.length) {
        if (pieceIndex === 8) {
          return failure;
        }
        if (input[pointer] === 58) {
          if (compress !== null) {
            return failure;
          }
          ++pointer;
          ++pieceIndex;
          compress = pieceIndex;
          continue;
        }
        let value = 0;
        let length = 0;
        while (length < 4 && isASCIIHex(input[pointer])) {
          value = value * 16 + parseInt(at(input, pointer), 16);
          ++pointer;
          ++length;
        }
        if (input[pointer] === 46) {
          if (length === 0) {
            return failure;
          }
          pointer -= length;
          if (pieceIndex > 6) {
            return failure;
          }
          let numbersSeen = 0;
          while (input[pointer] !== void 0) {
            let ipv4Piece = null;
            if (numbersSeen > 0) {
              if (input[pointer] === 46 && numbersSeen < 4) {
                ++pointer;
              } else {
                return failure;
              }
            }
            if (!isASCIIDigit(input[pointer])) {
              return failure;
            }
            while (isASCIIDigit(input[pointer])) {
              const number = parseInt(at(input, pointer));
              if (ipv4Piece === null) {
                ipv4Piece = number;
              } else if (ipv4Piece === 0) {
                return failure;
              } else {
                ipv4Piece = ipv4Piece * 10 + number;
              }
              if (ipv4Piece > 255) {
                return failure;
              }
              ++pointer;
            }
            address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece;
            ++numbersSeen;
            if (numbersSeen === 2 || numbersSeen === 4) {
              ++pieceIndex;
            }
          }
          if (numbersSeen !== 4) {
            return failure;
          }
          break;
        } else if (input[pointer] === 58) {
          ++pointer;
          if (input[pointer] === void 0) {
            return failure;
          }
        } else if (input[pointer] !== void 0) {
          return failure;
        }
        address[pieceIndex] = value;
        ++pieceIndex;
      }
      if (compress !== null) {
        let swaps = pieceIndex - compress;
        pieceIndex = 7;
        while (pieceIndex !== 0 && swaps > 0) {
          const temp = address[compress + swaps - 1];
          address[compress + swaps - 1] = address[pieceIndex];
          address[pieceIndex] = temp;
          --pieceIndex;
          --swaps;
        }
      } else if (compress === null && pieceIndex !== 8) {
        return failure;
      }
      return address;
    }
    function serializeIPv6(address) {
      let output = "";
      const seqResult = findLongestZeroSequence(address);
      const compress = seqResult.idx;
      let ignore0 = false;
      for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) {
        if (ignore0 && address[pieceIndex] === 0) {
          continue;
        } else if (ignore0) {
          ignore0 = false;
        }
        if (compress === pieceIndex) {
          const separator = pieceIndex === 0 ? "::" : ":";
          output += separator;
          ignore0 = true;
          continue;
        }
        output += address[pieceIndex].toString(16);
        if (pieceIndex !== 7) {
          output += ":";
        }
      }
      return output;
    }
    function parseHost(input, isSpecialArg) {
      if (input[0] === "[") {
        if (input[input.length - 1] !== "]") {
          return failure;
        }
        return parseIPv6(input.substring(1, input.length - 1));
      }
      if (!isSpecialArg) {
        return parseOpaqueHost(input);
      }
      const domain = utf8PercentDecode(input);
      const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false);
      if (asciiDomain === null) {
        return failure;
      }
      if (containsForbiddenHostCodePoint(asciiDomain)) {
        return failure;
      }
      const ipv4Host = parseIPv4(asciiDomain);
      if (typeof ipv4Host === "number" || ipv4Host === failure) {
        return ipv4Host;
      }
      return asciiDomain;
    }
    function parseOpaqueHost(input) {
      if (containsForbiddenHostCodePointExcludingPercent(input)) {
        return failure;
      }
      let output = "";
      const decoded = punycode.ucs2.decode(input);
      for (let i = 0; i < decoded.length; ++i) {
        output += percentEncodeChar(decoded[i], isC0ControlPercentEncode);
      }
      return output;
    }
    function findLongestZeroSequence(arr) {
      let maxIdx = null;
      let maxLen = 1;
      let currStart = null;
      let currLen = 0;
      for (let i = 0; i < arr.length; ++i) {
        if (arr[i] !== 0) {
          if (currLen > maxLen) {
            maxIdx = currStart;
            maxLen = currLen;
          }
          currStart = null;
          currLen = 0;
        } else {
          if (currStart === null) {
            currStart = i;
          }
          ++currLen;
        }
      }
      if (currLen > maxLen) {
        maxIdx = currStart;
        maxLen = currLen;
      }
      return {
        idx: maxIdx,
        len: maxLen
      };
    }
    function serializeHost(host) {
      if (typeof host === "number") {
        return serializeIPv4(host);
      }
      if (host instanceof Array) {
        return "[" + serializeIPv6(host) + "]";
      }
      return host;
    }
    function trimControlChars(url) {
      return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, "");
    }
    function trimTabAndNewline(url) {
      return url.replace(/\u0009|\u000A|\u000D/g, "");
    }
    function shortenPath(url) {
      const path = url.path;
      if (path.length === 0) {
        return;
      }
      if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) {
        return;
      }
      path.pop();
    }
    function includesCredentials(url) {
      return url.username !== "" || url.password !== "";
    }
    function cannotHaveAUsernamePasswordPort(url) {
      return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file";
    }
    function isNormalizedWindowsDriveLetter(string) {
      return /^[A-Za-z]:$/.test(string);
    }
    function URLStateMachine(input, base, encodingOverride, url, stateOverride) {
      this.pointer = 0;
      this.input = input;
      this.base = base || null;
      this.encodingOverride = encodingOverride || "utf-8";
      this.stateOverride = stateOverride;
      this.url = url;
      this.failure = false;
      this.parseError = false;
      if (!this.url) {
        this.url = {
          scheme: "",
          username: "",
          password: "",
          host: null,
          port: null,
          path: [],
          query: null,
          fragment: null,
          cannotBeABaseURL: false
        };
        const res2 = trimControlChars(this.input);
        if (res2 !== this.input) {
          this.parseError = true;
        }
        this.input = res2;
      }
      const res = trimTabAndNewline(this.input);
      if (res !== this.input) {
        this.parseError = true;
      }
      this.input = res;
      this.state = stateOverride || "scheme start";
      this.buffer = "";
      this.atFlag = false;
      this.arrFlag = false;
      this.passwordTokenSeenFlag = false;
      this.input = punycode.ucs2.decode(this.input);
      for (; this.pointer <= this.input.length; ++this.pointer) {
        const c = this.input[this.pointer];
        const cStr = isNaN(c) ? void 0 : String.fromCodePoint(c);
        const ret = this["parse " + this.state](c, cStr);
        if (!ret) {
          break;
        } else if (ret === failure) {
          this.failure = true;
          break;
        }
      }
    }
    URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) {
      if (isASCIIAlpha(c)) {
        this.buffer += cStr.toLowerCase();
        this.state = "scheme";
      } else if (!this.stateOverride) {
        this.state = "no scheme";
        --this.pointer;
      } else {
        this.parseError = true;
        return failure;
      }
      return true;
    };
    URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) {
      if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) {
        this.buffer += cStr.toLowerCase();
      } else if (c === 58) {
        if (this.stateOverride) {
          if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) {
            return false;
          }
          if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) {
            return false;
          }
          if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") {
            return false;
          }
          if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) {
            return false;
          }
        }
        this.url.scheme = this.buffer;
        this.buffer = "";
        if (this.stateOverride) {
          return false;
        }
        if (this.url.scheme === "file") {
          if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) {
            this.parseError = true;
          }
          this.state = "file";
        } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) {
          this.state = "special relative or authority";
        } else if (isSpecial(this.url)) {
          this.state = "special authority slashes";
        } else if (this.input[this.pointer + 1] === 47) {
          this.state = "path or authority";
          ++this.pointer;
        } else {
          this.url.cannotBeABaseURL = true;
          this.url.path.push("");
          this.state = "cannot-be-a-base-URL path";
        }
      } else if (!this.stateOverride) {
        this.buffer = "";
        this.state = "no scheme";
        this.pointer = -1;
      } else {
        this.parseError = true;
        return failure;
      }
      return true;
    };
    URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) {
      if (this.base === null || this.base.cannotBeABaseURL && c !== 35) {
        return failure;
      } else if (this.base.cannotBeABaseURL && c === 35) {
        this.url.scheme = this.base.scheme;
        this.url.path = this.base.path.slice();
        this.url.query = this.base.query;
        this.url.fragment = "";
        this.url.cannotBeABaseURL = true;
        this.state = "fragment";
      } else if (this.base.scheme === "file") {
        this.state = "file";
        --this.pointer;
      } else {
        this.state = "relative";
        --this.pointer;
      }
      return true;
    };
    URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) {
      if (c === 47 && this.input[this.pointer + 1] === 47) {
        this.state = "special authority ignore slashes";
        ++this.pointer;
      } else {
        this.parseError = true;
        this.state = "relative";
        --this.pointer;
      }
      return true;
    };
    URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) {
      if (c === 47) {
        this.state = "authority";
      } else {
        this.state = "path";
        --this.pointer;
      }
      return true;
    };
    URLStateMachine.prototype["parse relative"] = function parseRelative(c) {
      this.url.scheme = this.base.scheme;
      if (isNaN(c)) {
        this.url.username = this.base.username;
        this.url.password = this.base.password;
        this.url.host = this.base.host;
        this.url.port = this.base.port;
        this.url.path = this.base.path.slice();
        this.url.query = this.base.query;
      } else if (c === 47) {
        this.state = "relative slash";
      } else if (c === 63) {
        this.url.username = this.base.username;
        this.url.password = this.base.password;
        this.url.host = this.base.host;
        this.url.port = this.base.port;
        this.url.path = this.base.path.slice();
        this.url.query = "";
        this.state = "query";
      } else if (c === 35) {
        this.url.username = this.base.username;
        this.url.password = this.base.password;
        this.url.host = this.base.host;
        this.url.port = this.base.port;
        this.url.path = this.base.path.slice();
        this.url.query = this.base.query;
        this.url.fragment = "";
        this.state = "fragment";
      } else if (isSpecial(this.url) && c === 92) {
        this.parseError = true;
        this.state = "relative slash";
      } else {
        this.url.username = this.base.username;
        this.url.password = this.base.password;
        this.url.host = this.base.host;
        this.url.port = this.base.port;
        this.url.path = this.base.path.slice(0, this.base.path.length - 1);
        this.state = "path";
        --this.pointer;
      }
      return true;
    };
    URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) {
      if (isSpecial(this.url) && (c === 47 || c === 92)) {
        if (c === 92) {
          this.parseError = true;
        }
        this.state = "special authority ignore slashes";
      } else if (c === 47) {
        this.state = "authority";
      } else {
        this.url.username = this.base.username;
        this.url.password = this.base.password;
        this.url.host = this.base.host;
        this.url.port = this.base.port;
        this.state = "path";
        --this.pointer;
      }
      return true;
    };
    URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) {
      if (c === 47 && this.input[this.pointer + 1] === 47) {
        this.state = "special authority ignore slashes";
        ++this.pointer;
      } else {
        this.parseError = true;
        this.state = "special authority ignore slashes";
        --this.pointer;
      }
      return true;
    };
    URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) {
      if (c !== 47 && c !== 92) {
        this.state = "authority";
        --this.pointer;
      } else {
        this.parseError = true;
      }
      return true;
    };
    URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) {
      if (c === 64) {
        this.parseError = true;
        if (this.atFlag) {
          this.buffer = "%40" + this.buffer;
        }
        this.atFlag = true;
        const len = countSymbols(this.buffer);
        for (let pointer = 0; pointer < len; ++pointer) {
          const codePoint = this.buffer.codePointAt(pointer);
          if (codePoint === 58 && !this.passwordTokenSeenFlag) {
            this.passwordTokenSeenFlag = true;
            continue;
          }
          const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode);
          if (this.passwordTokenSeenFlag) {
            this.url.password += encodedCodePoints;
          } else {
            this.url.username += encodedCodePoints;
          }
        }
        this.buffer = "";
      } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || isSpecial(this.url) && c === 92) {
        if (this.atFlag && this.buffer === "") {
          this.parseError = true;
          return failure;
        }
        this.pointer -= countSymbols(this.buffer) + 1;
        this.buffer = "";
        this.state = "host";
      } else {
        this.buffer += cStr;
      }
      return true;
    };
    URLStateMachine.prototype["parse hostname"] = URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) {
      if (this.stateOverride && this.url.scheme === "file") {
        --this.pointer;
        this.state = "file host";
      } else if (c === 58 && !this.arrFlag) {
        if (this.buffer === "") {
          this.parseError = true;
          return failure;
        }
        const host = parseHost(this.buffer, isSpecial(this.url));
        if (host === failure) {
          return failure;
        }
        this.url.host = host;
        this.buffer = "";
        this.state = "port";
        if (this.stateOverride === "hostname") {
          return false;
        }
      } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || isSpecial(this.url) && c === 92) {
        --this.pointer;
        if (isSpecial(this.url) && this.buffer === "") {
          this.parseError = true;
          return failure;
        } else if (this.stateOverride && this.buffer === "" && (includesCredentials(this.url) || this.url.port !== null)) {
          this.parseError = true;
          return false;
        }
        const host = parseHost(this.buffer, isSpecial(this.url));
        if (host === failure) {
          return failure;
        }
        this.url.host = host;
        this.buffer = "";
        this.state = "path start";
        if (this.stateOverride) {
          return false;
        }
      } else {
        if (c === 91) {
          this.arrFlag = true;
        } else if (c === 93) {
          this.arrFlag = false;
        }
        this.buffer += cStr;
      }
      return true;
    };
    URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) {
      if (isASCIIDigit(c)) {
        this.buffer += cStr;
      } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || isSpecial(this.url) && c === 92 || this.stateOverride) {
        if (this.buffer !== "") {
          const port = parseInt(this.buffer);
          if (port > Math.pow(2, 16) - 1) {
            this.parseError = true;
            return failure;
          }
          this.url.port = port === defaultPort(this.url.scheme) ? null : port;
          this.buffer = "";
        }
        if (this.stateOverride) {
          return false;
        }
        this.state = "path start";
        --this.pointer;
      } else {
        this.parseError = true;
        return failure;
      }
      return true;
    };
    var fileOtherwiseCodePoints = /* @__PURE__ */ new Set([47, 92, 63, 35]);
    URLStateMachine.prototype["parse file"] = function parseFile(c) {
      this.url.scheme = "file";
      if (c === 47 || c === 92) {
        if (c === 92) {
          this.parseError = true;
        }
        this.state = "file slash";
      } else if (this.base !== null && this.base.scheme === "file") {
        if (isNaN(c)) {
          this.url.host = this.base.host;
          this.url.path = this.base.path.slice();
          this.url.query = this.base.query;
        } else if (c === 63) {
          this.url.host = this.base.host;
          this.url.path = this.base.path.slice();
          this.url.query = "";
          this.state = "query";
        } else if (c === 35) {
          this.url.host = this.base.host;
          this.url.path = this.base.path.slice();
          this.url.query = this.base.query;
          this.url.fragment = "";
          this.state = "fragment";
        } else {
          if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points
          !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points
          !fileOtherwiseCodePoints.has(this.input[this.pointer + 2])) {
            this.url.host = this.base.host;
            this.url.path = this.base.path.slice();
            shortenPath(this.url);
          } else {
            this.parseError = true;
          }
          this.state = "path";
          --this.pointer;
        }
      } else {
        this.state = "path";
        --this.pointer;
      }
      return true;
    };
    URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) {
      if (c === 47 || c === 92) {
        if (c === 92) {
          this.parseError = true;
        }
        this.state = "file host";
      } else {
        if (this.base !== null && this.base.scheme === "file") {
          if (isNormalizedWindowsDriveLetterString(this.base.path[0])) {
            this.url.path.push(this.base.path[0]);
          } else {
            this.url.host = this.base.host;
          }
        }
        this.state = "path";
        --this.pointer;
      }
      return true;
    };
    URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) {
      if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) {
        --this.pointer;
        if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) {
          this.parseError = true;
          this.state = "path";
        } else if (this.buffer === "") {
          this.url.host = "";
          if (this.stateOverride) {
            return false;
          }
          this.state = "path start";
        } else {
          let host = parseHost(this.buffer, isSpecial(this.url));
          if (host === failure) {
            return failure;
          }
          if (host === "localhost") {
            host = "";
          }
          this.url.host = host;
          if (this.stateOverride) {
            return false;
          }
          this.buffer = "";
          this.state = "path start";
        }
      } else {
        this.buffer += cStr;
      }
      return true;
    };
    URLStateMachine.prototype["parse path start"] = function parsePathStart(c) {
      if (isSpecial(this.url)) {
        if (c === 92) {
          this.parseError = true;
        }
        this.state = "path";
        if (c !== 47 && c !== 92) {
          --this.pointer;
        }
      } else if (!this.stateOverride && c === 63) {
        this.url.query = "";
        this.state = "query";
      } else if (!this.stateOverride && c === 35) {
        this.url.fragment = "";
        this.state = "fragment";
      } else if (c !== void 0) {
        this.state = "path";
        if (c !== 47) {
          --this.pointer;
        }
      }
      return true;
    };
    URLStateMachine.prototype["parse path"] = function parsePath(c) {
      if (isNaN(c) || c === 47 || isSpecial(this.url) && c === 92 || !this.stateOverride && (c === 63 || c === 35)) {
        if (isSpecial(this.url) && c === 92) {
          this.parseError = true;
        }
        if (isDoubleDot(this.buffer)) {
          shortenPath(this.url);
          if (c !== 47 && !(isSpecial(this.url) && c === 92)) {
            this.url.path.push("");
          }
        } else if (isSingleDot(this.buffer) && c !== 47 && !(isSpecial(this.url) && c === 92)) {
          this.url.path.push("");
        } else if (!isSingleDot(this.buffer)) {
          if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) {
            if (this.url.host !== "" && this.url.host !== null) {
              this.parseError = true;
              this.url.host = "";
            }
            this.buffer = this.buffer[0] + ":";
          }
          this.url.path.push(this.buffer);
        }
        this.buffer = "";
        if (this.url.scheme === "file" && (c === void 0 || c === 63 || c === 35)) {
          while (this.url.path.length > 1 && this.url.path[0] === "") {
            this.parseError = true;
            this.url.path.shift();
          }
        }
        if (c === 63) {
          this.url.query = "";
          this.state = "query";
        }
        if (c === 35) {
          this.url.fragment = "";
          this.state = "fragment";
        }
      } else {
        if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
          this.parseError = true;
        }
        this.buffer += percentEncodeChar(c, isPathPercentEncode);
      }
      return true;
    };
    URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) {
      if (c === 63) {
        this.url.query = "";
        this.state = "query";
      } else if (c === 35) {
        this.url.fragment = "";
        this.state = "fragment";
      } else {
        if (!isNaN(c) && c !== 37) {
          this.parseError = true;
        }
        if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
          this.parseError = true;
        }
        if (!isNaN(c)) {
          this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode);
        }
      }
      return true;
    };
    URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) {
      if (isNaN(c) || !this.stateOverride && c === 35) {
        if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") {
          this.encodingOverride = "utf-8";
        }
        const buffer = new Buffer(this.buffer);
        for (let i = 0; i < buffer.length; ++i) {
          if (buffer[i] < 33 || buffer[i] > 126 || buffer[i] === 34 || buffer[i] === 35 || buffer[i] === 60 || buffer[i] === 62) {
            this.url.query += percentEncode(buffer[i]);
          } else {
            this.url.query += String.fromCodePoint(buffer[i]);
          }
        }
        this.buffer = "";
        if (c === 35) {
          this.url.fragment = "";
          this.state = "fragment";
        }
      } else {
        if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
          this.parseError = true;
        }
        this.buffer += cStr;
      }
      return true;
    };
    URLStateMachine.prototype["parse fragment"] = function parseFragment(c) {
      if (isNaN(c)) {
      } else if (c === 0) {
        this.parseError = true;
      } else {
        if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
          this.parseError = true;
        }
        this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode);
      }
      return true;
    };
    function serializeURL(url, excludeFragment) {
      let output = url.scheme + ":";
      if (url.host !== null) {
        output += "//";
        if (url.username !== "" || url.password !== "") {
          output += url.username;
          if (url.password !== "") {
            output += ":" + url.password;
          }
          output += "@";
        }
        output += serializeHost(url.host);
        if (url.port !== null) {
          output += ":" + url.port;
        }
      } else if (url.host === null && url.scheme === "file") {
        output += "//";
      }
      if (url.cannotBeABaseURL) {
        output += url.path[0];
      } else {
        for (const string of url.path) {
          output += "/" + string;
        }
      }
      if (url.query !== null) {
        output += "?" + url.query;
      }
      if (!excludeFragment && url.fragment !== null) {
        output += "#" + url.fragment;
      }
      return output;
    }
    function serializeOrigin(tuple) {
      let result = tuple.scheme + "://";
      result += serializeHost(tuple.host);
      if (tuple.port !== null) {
        result += ":" + tuple.port;
      }
      return result;
    }
    module2.exports.serializeURL = serializeURL;
    module2.exports.serializeURLOrigin = function(url) {
      switch (url.scheme) {
        case "blob":
          try {
            return module2.exports.serializeURLOrigin(module2.exports.parseURL(url.path[0]));
          } catch (e) {
            return "null";
          }
        case "ftp":
        case "gopher":
        case "http":
        case "https":
        case "ws":
        case "wss":
          return serializeOrigin({
            scheme: url.scheme,
            host: url.host,
            port: url.port
          });
        case "file":
          return "file://";
        default:
          return "null";
      }
    };
    module2.exports.basicURLParse = function(input, options) {
      if (options === void 0) {
        options = {};
      }
      const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride);
      if (usm.failure) {
        return "failure";
      }
      return usm.url;
    };
    module2.exports.setTheUsername = function(url, username) {
      url.username = "";
      const decoded = punycode.ucs2.decode(username);
      for (let i = 0; i < decoded.length; ++i) {
        url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode);
      }
    };
    module2.exports.setThePassword = function(url, password) {
      url.password = "";
      const decoded = punycode.ucs2.decode(password);
      for (let i = 0; i < decoded.length; ++i) {
        url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode);
      }
    };
    module2.exports.serializeHost = serializeHost;
    module2.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort;
    module2.exports.serializeInteger = function(integer) {
      return String(integer);
    };
    module2.exports.parseURL = function(input, options) {
      if (options === void 0) {
        options = {};
      }
      return module2.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride });
    };
  }
});

// node_modules/whatwg-url/lib/URL-impl.js
var require_URL_impl = __commonJS({
  "node_modules/whatwg-url/lib/URL-impl.js"(exports2) {
    "use strict";
    var usm = require_url_state_machine();
    exports2.implementation = class URLImpl {
      constructor(constructorArgs) {
        const url = constructorArgs[0];
        const base = constructorArgs[1];
        let parsedBase = null;
        if (base !== void 0) {
          parsedBase = usm.basicURLParse(base);
          if (parsedBase === "failure") {
            throw new TypeError("Invalid base URL");
          }
        }
        const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase });
        if (parsedURL === "failure") {
          throw new TypeError("Invalid URL");
        }
        this._url = parsedURL;
      }
      get href() {
        return usm.serializeURL(this._url);
      }
      set href(v) {
        const parsedURL = usm.basicURLParse(v);
        if (parsedURL === "failure") {
          throw new TypeError("Invalid URL");
        }
        this._url = parsedURL;
      }
      get origin() {
        return usm.serializeURLOrigin(this._url);
      }
      get protocol() {
        return this._url.scheme + ":";
      }
      set protocol(v) {
        usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" });
      }
      get username() {
        return this._url.username;
      }
      set username(v) {
        if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
          return;
        }
        usm.setTheUsername(this._url, v);
      }
      get password() {
        return this._url.password;
      }
      set password(v) {
        if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
          return;
        }
        usm.setThePassword(this._url, v);
      }
      get host() {
        const url = this._url;
        if (url.host === null) {
          return "";
        }
        if (url.port === null) {
          return usm.serializeHost(url.host);
        }
        return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port);
      }
      set host(v) {
        if (this._url.cannotBeABaseURL) {
          return;
        }
        usm.basicURLParse(v, { url: this._url, stateOverride: "host" });
      }
      get hostname() {
        if (this._url.host === null) {
          return "";
        }
        return usm.serializeHost(this._url.host);
      }
      set hostname(v) {
        if (this._url.cannotBeABaseURL) {
          return;
        }
        usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" });
      }
      get port() {
        if (this._url.port === null) {
          return "";
        }
        return usm.serializeInteger(this._url.port);
      }
      set port(v) {
        if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
          return;
        }
        if (v === "") {
          this._url.port = null;
        } else {
          usm.basicURLParse(v, { url: this._url, stateOverride: "port" });
        }
      }
      get pathname() {
        if (this._url.cannotBeABaseURL) {
          return this._url.path[0];
        }
        if (this._url.path.length === 0) {
          return "";
        }
        return "/" + this._url.path.join("/");
      }
      set pathname(v) {
        if (this._url.cannotBeABaseURL) {
          return;
        }
        this._url.path = [];
        usm.basicURLParse(v, { url: this._url, stateOverride: "path start" });
      }
      get search() {
        if (this._url.query === null || this._url.query === "") {
          return "";
        }
        return "?" + this._url.query;
      }
      set search(v) {
        const url = this._url;
        if (v === "") {
          url.query = null;
          return;
        }
        const input = v[0] === "?" ? v.substring(1) : v;
        url.query = "";
        usm.basicURLParse(input, { url, stateOverride: "query" });
      }
      get hash() {
        if (this._url.fragment === null || this._url.fragment === "") {
          return "";
        }
        return "#" + this._url.fragment;
      }
      set hash(v) {
        if (v === "") {
          this._url.fragment = null;
          return;
        }
        const input = v[0] === "#" ? v.substring(1) : v;
        this._url.fragment = "";
        usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" });
      }
      toJSON() {
        return this.href;
      }
    };
  }
});

// node_modules/whatwg-url/lib/URL.js
var require_URL = __commonJS({
  "node_modules/whatwg-url/lib/URL.js"(exports2, module2) {
    "use strict";
    var conversions = require_lib();
    var utils = require_utils();
    var Impl = require_URL_impl();
    var impl = utils.implSymbol;
    function URL(url) {
      if (!this || this[impl] || !(this instanceof URL)) {
        throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function.");
      }
      if (arguments.length < 1) {
        throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present.");
      }
      const args = [];
      for (let i = 0; i < arguments.length && i < 2; ++i) {
        args[i] = arguments[i];
      }
      args[0] = conversions["USVString"](args[0]);
      if (args[1] !== void 0) {
        args[1] = conversions["USVString"](args[1]);
      }
      module2.exports.setup(this, args);
    }
    URL.prototype.toJSON = function toJSON() {
      if (!this || !module2.exports.is(this)) {
        throw new TypeError("Illegal invocation");
      }
      const args = [];
      for (let i = 0; i < arguments.length && i < 0; ++i) {
        args[i] = arguments[i];
      }
      return this[impl].toJSON.apply(this[impl], args);
    };
    Object.defineProperty(URL.prototype, "href", {
      get() {
        return this[impl].href;
      },
      set(V) {
        V = conversions["USVString"](V);
        this[impl].href = V;
      },
      enumerable: true,
      configurable: true
    });
    URL.prototype.toString = function() {
      if (!this || !module2.exports.is(this)) {
        throw new TypeError("Illegal invocation");
      }
      return this.href;
    };
    Object.defineProperty(URL.prototype, "origin", {
      get() {
        return this[impl].origin;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL.prototype, "protocol", {
      get() {
        return this[impl].protocol;
      },
      set(V) {
        V = conversions["USVString"](V);
        this[impl].protocol = V;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL.prototype, "username", {
      get() {
        return this[impl].username;
      },
      set(V) {
        V = conversions["USVString"](V);
        this[impl].username = V;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL.prototype, "password", {
      get() {
        return this[impl].password;
      },
      set(V) {
        V = conversions["USVString"](V);
        this[impl].password = V;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL.prototype, "host", {
      get() {
        return this[impl].host;
      },
      set(V) {
        V = conversions["USVString"](V);
        this[impl].host = V;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL.prototype, "hostname", {
      get() {
        return this[impl].hostname;
      },
      set(V) {
        V = conversions["USVString"](V);
        this[impl].hostname = V;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL.prototype, "port", {
      get() {
        return this[impl].port;
      },
      set(V) {
        V = conversions["USVString"](V);
        this[impl].port = V;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL.prototype, "pathname", {
      get() {
        return this[impl].pathname;
      },
      set(V) {
        V = conversions["USVString"](V);
        this[impl].pathname = V;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL.prototype, "search", {
      get() {
        return this[impl].search;
      },
      set(V) {
        V = conversions["USVString"](V);
        this[impl].search = V;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL.prototype, "hash", {
      get() {
        return this[impl].hash;
      },
      set(V) {
        V = conversions["USVString"](V);
        this[impl].hash = V;
      },
      enumerable: true,
      configurable: true
    });
    module2.exports = {
      is(obj) {
        return !!obj && obj[impl] instanceof Impl.implementation;
      },
      create(constructorArgs, privateData) {
        let obj = Object.create(URL.prototype);
        this.setup(obj, constructorArgs, privateData);
        return obj;
      },
      setup(obj, constructorArgs, privateData) {
        if (!privateData) privateData = {};
        privateData.wrapper = obj;
        obj[impl] = new Impl.implementation(constructorArgs, privateData);
        obj[impl][utils.wrapperSymbol] = obj;
      },
      interface: URL,
      expose: {
        Window: { URL },
        Worker: { URL }
      }
    };
  }
});

// node_modules/whatwg-url/lib/public-api.js
var require_public_api = __commonJS({
  "node_modules/whatwg-url/lib/public-api.js"(exports2) {
    "use strict";
    exports2.URL = require_URL().interface;
    exports2.serializeURL = require_url_state_machine().serializeURL;
    exports2.serializeURLOrigin = require_url_state_machine().serializeURLOrigin;
    exports2.basicURLParse = require_url_state_machine().basicURLParse;
    exports2.setTheUsername = require_url_state_machine().setTheUsername;
    exports2.setThePassword = require_url_state_machine().setThePassword;
    exports2.serializeHost = require_url_state_machine().serializeHost;
    exports2.serializeInteger = require_url_state_machine().serializeInteger;
    exports2.parseURL = require_url_state_machine().parseURL;
  }
});

// node_modules/node-fetch/lib/index.js
var require_lib2 = __commonJS({
  "node_modules/node-fetch/lib/index.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    function _interopDefault(ex) {
      return ex && typeof ex === "object" && "default" in ex ? ex["default"] : ex;
    }
    var Stream = _interopDefault(require("stream"));
    var http = _interopDefault(require("http"));
    var Url = _interopDefault(require("url"));
    var whatwgUrl = _interopDefault(require_public_api());
    var https = _interopDefault(require("https"));
    var zlib = _interopDefault(require("zlib"));
    var Readable = Stream.Readable;
    var BUFFER = Symbol("buffer");
    var TYPE = Symbol("type");
    var Blob2 = class _Blob {
      constructor() {
        this[TYPE] = "";
        const blobParts = arguments[0];
        const options = arguments[1];
        const buffers = [];
        let size = 0;
        if (blobParts) {
          const a = blobParts;
          const length = Number(a.length);
          for (let i = 0; i < length; i++) {
            const element = a[i];
            let buffer;
            if (element instanceof Buffer) {
              buffer = element;
            } else if (ArrayBuffer.isView(element)) {
              buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
            } else if (element instanceof ArrayBuffer) {
              buffer = Buffer.from(element);
            } else if (element instanceof _Blob) {
              buffer = element[BUFFER];
            } else {
              buffer = Buffer.from(typeof element === "string" ? element : String(element));
            }
            size += buffer.length;
            buffers.push(buffer);
          }
        }
        this[BUFFER] = Buffer.concat(buffers);
        let type = options && options.type !== void 0 && String(options.type).toLowerCase();
        if (type && !/[^\u0020-\u007E]/.test(type)) {
          this[TYPE] = type;
        }
      }
      get size() {
        return this[BUFFER].length;
      }
      get type() {
        return this[TYPE];
      }
      text() {
        return Promise.resolve(this[BUFFER].toString());
      }
      arrayBuffer() {
        const buf = this[BUFFER];
        const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
        return Promise.resolve(ab);
      }
      stream() {
        const readable = new Readable();
        readable._read = function() {
        };
        readable.push(this[BUFFER]);
        readable.push(null);
        return readable;
      }
      toString() {
        return "[object Blob]";
      }
      slice() {
        const size = this.size;
        const start = arguments[0];
        const end = arguments[1];
        let relativeStart, relativeEnd;
        if (start === void 0) {
          relativeStart = 0;
        } else if (start < 0) {
          relativeStart = Math.max(size + start, 0);
        } else {
          relativeStart = Math.min(start, size);
        }
        if (end === void 0) {
          relativeEnd = size;
        } else if (end < 0) {
          relativeEnd = Math.max(size + end, 0);
        } else {
          relativeEnd = Math.min(end, size);
        }
        const span = Math.max(relativeEnd - relativeStart, 0);
        const buffer = this[BUFFER];
        const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
        const blob = new _Blob([], { type: arguments[2] });
        blob[BUFFER] = slicedBuffer;
        return blob;
      }
    };
    Object.defineProperties(Blob2.prototype, {
      size: { enumerable: true },
      type: { enumerable: true },
      slice: { enumerable: true }
    });
    Object.defineProperty(Blob2.prototype, Symbol.toStringTag, {
      value: "Blob",
      writable: false,
      enumerable: false,
      configurable: true
    });
    function FetchError(message, type, systemError) {
      Error.call(this, message);
      this.message = message;
      this.type = type;
      if (systemError) {
        this.code = this.errno = systemError.code;
      }
      Error.captureStackTrace(this, this.constructor);
    }
    FetchError.prototype = Object.create(Error.prototype);
    FetchError.prototype.constructor = FetchError;
    FetchError.prototype.name = "FetchError";
    var convert;
    try {
      convert = require("encoding").convert;
    } catch (e) {
    }
    var INTERNALS = Symbol("Body internals");
    var PassThrough = Stream.PassThrough;
    function Body(body) {
      var _this = this;
      var _ref = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, _ref$size = _ref.size;
      let size = _ref$size === void 0 ? 0 : _ref$size;
      var _ref$timeout = _ref.timeout;
      let timeout = _ref$timeout === void 0 ? 0 : _ref$timeout;
      if (body == null) {
        body = null;
      } else if (isURLSearchParams(body)) {
        body = Buffer.from(body.toString());
      } else if (isBlob(body)) ;
      else if (Buffer.isBuffer(body)) ;
      else if (Object.prototype.toString.call(body) === "[object ArrayBuffer]") {
        body = Buffer.from(body);
      } else if (ArrayBuffer.isView(body)) {
        body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
      } else if (body instanceof Stream) ;
      else {
        body = Buffer.from(String(body));
      }
      this[INTERNALS] = {
        body,
        disturbed: false,
        error: null
      };
      this.size = size;
      this.timeout = timeout;
      if (body instanceof Stream) {
        body.on("error", function(err) {
          const error = err.name === "AbortError" ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, "system", err);
          _this[INTERNALS].error = error;
        });
      }
    }
    Body.prototype = {
      get body() {
        return this[INTERNALS].body;
      },
      get bodyUsed() {
        return this[INTERNALS].disturbed;
      },
      /**
       * Decode response as ArrayBuffer
       *
       * @return  Promise
       */
      arrayBuffer() {
        return consumeBody.call(this).then(function(buf) {
          return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
        });
      },
      /**
       * Return raw response as Blob
       *
       * @return Promise
       */
      blob() {
        let ct = this.headers && this.headers.get("content-type") || "";
        return consumeBody.call(this).then(function(buf) {
          return Object.assign(
            // Prevent copying
            new Blob2([], {
              type: ct.toLowerCase()
            }),
            {
              [BUFFER]: buf
            }
          );
        });
      },
      /**
       * Decode response as json
       *
       * @return  Promise
       */
      json() {
        var _this2 = this;
        return consumeBody.call(this).then(function(buffer) {
          try {
            return JSON.parse(buffer.toString());
          } catch (err) {
            return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, "invalid-json"));
          }
        });
      },
      /**
       * Decode response as text
       *
       * @return  Promise
       */
      text() {
        return consumeBody.call(this).then(function(buffer) {
          return buffer.toString();
        });
      },
      /**
       * Decode response as buffer (non-spec api)
       *
       * @return  Promise
       */
      buffer() {
        return consumeBody.call(this);
      },
      /**
       * Decode response as text, while automatically detecting the encoding and
       * trying to decode to UTF-8 (non-spec api)
       *
       * @return  Promise
       */
      textConverted() {
        var _this3 = this;
        return consumeBody.call(this).then(function(buffer) {
          return convertBody(buffer, _this3.headers);
        });
      }
    };
    Object.defineProperties(Body.prototype, {
      body: { enumerable: true },
      bodyUsed: { enumerable: true },
      arrayBuffer: { enumerable: true },
      blob: { enumerable: true },
      json: { enumerable: true },
      text: { enumerable: true }
    });
    Body.mixIn = function(proto) {
      for (const name of Object.getOwnPropertyNames(Body.prototype)) {
        if (!(name in proto)) {
          const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
          Object.defineProperty(proto, name, desc);
        }
      }
    };
    function consumeBody() {
      var _this4 = this;
      if (this[INTERNALS].disturbed) {
        return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
      }
      this[INTERNALS].disturbed = true;
      if (this[INTERNALS].error) {
        return Body.Promise.reject(this[INTERNALS].error);
      }
      let body = this.body;
      if (body === null) {
        return Body.Promise.resolve(Buffer.alloc(0));
      }
      if (isBlob(body)) {
        body = body.stream();
      }
      if (Buffer.isBuffer(body)) {
        return Body.Promise.resolve(body);
      }
      if (!(body instanceof Stream)) {
        return Body.Promise.resolve(Buffer.alloc(0));
      }
      let accum = [];
      let accumBytes = 0;
      let abort = false;
      return new Body.Promise(function(resolve, reject) {
        let resTimeout;
        if (_this4.timeout) {
          resTimeout = setTimeout(function() {
            abort = true;
            reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, "body-timeout"));
          }, _this4.timeout);
        }
        body.on("error", function(err) {
          if (err.name === "AbortError") {
            abort = true;
            reject(err);
          } else {
            reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, "system", err));
          }
        });
        body.on("data", function(chunk) {
          if (abort || chunk === null) {
            return;
          }
          if (_this4.size && accumBytes + chunk.length > _this4.size) {
            abort = true;
            reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, "max-size"));
            return;
          }
          accumBytes += chunk.length;
          accum.push(chunk);
        });
        body.on("end", function() {
          if (abort) {
            return;
          }
          clearTimeout(resTimeout);
          try {
            resolve(Buffer.concat(accum, accumBytes));
          } catch (err) {
            reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, "system", err));
          }
        });
      });
    }
    function convertBody(buffer, headers) {
      if (typeof convert !== "function") {
        throw new Error("The package `encoding` must be installed to use the textConverted() function");
      }
      const ct = headers.get("content-type");
      let charset = "utf-8";
      let res, str;
      if (ct) {
        res = /charset=([^;]*)/i.exec(ct);
      }
      str = buffer.slice(0, 1024).toString();
      if (!res && str) {
        res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);
      }
      if (!res && str) {
        res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);
        if (!res) {
          res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str);
          if (res) {
            res.pop();
          }
        }
        if (res) {
          res = /charset=(.*)/i.exec(res.pop());
        }
      }
      if (!res && str) {
        res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);
      }
      if (res) {
        charset = res.pop();
        if (charset === "gb2312" || charset === "gbk") {
          charset = "gb18030";
        }
      }
      return convert(buffer, "UTF-8", charset).toString();
    }
    function isURLSearchParams(obj) {
      if (typeof obj !== "object" || typeof obj.append !== "function" || typeof obj.delete !== "function" || typeof obj.get !== "function" || typeof obj.getAll !== "function" || typeof obj.has !== "function" || typeof obj.set !== "function") {
        return false;
      }
      return obj.constructor.name === "URLSearchParams" || Object.prototype.toString.call(obj) === "[object URLSearchParams]" || typeof obj.sort === "function";
    }
    function isBlob(obj) {
      return typeof obj === "object" && typeof obj.arrayBuffer === "function" && typeof obj.type === "string" && typeof obj.stream === "function" && typeof obj.constructor === "function" && typeof obj.constructor.name === "string" && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);
    }
    function clone(instance) {
      let p1, p2;
      let body = instance.body;
      if (instance.bodyUsed) {
        throw new Error("cannot clone body after it is used");
      }
      if (body instanceof Stream && typeof body.getBoundary !== "function") {
        p1 = new PassThrough();
        p2 = new PassThrough();
        body.pipe(p1);
        body.pipe(p2);
        instance[INTERNALS].body = p1;
        body = p2;
      }
      return body;
    }
    function extractContentType(body) {
      if (body === null) {
        return null;
      } else if (typeof body === "string") {
        return "text/plain;charset=UTF-8";
      } else if (isURLSearchParams(body)) {
        return "application/x-www-form-urlencoded;charset=UTF-8";
      } else if (isBlob(body)) {
        return body.type || null;
      } else if (Buffer.isBuffer(body)) {
        return null;
      } else if (Object.prototype.toString.call(body) === "[object ArrayBuffer]") {
        return null;
      } else if (ArrayBuffer.isView(body)) {
        return null;
      } else if (typeof body.getBoundary === "function") {
        return `multipart/form-data;boundary=${body.getBoundary()}`;
      } else if (body instanceof Stream) {
        return null;
      } else {
        return "text/plain;charset=UTF-8";
      }
    }
    function getTotalBytes(instance) {
      const body = instance.body;
      if (body === null) {
        return 0;
      } else if (isBlob(body)) {
        return body.size;
      } else if (Buffer.isBuffer(body)) {
        return body.length;
      } else if (body && typeof body.getLengthSync === "function") {
        if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
        body.hasKnownLength && body.hasKnownLength()) {
          return body.getLengthSync();
        }
        return null;
      } else {
        return null;
      }
    }
    function writeToStream(dest, instance) {
      const body = instance.body;
      if (body === null) {
        dest.end();
      } else if (isBlob(body)) {
        body.stream().pipe(dest);
      } else if (Buffer.isBuffer(body)) {
        dest.write(body);
        dest.end();
      } else {
        body.pipe(dest);
      }
    }
    Body.Promise = global.Promise;
    var invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
    var invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
    function validateName(name) {
      name = `${name}`;
      if (invalidTokenRegex.test(name) || name === "") {
        throw new TypeError(`${name} is not a legal HTTP header name`);
      }
    }
    function validateValue(value) {
      value = `${value}`;
      if (invalidHeaderCharRegex.test(value)) {
        throw new TypeError(`${value} is not a legal HTTP header value`);
      }
    }
    function find(map, name) {
      name = name.toLowerCase();
      for (const key in map) {
        if (key.toLowerCase() === name) {
          return key;
        }
      }
      return void 0;
    }
    var MAP = Symbol("map");
    var Headers = class _Headers {
      /**
       * Headers class
       *
       * @param   Object  headers  Response headers
       * @return  Void
       */
      constructor() {
        let init = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : void 0;
        this[MAP] = /* @__PURE__ */ Object.create(null);
        if (init instanceof _Headers) {
          const rawHeaders = init.raw();
          const headerNames = Object.keys(rawHeaders);
          for (const headerName of headerNames) {
            for (const value of rawHeaders[headerName]) {
              this.append(headerName, value);
            }
          }
          return;
        }
        if (init == null) ;
        else if (typeof init === "object") {
          const method = init[Symbol.iterator];
          if (method != null) {
            if (typeof method !== "function") {
              throw new TypeError("Header pairs must be iterable");
            }
            const pairs = [];
            for (const pair of init) {
              if (typeof pair !== "object" || typeof pair[Symbol.iterator] !== "function") {
                throw new TypeError("Each header pair must be iterable");
              }
              pairs.push(Array.from(pair));
            }
            for (const pair of pairs) {
              if (pair.length !== 2) {
                throw new TypeError("Each header pair must be a name/value tuple");
              }
              this.append(pair[0], pair[1]);
            }
          } else {
            for (const key of Object.keys(init)) {
              const value = init[key];
              this.append(key, value);
            }
          }
        } else {
          throw new TypeError("Provided initializer must be an object");
        }
      }
      /**
       * Return combined header value given name
       *
       * @param   String  name  Header name
       * @return  Mixed
       */
      get(name) {
        name = `${name}`;
        validateName(name);
        const key = find(this[MAP], name);
        if (key === void 0) {
          return null;
        }
        return this[MAP][key].join(", ");
      }
      /**
       * Iterate over all headers
       *
       * @param   Function  callback  Executed for each item with parameters (value, name, thisArg)
       * @param   Boolean   thisArg   `this` context for callback function
       * @return  Void
       */
      forEach(callback) {
        let thisArg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : void 0;
        let pairs = getHeaders(this);
        let i = 0;
        while (i < pairs.length) {
          var _pairs$i = pairs[i];
          const name = _pairs$i[0], value = _pairs$i[1];
          callback.call(thisArg, value, name, this);
          pairs = getHeaders(this);
          i++;
        }
      }
      /**
       * Overwrite header values given name
       *
       * @param   String  name   Header name
       * @param   String  value  Header value
       * @return  Void
       */
      set(name, value) {
        name = `${name}`;
        value = `${value}`;
        validateName(name);
        validateValue(value);
        const key = find(this[MAP], name);
        this[MAP][key !== void 0 ? key : name] = [value];
      }
      /**
       * Append a value onto existing header
       *
       * @param   String  name   Header name
       * @param   String  value  Header value
       * @return  Void
       */
      append(name, value) {
        name = `${name}`;
        value = `${value}`;
        validateName(name);
        validateValue(value);
        const key = find(this[MAP], name);
        if (key !== void 0) {
          this[MAP][key].push(value);
        } else {
          this[MAP][name] = [value];
        }
      }
      /**
       * Check for header name existence
       *
       * @param   String   name  Header name
       * @return  Boolean
       */
      has(name) {
        name = `${name}`;
        validateName(name);
        return find(this[MAP], name) !== void 0;
      }
      /**
       * Delete all header values given name
       *
       * @param   String  name  Header name
       * @return  Void
       */
      delete(name) {
        name = `${name}`;
        validateName(name);
        const key = find(this[MAP], name);
        if (key !== void 0) {
          delete this[MAP][key];
        }
      }
      /**
       * Return raw headers (non-spec api)
       *
       * @return  Object
       */
      raw() {
        return this[MAP];
      }
      /**
       * Get an iterator on keys.
       *
       * @return  Iterator
       */
      keys() {
        return createHeadersIterator(this, "key");
      }
      /**
       * Get an iterator on values.
       *
       * @return  Iterator
       */
      values() {
        return createHeadersIterator(this, "value");
      }
      /**
       * Get an iterator on entries.
       *
       * This is the default iterator of the Headers object.
       *
       * @return  Iterator
       */
      [Symbol.iterator]() {
        return createHeadersIterator(this, "key+value");
      }
    };
    Headers.prototype.entries = Headers.prototype[Symbol.iterator];
    Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
      value: "Headers",
      writable: false,
      enumerable: false,
      configurable: true
    });
    Object.defineProperties(Headers.prototype, {
      get: { enumerable: true },
      forEach: { enumerable: true },
      set: { enumerable: true },
      append: { enumerable: true },
      has: { enumerable: true },
      delete: { enumerable: true },
      keys: { enumerable: true },
      values: { enumerable: true },
      entries: { enumerable: true }
    });
    function getHeaders(headers) {
      let kind = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "key+value";
      const keys = Object.keys(headers[MAP]).sort();
      return keys.map(kind === "key" ? function(k) {
        return k.toLowerCase();
      } : kind === "value" ? function(k) {
        return headers[MAP][k].join(", ");
      } : function(k) {
        return [k.toLowerCase(), headers[MAP][k].join(", ")];
      });
    }
    var INTERNAL = Symbol("internal");
    function createHeadersIterator(target, kind) {
      const iterator = Object.create(HeadersIteratorPrototype);
      iterator[INTERNAL] = {
        target,
        kind,
        index: 0
      };
      return iterator;
    }
    var HeadersIteratorPrototype = Object.setPrototypeOf({
      next() {
        if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
          throw new TypeError("Value of `this` is not a HeadersIterator");
        }
        var _INTERNAL = this[INTERNAL];
        const target = _INTERNAL.target, kind = _INTERNAL.kind, index = _INTERNAL.index;
        const values = getHeaders(target, kind);
        const len = values.length;
        if (index >= len) {
          return {
            value: void 0,
            done: true
          };
        }
        this[INTERNAL].index = index + 1;
        return {
          value: values[index],
          done: false
        };
      }
    }, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
    Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
      value: "HeadersIterator",
      writable: false,
      enumerable: false,
      configurable: true
    });
    function exportNodeCompatibleHeaders(headers) {
      const obj = Object.assign({ __proto__: null }, headers[MAP]);
      const hostHeaderKey = find(headers[MAP], "Host");
      if (hostHeaderKey !== void 0) {
        obj[hostHeaderKey] = obj[hostHeaderKey][0];
      }
      return obj;
    }
    function createHeadersLenient(obj) {
      const headers = new Headers();
      for (const name of Object.keys(obj)) {
        if (invalidTokenRegex.test(name)) {
          continue;
        }
        if (Array.isArray(obj[name])) {
          for (const val of obj[name]) {
            if (invalidHeaderCharRegex.test(val)) {
              continue;
            }
            if (headers[MAP][name] === void 0) {
              headers[MAP][name] = [val];
            } else {
              headers[MAP][name].push(val);
            }
          }
        } else if (!invalidHeaderCharRegex.test(obj[name])) {
          headers[MAP][name] = [obj[name]];
        }
      }
      return headers;
    }
    var INTERNALS$1 = Symbol("Response internals");
    var STATUS_CODES = http.STATUS_CODES;
    var Response = class _Response {
      constructor() {
        let body = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : null;
        let opts = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
        Body.call(this, body, opts);
        const status = opts.status || 200;
        const headers = new Headers(opts.headers);
        if (body != null && !headers.has("Content-Type")) {
          const contentType = extractContentType(body);
          if (contentType) {
            headers.append("Content-Type", contentType);
          }
        }
        this[INTERNALS$1] = {
          url: opts.url,
          status,
          statusText: opts.statusText || STATUS_CODES[status],
          headers,
          counter: opts.counter
        };
      }
      get url() {
        return this[INTERNALS$1].url || "";
      }
      get status() {
        return this[INTERNALS$1].status;
      }
      /**
       * Convenience property representing if the request ended normally
       */
      get ok() {
        return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
      }
      get redirected() {
        return this[INTERNALS$1].counter > 0;
      }
      get statusText() {
        return this[INTERNALS$1].statusText;
      }
      get headers() {
        return this[INTERNALS$1].headers;
      }
      /**
       * Clone this response
       *
       * @return  Response
       */
      clone() {
        return new _Response(clone(this), {
          url: this.url,
          status: this.status,
          statusText: this.statusText,
          headers: this.headers,
          ok: this.ok,
          redirected: this.redirected
        });
      }
    };
    Body.mixIn(Response.prototype);
    Object.defineProperties(Response.prototype, {
      url: { enumerable: true },
      status: { enumerable: true },
      ok: { enumerable: true },
      redirected: { enumerable: true },
      statusText: { enumerable: true },
      headers: { enumerable: true },
      clone: { enumerable: true }
    });
    Object.defineProperty(Response.prototype, Symbol.toStringTag, {
      value: "Response",
      writable: false,
      enumerable: false,
      configurable: true
    });
    var INTERNALS$2 = Symbol("Request internals");
    var URL = Url.URL || whatwgUrl.URL;
    var parse_url = Url.parse;
    var format_url = Url.format;
    function parseURL(urlStr) {
      if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {
        urlStr = new URL(urlStr).toString();
      }
      return parse_url(urlStr);
    }
    var streamDestructionSupported = "destroy" in Stream.Readable.prototype;
    function isRequest(input) {
      return typeof input === "object" && typeof input[INTERNALS$2] === "object";
    }
    function isAbortSignal(signal) {
      const proto = signal && typeof signal === "object" && Object.getPrototypeOf(signal);
      return !!(proto && proto.constructor.name === "AbortSignal");
    }
    var Request = class _Request {
      constructor(input) {
        let init = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
        let parsedURL;
        if (!isRequest(input)) {
          if (input && input.href) {
            parsedURL = parseURL(input.href);
          } else {
            parsedURL = parseURL(`${input}`);
          }
          input = {};
        } else {
          parsedURL = parseURL(input.url);
        }
        let method = init.method || input.method || "GET";
        method = method.toUpperCase();
        if ((init.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) {
          throw new TypeError("Request with GET/HEAD method cannot have body");
        }
        let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
        Body.call(this, inputBody, {
          timeout: init.timeout || input.timeout || 0,
          size: init.size || input.size || 0
        });
        const headers = new Headers(init.headers || input.headers || {});
        if (inputBody != null && !headers.has("Content-Type")) {
          const contentType = extractContentType(inputBody);
          if (contentType) {
            headers.append("Content-Type", contentType);
          }
        }
        let signal = isRequest(input) ? input.signal : null;
        if ("signal" in init) signal = init.signal;
        if (signal != null && !isAbortSignal(signal)) {
          throw new TypeError("Expected signal to be an instanceof AbortSignal");
        }
        this[INTERNALS$2] = {
          method,
          redirect: init.redirect || input.redirect || "follow",
          headers,
          parsedURL,
          signal
        };
        this.follow = init.follow !== void 0 ? init.follow : input.follow !== void 0 ? input.follow : 20;
        this.compress = init.compress !== void 0 ? init.compress : input.compress !== void 0 ? input.compress : true;
        this.counter = init.counter || input.counter || 0;
        this.agent = init.agent || input.agent;
      }
      get method() {
        return this[INTERNALS$2].method;
      }
      get url() {
        return format_url(this[INTERNALS$2].parsedURL);
      }
      get headers() {
        return this[INTERNALS$2].headers;
      }
      get redirect() {
        return this[INTERNALS$2].redirect;
      }
      get signal() {
        return this[INTERNALS$2].signal;
      }
      /**
       * Clone this request
       *
       * @return  Request
       */
      clone() {
        return new _Request(this);
      }
    };
    Body.mixIn(Request.prototype);
    Object.defineProperty(Request.prototype, Symbol.toStringTag, {
      value: "Request",
      writable: false,
      enumerable: false,
      configurable: true
    });
    Object.defineProperties(Request.prototype, {
      method: { enumerable: true },
      url: { enumerable: true },
      headers: { enumerable: true },
      redirect: { enumerable: true },
      clone: { enumerable: true },
      signal: { enumerable: true }
    });
    function getNodeRequestOptions(request) {
      const parsedURL = request[INTERNALS$2].parsedURL;
      const headers = new Headers(request[INTERNALS$2].headers);
      if (!headers.has("Accept")) {
        headers.set("Accept", "*/*");
      }
      if (!parsedURL.protocol || !parsedURL.hostname) {
        throw new TypeError("Only absolute URLs are supported");
      }
      if (!/^https?:$/.test(parsedURL.protocol)) {
        throw new TypeError("Only HTTP(S) protocols are supported");
      }
      if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
        throw new Error("Cancellation of streamed requests with AbortSignal is not supported in node < 8");
      }
      let contentLengthValue = null;
      if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
        contentLengthValue = "0";
      }
      if (request.body != null) {
        const totalBytes = getTotalBytes(request);
        if (typeof totalBytes === "number") {
          contentLengthValue = String(totalBytes);
        }
      }
      if (contentLengthValue) {
        headers.set("Content-Length", contentLengthValue);
      }
      if (!headers.has("User-Agent")) {
        headers.set("User-Agent", "node-fetch/1.0 (+https://github.com/bitinn/node-fetch)");
      }
      if (request.compress && !headers.has("Accept-Encoding")) {
        headers.set("Accept-Encoding", "gzip,deflate");
      }
      let agent = request.agent;
      if (typeof agent === "function") {
        agent = agent(parsedURL);
      }
      return Object.assign({}, parsedURL, {
        method: request.method,
        headers: exportNodeCompatibleHeaders(headers),
        agent
      });
    }
    function AbortError(message) {
      Error.call(this, message);
      this.type = "aborted";
      this.message = message;
      Error.captureStackTrace(this, this.constructor);
    }
    AbortError.prototype = Object.create(Error.prototype);
    AbortError.prototype.constructor = AbortError;
    AbortError.prototype.name = "AbortError";
    var URL$1 = Url.URL || whatwgUrl.URL;
    var PassThrough$1 = Stream.PassThrough;
    var isDomainOrSubdomain = function isDomainOrSubdomain2(destination, original) {
      const orig = new URL$1(original).hostname;
      const dest = new URL$1(destination).hostname;
      return orig === dest || orig[orig.length - dest.length - 1] === "." && orig.endsWith(dest);
    };
    var isSameProtocol = function isSameProtocol2(destination, original) {
      const orig = new URL$1(original).protocol;
      const dest = new URL$1(destination).protocol;
      return orig === dest;
    };
    function fetch2(url, opts) {
      if (!fetch2.Promise) {
        throw new Error("native promise missing, set fetch.Promise to your favorite alternative");
      }
      Body.Promise = fetch2.Promise;
      return new fetch2.Promise(function(resolve, reject) {
        const request = new Request(url, opts);
        const options = getNodeRequestOptions(request);
        const send = (options.protocol === "https:" ? https : http).request;
        const signal = request.signal;
        let response = null;
        const abort = function abort2() {
          let error = new AbortError("The user aborted a request.");
          reject(error);
          if (request.body && request.body instanceof Stream.Readable) {
            destroyStream(request.body, error);
          }
          if (!response || !response.body) return;
          response.body.emit("error", error);
        };
        if (signal && signal.aborted) {
          abort();
          return;
        }
        const abortAndFinalize = function abortAndFinalize2() {
          abort();
          finalize();
        };
        const req = send(options);
        let reqTimeout;
        if (signal) {
          signal.addEventListener("abort", abortAndFinalize);
        }
        function finalize() {
          req.abort();
          if (signal) signal.removeEventListener("abort", abortAndFinalize);
          clearTimeout(reqTimeout);
        }
        if (request.timeout) {
          req.once("socket", function(socket) {
            reqTimeout = setTimeout(function() {
              reject(new FetchError(`network timeout at: ${request.url}`, "request-timeout"));
              finalize();
            }, request.timeout);
          });
        }
        req.on("error", function(err) {
          reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, "system", err));
          if (response && response.body) {
            destroyStream(response.body, err);
          }
          finalize();
        });
        fixResponseChunkedTransferBadEnding(req, function(err) {
          if (signal && signal.aborted) {
            return;
          }
          if (response && response.body) {
            destroyStream(response.body, err);
          }
        });
        if (parseInt(process.version.substring(1)) < 14) {
          req.on("socket", function(s) {
            s.addListener("close", function(hadError) {
              const hasDataListener = s.listenerCount("data") > 0;
              if (response && hasDataListener && !hadError && !(signal && signal.aborted)) {
                const err = new Error("Premature close");
                err.code = "ERR_STREAM_PREMATURE_CLOSE";
                response.body.emit("error", err);
              }
            });
          });
        }
        req.on("response", function(res) {
          clearTimeout(reqTimeout);
          const headers = createHeadersLenient(res.headers);
          if (fetch2.isRedirect(res.statusCode)) {
            const location = headers.get("Location");
            let locationURL = null;
            try {
              locationURL = location === null ? null : new URL$1(location, request.url).toString();
            } catch (err) {
              if (request.redirect !== "manual") {
                reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect"));
                finalize();
                return;
              }
            }
            switch (request.redirect) {
              case "error":
                reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, "no-redirect"));
                finalize();
                return;
              case "manual":
                if (locationURL !== null) {
                  try {
                    headers.set("Location", locationURL);
                  } catch (err) {
                    reject(err);
                  }
                }
                break;
              case "follow":
                if (locationURL === null) {
                  break;
                }
                if (request.counter >= request.follow) {
                  reject(new FetchError(`maximum redirect reached at: ${request.url}`, "max-redirect"));
                  finalize();
                  return;
                }
                const requestOpts = {
                  headers: new Headers(request.headers),
                  follow: request.follow,
                  counter: request.counter + 1,
                  agent: request.agent,
                  compress: request.compress,
                  method: request.method,
                  body: request.body,
                  signal: request.signal,
                  timeout: request.timeout,
                  size: request.size
                };
                if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {
                  for (const name of ["authorization", "www-authenticate", "cookie", "cookie2"]) {
                    requestOpts.headers.delete(name);
                  }
                }
                if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
                  reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect"));
                  finalize();
                  return;
                }
                if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === "POST") {
                  requestOpts.method = "GET";
                  requestOpts.body = void 0;
                  requestOpts.headers.delete("content-length");
                }
                resolve(fetch2(new Request(locationURL, requestOpts)));
                finalize();
                return;
            }
          }
          res.once("end", function() {
            if (signal) signal.removeEventListener("abort", abortAndFinalize);
          });
          let body = res.pipe(new PassThrough$1());
          const response_options = {
            url: request.url,
            status: res.statusCode,
            statusText: res.statusMessage,
            headers,
            size: request.size,
            timeout: request.timeout,
            counter: request.counter
          };
          const codings = headers.get("Content-Encoding");
          if (!request.compress || request.method === "HEAD" || codings === null || res.statusCode === 204 || res.statusCode === 304) {
            response = new Response(body, response_options);
            resolve(response);
            return;
          }
          const zlibOptions = {
            flush: zlib.Z_SYNC_FLUSH,
            finishFlush: zlib.Z_SYNC_FLUSH
          };
          if (codings == "gzip" || codings == "x-gzip") {
            body = body.pipe(zlib.createGunzip(zlibOptions));
            response = new Response(body, response_options);
            resolve(response);
            return;
          }
          if (codings == "deflate" || codings == "x-deflate") {
            const raw = res.pipe(new PassThrough$1());
            raw.once("data", function(chunk) {
              if ((chunk[0] & 15) === 8) {
                body = body.pipe(zlib.createInflate());
              } else {
                body = body.pipe(zlib.createInflateRaw());
              }
              response = new Response(body, response_options);
              resolve(response);
            });
            raw.on("end", function() {
              if (!response) {
                response = new Response(body, response_options);
                resolve(response);
              }
            });
            return;
          }
          if (codings == "br" && typeof zlib.createBrotliDecompress === "function") {
            body = body.pipe(zlib.createBrotliDecompress());
            response = new Response(body, response_options);
            resolve(response);
            return;
          }
          response = new Response(body, response_options);
          resolve(response);
        });
        writeToStream(req, request);
      });
    }
    function fixResponseChunkedTransferBadEnding(request, errorCallback) {
      let socket;
      request.on("socket", function(s) {
        socket = s;
      });
      request.on("response", function(response) {
        const headers = response.headers;
        if (headers["transfer-encoding"] === "chunked" && !headers["content-length"]) {
          response.once("close", function(hadError) {
            const hasDataListener = socket && socket.listenerCount("data") > 0;
            if (hasDataListener && !hadError) {
              const err = new Error("Premature close");
              err.code = "ERR_STREAM_PREMATURE_CLOSE";
              errorCallback(err);
            }
          });
        }
      });
    }
    function destroyStream(stream, err) {
      if (stream.destroy) {
        stream.destroy(err);
      } else {
        stream.emit("error", err);
        stream.end();
      }
    }
    fetch2.isRedirect = function(code) {
      return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
    };
    fetch2.Promise = global.Promise;
    module2.exports = exports2 = fetch2;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.default = exports2;
    exports2.Headers = Headers;
    exports2.Request = Request;
    exports2.Response = Response;
    exports2.FetchError = FetchError;
  }
});

// node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js
var require_tf_core_node = __commonJS({
  "node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js"(exports2) {
    "use strict";
    function _mergeNamespaces(n, m) {
      m.forEach(function(e) {
        e && typeof e !== "string" && !Array.isArray(e) && Object.keys(e).forEach(function(k) {
          if (k !== "default" && !(k in n)) {
            var d = Object.getOwnPropertyDescriptor(e, k);
            Object.defineProperty(n, k, d.get ? d : {
              enumerable: true,
              get: function() {
                return e[k];
              }
            });
          }
        });
      });
      return n;
    }
    var extendStatics = function(d, b) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
        d2.__proto__ = b2;
      } || function(d2, b2) {
        for (var p in b2)
          if (Object.prototype.hasOwnProperty.call(b2, p))
            d2[p] = b2[p];
      };
      return extendStatics(d, b);
    };
    function __extends(d, b) {
      if (typeof b !== "function" && b !== null)
        throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
      extendStatics(d, b);
      function __() {
        this.constructor = d;
      }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }
    function __awaiter(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step2(generator.next(value));
          } catch (e) {
            reject(e);
          }
        }
        function rejected(value) {
          try {
            step2(generator["throw"](value));
          } catch (e) {
            reject(e);
          }
        }
        function step2(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step2((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    }
    function __generator(thisArg, body) {
      var _ = { label: 0, sent: function() {
        if (t[0] & 1)
          throw t[1];
        return t[1];
      }, trys: [], ops: [] }, f, y, t, g;
      return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
        return this;
      }), g;
      function verb(n) {
        return function(v) {
          return step2([n, v]);
        };
      }
      function step2(op2) {
        if (f)
          throw new TypeError("Generator is already executing.");
        while (_)
          try {
            if (f = 1, y && (t = op2[0] & 2 ? y["return"] : op2[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op2[1])).done)
              return t;
            if (y = 0, t)
              op2 = [op2[0] & 2, t.value];
            switch (op2[0]) {
              case 0:
              case 1:
                t = op2;
                break;
              case 4:
                _.label++;
                return { value: op2[1], done: false };
              case 5:
                _.label++;
                y = op2[1];
                op2 = [0];
                continue;
              case 7:
                op2 = _.ops.pop();
                _.trys.pop();
                continue;
              default:
                if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op2[0] === 6 || op2[0] === 2)) {
                  _ = 0;
                  continue;
                }
                if (op2[0] === 3 && (!t || op2[1] > t[0] && op2[1] < t[3])) {
                  _.label = op2[1];
                  break;
                }
                if (op2[0] === 6 && _.label < t[1]) {
                  _.label = t[1];
                  t = op2;
                  break;
                }
                if (t && _.label < t[2]) {
                  _.label = t[2];
                  _.ops.push(op2);
                  break;
                }
                if (t[2])
                  _.ops.pop();
                _.trys.pop();
                continue;
            }
            op2 = body.call(thisArg, _);
          } catch (e) {
            op2 = [6, e];
            y = 0;
          } finally {
            f = t = 0;
          }
        if (op2[0] & 5)
          throw op2[1];
        return { value: op2[0] ? op2[1] : void 0, done: true };
      }
    }
    function __values(o) {
      var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
      if (m)
        return m.call(o);
      if (o && typeof o.length === "number")
        return {
          next: function() {
            if (o && i >= o.length)
              o = void 0;
            return { value: o && o[i++], done: !o };
          }
        };
      throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    }
    function __read(o, n) {
      var m = typeof Symbol === "function" && o[Symbol.iterator];
      if (!m)
        return o;
      var i = m.call(o), r, ar = [], e;
      try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
          ar.push(r.value);
      } catch (error) {
        e = { error };
      } finally {
        try {
          if (r && !r.done && (m = i["return"]))
            m.call(i);
        } finally {
          if (e)
            throw e.error;
        }
      }
      return ar;
    }
    function __spreadArray(to, from, pack) {
      if (pack || arguments.length === 2)
        for (var i = 0, l = from.length, ar; i < l; i++) {
          if (ar || !(i in from)) {
            if (!ar)
              ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
          }
        }
      return to.concat(ar || Array.prototype.slice.call(from));
    }
    var EPSILON_FLOAT32 = 1e-7;
    var EPSILON_FLOAT16 = 1e-4;
    var DataStorage = (
      /** @class */
      function() {
        function DataStorage2(backend2, dataMover) {
          this.backend = backend2;
          this.dataMover = dataMover;
          this.data = /* @__PURE__ */ new WeakMap();
          this.dataIdsCount = 0;
        }
        DataStorage2.prototype.get = function(dataId) {
          if (!this.data.has(dataId)) {
            this.dataMover.moveData(this.backend, dataId);
          }
          return this.data.get(dataId);
        };
        DataStorage2.prototype.set = function(dataId, value) {
          this.dataIdsCount++;
          this.data.set(dataId, value);
        };
        DataStorage2.prototype.has = function(dataId) {
          return this.data.has(dataId);
        };
        DataStorage2.prototype.delete = function(dataId) {
          this.dataIdsCount--;
          return this.data.delete(dataId);
        };
        DataStorage2.prototype.numDataIds = function() {
          return this.dataIdsCount;
        };
        return DataStorage2;
      }()
    );
    var KernelBackend = (
      /** @class */
      function() {
        function KernelBackend2() {
        }
        KernelBackend2.prototype.refCount = function(dataId) {
          return notYetImplemented("refCount");
        };
        KernelBackend2.prototype.incRef = function(dataId) {
          return notYetImplemented("incRef");
        };
        KernelBackend2.prototype.timerAvailable = function() {
          return true;
        };
        KernelBackend2.prototype.time = function(f) {
          return notYetImplemented("time");
        };
        KernelBackend2.prototype.read = function(dataId) {
          return notYetImplemented("read");
        };
        KernelBackend2.prototype.readSync = function(dataId) {
          return notYetImplemented("readSync");
        };
        KernelBackend2.prototype.readToGPU = function(dataId, options) {
          return notYetImplemented("readToGPU");
        };
        KernelBackend2.prototype.numDataIds = function() {
          return notYetImplemented("numDataIds");
        };
        KernelBackend2.prototype.disposeData = function(dataId, force) {
          return notYetImplemented("disposeData");
        };
        KernelBackend2.prototype.write = function(values, shape, dtype) {
          return notYetImplemented("write");
        };
        KernelBackend2.prototype.move = function(dataId, values, shape, dtype, refCount) {
          return notYetImplemented("move");
        };
        KernelBackend2.prototype.createTensorFromGPUData = function(values, shape, dtype) {
          return notYetImplemented("createTensorFromGPUData");
        };
        KernelBackend2.prototype.memory = function() {
          return notYetImplemented("memory");
        };
        KernelBackend2.prototype.floatPrecision = function() {
          return notYetImplemented("floatPrecision");
        };
        KernelBackend2.prototype.epsilon = function() {
          return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;
        };
        KernelBackend2.prototype.dispose = function() {
          return notYetImplemented("dispose");
        };
        return KernelBackend2;
      }()
    );
    function notYetImplemented(kernelName) {
      throw new Error("'".concat(kernelName, "' not yet implemented or not found in the registry. ") + "This kernel may not be supported by the tfjs backend you have chosen");
    }
    function shuffle(array) {
      var counter = array.length;
      var index = 0;
      while (counter > 0) {
        index = Math.random() * counter | 0;
        counter--;
        swap(array, counter, index);
      }
    }
    function shuffleCombo(array, array2) {
      if (array.length !== array2.length) {
        throw new Error("Array sizes must match to be shuffled together " + "First array length was ".concat(array.length) + "Second array length was ".concat(array2.length));
      }
      var counter = array.length;
      var index = 0;
      while (counter > 0) {
        index = Math.random() * counter | 0;
        counter--;
        swap(array, counter, index);
        swap(array2, counter, index);
      }
    }
    function clamp(min2, x, max2) {
      return Math.max(min2, Math.min(x, max2));
    }
    function nearestLargerEven(val) {
      return val % 2 === 0 ? val : val + 1;
    }
    function swap(object, left, right) {
      var temp = object[left];
      object[left] = object[right];
      object[right] = temp;
    }
    function sum$1(arr) {
      var sum2 = 0;
      for (var i = 0; i < arr.length; i++) {
        sum2 += arr[i];
      }
      return sum2;
    }
    function randUniform(a, b) {
      var r = Math.random();
      return b * r + (1 - r) * a;
    }
    function distSquared(a, b) {
      var result = 0;
      for (var i = 0; i < a.length; i++) {
        var diff = Number(a[i]) - Number(b[i]);
        result += diff * diff;
      }
      return result;
    }
    function assert(expr, msg) {
      if (!expr) {
        throw new Error(typeof msg === "string" ? msg : msg());
      }
    }
    function assertShapesMatch(shapeA, shapeB, errorMessagePrefix) {
      if (errorMessagePrefix === void 0) {
        errorMessagePrefix = "";
      }
      assert(arraysEqual(shapeA, shapeB), function() {
        return errorMessagePrefix + " Shapes ".concat(shapeA, " and ").concat(shapeB, " must match");
      });
    }
    function assertNonNull(a) {
      assert(a != null, function() {
        return "The input to the tensor constructor must be a non-null value.";
      });
    }
    function sizeFromShape(shape) {
      if (shape.length === 0) {
        return 1;
      }
      var size = shape[0];
      for (var i = 1; i < shape.length; i++) {
        size *= shape[i];
      }
      return size;
    }
    function isScalarShape(shape) {
      return shape.length === 0;
    }
    function arraysEqualWithNull(n1, n2) {
      if (n1 === n2) {
        return true;
      }
      if (n1 == null || n2 == null) {
        return false;
      }
      if (n1.length !== n2.length) {
        return false;
      }
      for (var i = 0; i < n1.length; i++) {
        if (n1[i] !== null && n2[i] !== null && n1[i] !== n2[i]) {
          return false;
        }
      }
      return true;
    }
    function arraysEqual(n1, n2) {
      if (n1 === n2) {
        return true;
      }
      if (n1 == null || n2 == null) {
        return false;
      }
      if (n1.length !== n2.length) {
        return false;
      }
      for (var i = 0; i < n1.length; i++) {
        if (n1[i] !== n2[i]) {
          return false;
        }
      }
      return true;
    }
    function isInt(a) {
      return a % 1 === 0;
    }
    function tanh$1(x) {
      if (Math.tanh != null) {
        return Math.tanh(x);
      }
      if (x === Infinity) {
        return 1;
      } else if (x === -Infinity) {
        return -1;
      } else {
        var e2x = Math.exp(2 * x);
        return (e2x - 1) / (e2x + 1);
      }
    }
    function sizeToSquarishShape(size) {
      var width = Math.ceil(Math.sqrt(size));
      return [width, Math.ceil(size / width)];
    }
    function createShuffledIndices(n) {
      var shuffledIndices = new Uint32Array(n);
      for (var i = 0; i < n; ++i) {
        shuffledIndices[i] = i;
      }
      shuffle(shuffledIndices);
      return shuffledIndices;
    }
    function rightPad(a, size) {
      if (size <= a.length) {
        return a;
      }
      return a + " ".repeat(size - a.length);
    }
    function repeatedTry(checkFn, delayFn, maxCounter, scheduleFn) {
      if (delayFn === void 0) {
        delayFn = function(counter) {
          return 0;
        };
      }
      return new Promise(function(resolve, reject) {
        var tryCount = 0;
        var tryFn = function() {
          if (checkFn()) {
            resolve();
            return;
          }
          tryCount++;
          var nextBackoff = delayFn(tryCount);
          if (maxCounter != null && tryCount >= maxCounter) {
            reject();
            return;
          }
          if (scheduleFn != null) {
            scheduleFn(tryFn, nextBackoff);
          } else {
            setTimeout(tryFn, nextBackoff);
          }
        };
        tryFn();
      });
    }
    function inferFromImplicitShape(shape, size) {
      var shapeProd = 1;
      var implicitIdx = -1;
      for (var i = 0; i < shape.length; ++i) {
        if (shape[i] >= 0) {
          shapeProd *= shape[i];
        } else if (shape[i] === -1) {
          if (implicitIdx !== -1) {
            throw Error("Shapes can only have 1 implicit size. " + "Found -1 at dim ".concat(implicitIdx, " and dim ").concat(i));
          }
          implicitIdx = i;
        } else if (shape[i] < 0) {
          throw Error("Shapes can not be < 0. Found ".concat(shape[i], " at dim ").concat(i));
        }
      }
      if (implicitIdx === -1) {
        if (size > 0 && size !== shapeProd) {
          throw Error("Size(".concat(size, ") must match the product of shape ").concat(shape));
        }
        return shape;
      }
      if (shapeProd === 0) {
        throw Error("Cannot infer the missing size in [".concat(shape, "] when ") + "there are 0 elements");
      }
      if (size % shapeProd !== 0) {
        throw Error("The implicit shape can't be a fractional number. " + "Got ".concat(size, " / ").concat(shapeProd));
      }
      var newShape = shape.slice();
      newShape[implicitIdx] = size / shapeProd;
      return newShape;
    }
    function parseAxisParam(axis, shape) {
      var rank = shape.length;
      axis = axis == null ? shape.map(function(s, i) {
        return i;
      }) : [].concat(axis);
      assert(axis.every(function(ax) {
        return ax >= -rank && ax < rank;
      }), function() {
        return "All values in axis param must be in range [-".concat(rank, ", ").concat(rank, ") but ") + "got axis ".concat(axis);
      });
      assert(axis.every(function(ax) {
        return isInt(ax);
      }), function() {
        return "All values in axis param must be integers but " + "got axis ".concat(axis);
      });
      return axis.map(function(a) {
        return a < 0 ? rank + a : a;
      });
    }
    function squeezeShape(shape, axis) {
      var newShape = [];
      var keptDims = [];
      var isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;
      var axes = axis == null || isEmptyArray ? null : parseAxisParam(axis, shape).sort();
      var j = 0;
      for (var i = 0; i < shape.length; ++i) {
        if (axes != null) {
          if (axes[j] === i && shape[i] !== 1) {
            throw new Error("Can't squeeze axis ".concat(i, " since its dim '").concat(shape[i], "' is not 1"));
          }
          if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {
            newShape.push(shape[i]);
            keptDims.push(i);
          }
          if (axes[j] <= i) {
            j++;
          }
        }
        if (shape[i] !== 1) {
          newShape.push(shape[i]);
          keptDims.push(i);
        }
      }
      return { newShape, keptDims };
    }
    function getTypedArrayFromDType(dtype, size) {
      return getArrayFromDType(dtype, size);
    }
    function getArrayFromDType(dtype, size) {
      var values = null;
      if (dtype == null || dtype === "float32") {
        values = new Float32Array(size);
      } else if (dtype === "int32") {
        values = new Int32Array(size);
      } else if (dtype === "bool") {
        values = new Uint8Array(size);
      } else if (dtype === "string") {
        values = new Array(size);
      } else {
        throw new Error("Unknown data type ".concat(dtype));
      }
      return values;
    }
    function checkConversionForErrors(vals, dtype) {
      for (var i = 0; i < vals.length; i++) {
        var num = vals[i];
        if (isNaN(num) || !isFinite(num)) {
          throw Error("A tensor of type ".concat(dtype, " being uploaded contains ").concat(num, "."));
        }
      }
    }
    function isValidDtype(dtype) {
      return dtype === "bool" || dtype === "complex64" || dtype === "float32" || dtype === "int32" || dtype === "string";
    }
    function hasEncodingLoss(oldType, newType) {
      if (newType === "complex64") {
        return false;
      }
      if (newType === "float32" && oldType !== "complex64") {
        return false;
      }
      if (newType === "int32" && oldType !== "float32" && oldType !== "complex64") {
        return false;
      }
      if (newType === "bool" && oldType === "bool") {
        return false;
      }
      return true;
    }
    function bytesPerElement(dtype) {
      if (dtype === "float32" || dtype === "int32") {
        return 4;
      } else if (dtype === "complex64") {
        return 8;
      } else if (dtype === "bool") {
        return 1;
      } else {
        throw new Error("Unknown dtype ".concat(dtype));
      }
    }
    function bytesFromStringArray(arr) {
      if (arr == null) {
        return 0;
      }
      var bytes = 0;
      arr.forEach(function(x) {
        return bytes += x.length;
      });
      return bytes;
    }
    function isString(value) {
      return typeof value === "string" || value instanceof String;
    }
    function isBoolean(value) {
      return typeof value === "boolean";
    }
    function isNumber(value) {
      return typeof value === "number";
    }
    function inferDtype(values) {
      if (Array.isArray(values)) {
        return inferDtype(values[0]);
      }
      if (values instanceof Float32Array) {
        return "float32";
      } else if (values instanceof Int32Array || values instanceof Uint8Array || values instanceof Uint8ClampedArray) {
        return "int32";
      } else if (isNumber(values)) {
        return "float32";
      } else if (isString(values)) {
        return "string";
      } else if (isBoolean(values)) {
        return "bool";
      }
      return "float32";
    }
    function isFunction(f) {
      return !!(f && f.constructor && f.call && f.apply);
    }
    function nearestDivisor(size, start) {
      for (var i = start; i < size; ++i) {
        if (size % i === 0) {
          return i;
        }
      }
      return size;
    }
    function computeStrides(shape) {
      var rank = shape.length;
      if (rank < 2) {
        return [];
      }
      var strides = new Array(rank - 1);
      strides[rank - 2] = shape[rank - 1];
      for (var i = rank - 3; i >= 0; --i) {
        strides[i] = strides[i + 1] * shape[i + 1];
      }
      return strides;
    }
    function createNestedArray(offset, shape, a, isComplex) {
      if (isComplex === void 0) {
        isComplex = false;
      }
      var ret = new Array();
      if (shape.length === 1) {
        var d = shape[0] * (isComplex ? 2 : 1);
        for (var i = 0; i < d; i++) {
          ret[i] = a[offset + i];
        }
      } else {
        var d = shape[0];
        var rest = shape.slice(1);
        var len = rest.reduce(function(acc, c) {
          return acc * c;
        }) * (isComplex ? 2 : 1);
        for (var i = 0; i < d; i++) {
          ret[i] = createNestedArray(offset + i * len, rest, a, isComplex);
        }
      }
      return ret;
    }
    function toNestedArray(shape, a, isComplex) {
      if (isComplex === void 0) {
        isComplex = false;
      }
      if (shape.length === 0) {
        return a[0];
      }
      var size = shape.reduce(function(acc, c) {
        return acc * c;
      }) * (isComplex ? 2 : 1);
      if (size === 0) {
        return [];
      }
      if (size !== a.length) {
        throw new Error("[".concat(shape, "] does not match the input size ").concat(a.length).concat(isComplex ? " for a complex tensor" : "", "."));
      }
      return createNestedArray(0, shape, a, isComplex);
    }
    function convertBackendValuesAndArrayBuffer(data, dtype) {
      if (Array.isArray(data)) {
        return data;
      }
      if (dtype === "float32") {
        return data instanceof Float32Array ? data : new Float32Array(data);
      } else if (dtype === "int32") {
        return data instanceof Int32Array ? data : new Int32Array(data);
      } else if (dtype === "bool" || dtype === "string") {
        return Uint8Array.from(new Int32Array(data));
      } else {
        throw new Error("Unknown dtype ".concat(dtype));
      }
    }
    function makeOnesTypedArray(size, dtype) {
      var array = makeZerosTypedArray(size, dtype);
      for (var i = 0; i < array.length; i++) {
        array[i] = 1;
      }
      return array;
    }
    function makeZerosTypedArray(size, dtype) {
      if (dtype == null || dtype === "float32" || dtype === "complex64") {
        return new Float32Array(size);
      } else if (dtype === "int32") {
        return new Int32Array(size);
      } else if (dtype === "bool") {
        return new Uint8Array(size);
      } else {
        throw new Error("Unknown data type ".concat(dtype));
      }
    }
    function makeZerosNestedTypedArray(shape, dtype) {
      var size = shape.reduce(function(prev, curr) {
        return prev * curr;
      }, 1);
      if (dtype == null || dtype === "float32") {
        return toNestedArray(shape, new Float32Array(size));
      } else if (dtype === "int32") {
        return toNestedArray(shape, new Int32Array(size));
      } else if (dtype === "bool") {
        return toNestedArray(shape, new Uint8Array(size));
      } else {
        throw new Error("Unknown data type ".concat(dtype));
      }
    }
    function assertNonNegativeIntegerDimensions(shape) {
      shape.forEach(function(dimSize) {
        assert(Number.isInteger(dimSize) && dimSize >= 0, function() {
          return "Tensor must have a shape comprised of positive integers but got " + "shape [".concat(shape, "].");
        });
      });
    }
    function locToIndex(locs, rank, strides) {
      if (rank === 0) {
        return 0;
      } else if (rank === 1) {
        return locs[0];
      }
      var index = locs[locs.length - 1];
      for (var i = 0; i < locs.length - 1; ++i) {
        index += strides[i] * locs[i];
      }
      return index;
    }
    function indexToLoc(index, rank, strides) {
      if (rank === 0) {
        return [];
      } else if (rank === 1) {
        return [index];
      }
      var locs = new Array(rank);
      for (var i = 0; i < locs.length - 1; ++i) {
        locs[i] = Math.floor(index / strides[i]);
        index -= locs[i] * strides[i];
      }
      locs[locs.length - 1] = index;
      return locs;
    }
    function isPromise(object) {
      return object && object.then && typeof object.then === "function";
    }
    var TENSORFLOWJS_FLAGS_PREFIX = "tfjsflags";
    var Environment = (
      /** @class */
      function() {
        function Environment2(global2) {
          this.global = global2;
          this.flags = {};
          this.flagRegistry = {};
          this.urlFlags = {};
          this.getQueryParams = getQueryParams;
          this.populateURLFlags();
        }
        Environment2.prototype.setPlatform = function(platformName, platform) {
          if (this.platform != null) {
            if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) {
              console.warn("Platform ".concat(this.platformName, " has already been set. ") + "Overwriting the platform with ".concat(platformName, "."));
            }
          }
          this.platformName = platformName;
          this.platform = platform;
        };
        Environment2.prototype.registerFlag = function(flagName, evaluationFn, setHook) {
          this.flagRegistry[flagName] = { evaluationFn, setHook };
          if (this.urlFlags[flagName] != null) {
            var flagValue = this.urlFlags[flagName];
            if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) {
              console.warn("Setting feature override from URL ".concat(flagName, ": ").concat(flagValue, "."));
            }
            this.set(flagName, flagValue);
          }
        };
        Environment2.prototype.getAsync = function(flagName) {
          return __awaiter(this, void 0, void 0, function() {
            var _a, _b;
            return __generator(this, function(_c) {
              switch (_c.label) {
                case 0:
                  if (flagName in this.flags) {
                    return [2, this.flags[flagName]];
                  }
                  _a = this.flags;
                  _b = flagName;
                  return [4, this.evaluateFlag(flagName)];
                case 1:
                  _a[_b] = _c.sent();
                  return [2, this.flags[flagName]];
              }
            });
          });
        };
        Environment2.prototype.get = function(flagName) {
          if (flagName in this.flags) {
            return this.flags[flagName];
          }
          var flagValue = this.evaluateFlag(flagName);
          if (isPromise(flagValue)) {
            throw new Error("Flag ".concat(flagName, " cannot be synchronously evaluated. ") + "Please use getAsync() instead.");
          }
          this.flags[flagName] = flagValue;
          return this.flags[flagName];
        };
        Environment2.prototype.getNumber = function(flagName) {
          return this.get(flagName);
        };
        Environment2.prototype.getBool = function(flagName) {
          return this.get(flagName);
        };
        Environment2.prototype.getString = function(flagName) {
          return this.get(flagName);
        };
        Environment2.prototype.getFlags = function() {
          return this.flags;
        };
        Object.defineProperty(Environment2.prototype, "features", {
          // For backwards compatibility.
          get: function() {
            return this.flags;
          },
          enumerable: false,
          configurable: true
        });
        Environment2.prototype.set = function(flagName, value) {
          if (this.flagRegistry[flagName] == null) {
            throw new Error("Cannot set flag ".concat(flagName, " as it has not been registered."));
          }
          this.flags[flagName] = value;
          if (this.flagRegistry[flagName].setHook != null) {
            this.flagRegistry[flagName].setHook(value);
          }
        };
        Environment2.prototype.evaluateFlag = function(flagName) {
          if (this.flagRegistry[flagName] == null) {
            throw new Error("Cannot evaluate flag '".concat(flagName, "': no evaluation function found."));
          }
          return this.flagRegistry[flagName].evaluationFn();
        };
        Environment2.prototype.setFlags = function(flags) {
          this.flags = Object.assign({}, flags);
        };
        Environment2.prototype.reset = function() {
          this.flags = {};
          this.urlFlags = {};
          this.populateURLFlags();
        };
        Environment2.prototype.populateURLFlags = function() {
          var _this = this;
          if (typeof this.global === "undefined" || typeof this.global.location === "undefined" || typeof this.global.location.search === "undefined") {
            return;
          }
          var urlParams = this.getQueryParams(this.global.location.search);
          if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {
            var keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(",");
            keyValues.forEach(function(keyValue) {
              var _a = __read(keyValue.split(":"), 2), key = _a[0], value = _a[1];
              _this.urlFlags[key] = parseValue(key, value);
            });
          }
        };
        return Environment2;
      }()
    );
    function getQueryParams(queryString) {
      var params = {};
      queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, function(s) {
        var t = [];
        for (var _i = 1; _i < arguments.length; _i++) {
          t[_i - 1] = arguments[_i];
        }
        decodeParam(params, t[0], t[1]);
        return t.join("=");
      });
      return params;
    }
    function decodeParam(params, name, value) {
      params[decodeURIComponent(name)] = decodeURIComponent(value || "");
    }
    function parseValue(flagName, value) {
      var lowerCaseValue = value.toLowerCase();
      if (lowerCaseValue === "true" || lowerCaseValue === "false") {
        return lowerCaseValue === "true";
      } else if ("".concat(+lowerCaseValue) === lowerCaseValue) {
        return +lowerCaseValue;
      } else {
        return value;
      }
    }
    function env() {
      return exports2.ENV;
    }
    exports2.ENV = null;
    function setEnvironmentGlobal(environment) {
      exports2.ENV = environment;
    }
    var globalNameSpace;
    function getGlobalNamespace() {
      if (globalNameSpace == null) {
        var ns = void 0;
        if (typeof window !== "undefined") {
          ns = window;
        } else if (typeof global !== "undefined") {
          ns = global;
        } else if (typeof process !== "undefined") {
          ns = process;
        } else if (typeof self !== "undefined") {
          ns = self;
        } else {
          throw new Error("Could not find a global object");
        }
        globalNameSpace = ns;
      }
      return globalNameSpace;
    }
    function getGlobalMap() {
      var ns = getGlobalNamespace();
      if (ns._tfGlobals == null) {
        ns._tfGlobals = /* @__PURE__ */ new Map();
      }
      return ns._tfGlobals;
    }
    function getGlobal(key, init) {
      var globalMap = getGlobalMap();
      if (globalMap.has(key)) {
        return globalMap.get(key);
      } else {
        var singleton = init();
        globalMap.set(key, singleton);
        return globalMap.get(key);
      }
    }
    var Abs = "Abs";
    var Acos = "Acos";
    var Acosh = "Acosh";
    var Add = "Add";
    var AddN = "AddN";
    var All = "All";
    var Any = "Any";
    var ArgMax = "ArgMax";
    var ArgMin = "ArgMin";
    var Asin = "Asin";
    var Asinh = "Asinh";
    var Atan = "Atan";
    var Atanh = "Atanh";
    var Atan2 = "Atan2";
    var AvgPool = "AvgPool";
    var AvgPoolGrad = "AvgPoolGrad";
    var AvgPool3D = "AvgPool3D";
    var AvgPool3DGrad = "AvgPool3DGrad";
    var BatchMatMul = "BatchMatMul";
    var BatchToSpaceND = "BatchToSpaceND";
    var Bincount = "Bincount";
    var BitwiseAnd = "BitwiseAnd";
    var BroadcastTo = "BroadcastTo";
    var BroadcastArgs = "BroadcastArgs";
    var Cast = "Cast";
    var Ceil = "Ceil";
    var ClipByValue = "ClipByValue";
    var Complex = "Complex";
    var ComplexAbs = "ComplexAbs";
    var Concat = "Concat";
    var Conv2D = "Conv2D";
    var Conv2DBackpropFilter = "Conv2DBackpropFilter";
    var Conv2DBackpropInput = "Conv2DBackpropInput";
    var Conv3D = "Conv3D";
    var Conv3DBackpropFilterV2 = "Conv3DBackpropFilterV2";
    var Conv3DBackpropInputV2 = "Conv3DBackpropInputV2";
    var Cos = "Cos";
    var Cosh = "Cosh";
    var Cumprod = "Cumprod";
    var Cumsum = "Cumsum";
    var CropAndResize = "CropAndResize";
    var DenseBincount = "DenseBincount";
    var DepthToSpace = "DepthToSpace";
    var DepthwiseConv2dNative = "DepthwiseConv2dNative";
    var DepthwiseConv2dNativeBackpropFilter = "DepthwiseConv2dNativeBackpropFilter";
    var DepthwiseConv2dNativeBackpropInput = "DepthwiseConv2dNativeBackpropInput";
    var Diag = "Diag";
    var Dilation2D = "Dilation2D";
    var Dilation2DBackpropInput = "Dilation2DBackpropInput";
    var Dilation2DBackpropFilter = "Dilation2DBackpropFilter";
    var Draw = "Draw";
    var RealDiv = "RealDiv";
    var Einsum = "Einsum";
    var Elu = "Elu";
    var EluGrad = "EluGrad";
    var Erf = "Erf";
    var Equal = "Equal";
    var Exp = "Exp";
    var ExpandDims = "ExpandDims";
    var Expm1 = "Expm1";
    var FFT = "FFT";
    var Fill = "Fill";
    var FlipLeftRight = "FlipLeftRight";
    var Floor = "Floor";
    var FloorDiv = "FloorDiv";
    var FusedBatchNorm = "FusedBatchNorm";
    var GatherV2 = "GatherV2";
    var GatherNd = "GatherNd";
    var Greater = "Greater";
    var GreaterEqual = "GreaterEqual";
    var Identity = "Identity";
    var IFFT = "IFFT";
    var Imag = "Imag";
    var IsFinite = "IsFinite";
    var IsInf = "IsInf";
    var IsNan = "IsNan";
    var LeakyRelu = "LeakyRelu";
    var Less = "Less";
    var LessEqual = "LessEqual";
    var LinSpace = "LinSpace";
    var Log = "Log";
    var Log1p = "Log1p";
    var LogicalAnd = "LogicalAnd";
    var LogicalNot = "LogicalNot";
    var LogicalOr = "LogicalOr";
    var LogicalXor = "LogicalXor";
    var LogSoftmax = "LogSoftmax";
    var LowerBound = "LowerBound";
    var LRN = "LRN";
    var LRNGrad = "LRNGrad";
    var MatrixBandPart = "MatrixBandPart";
    var Max = "Max";
    var Maximum = "Maximum";
    var MaxPool = "MaxPool";
    var MaxPoolGrad = "MaxPoolGrad";
    var MaxPool3D = "MaxPool3D";
    var MaxPool3DGrad = "MaxPool3DGrad";
    var MaxPoolWithArgmax = "MaxPoolWithArgmax";
    var Mean = "Mean";
    var Min = "Min";
    var Minimum = "Minimum";
    var MirrorPad = "MirrorPad";
    var Mod = "Mod";
    var Multinomial = "Multinomial";
    var Multiply = "Multiply";
    var Neg = "Neg";
    var NotEqual = "NotEqual";
    var NonMaxSuppressionV3 = "NonMaxSuppressionV3";
    var NonMaxSuppressionV4 = "NonMaxSuppressionV4";
    var NonMaxSuppressionV5 = "NonMaxSuppressionV5";
    var OnesLike = "OnesLike";
    var OneHot = "OneHot";
    var Pack = "Pack";
    var PadV2 = "PadV2";
    var Pool = "Pool";
    var Pow = "Pow";
    var Prelu = "Prelu";
    var Prod = "Prod";
    var RaggedGather = "RaggedGather";
    var RaggedRange = "RaggedRange";
    var RaggedTensorToTensor = "RaggedTensorToTensor";
    var Range = "Range";
    var Real = "Real";
    var Reciprocal = "Reciprocal";
    var Relu = "Relu";
    var Reshape = "Reshape";
    var ResizeNearestNeighbor = "ResizeNearestNeighbor";
    var ResizeNearestNeighborGrad = "ResizeNearestNeighborGrad";
    var ResizeBilinear = "ResizeBilinear";
    var ResizeBilinearGrad = "ResizeBilinearGrad";
    var Relu6 = "Relu6";
    var Reverse = "Reverse";
    var Round = "Round";
    var Rsqrt = "Rsqrt";
    var ScatterNd = "ScatterNd";
    var TensorScatterUpdate = "TensorScatterUpdate";
    var SearchSorted = "SearchSorted";
    var Select = "Select";
    var Selu = "Selu";
    var Slice = "Slice";
    var Sin = "Sin";
    var Sinh = "Sinh";
    var Sign = "Sign";
    var Sigmoid = "Sigmoid";
    var Softplus = "Softplus";
    var Sqrt = "Sqrt";
    var Sum = "Sum";
    var SpaceToBatchND = "SpaceToBatchND";
    var SplitV = "SplitV";
    var Softmax = "Softmax";
    var SparseFillEmptyRows = "SparseFillEmptyRows";
    var SparseReshape = "SparseReshape";
    var SparseSegmentMean = "SparseSegmentMean";
    var SparseSegmentSum = "SparseSegmentSum";
    var SparseToDense = "SparseToDense";
    var SquaredDifference = "SquaredDifference";
    var Square = "Square";
    var StaticRegexReplace = "StaticRegexReplace";
    var StridedSlice = "StridedSlice";
    var StringNGrams = "StringNGrams";
    var StringSplit = "StringSplit";
    var StringToHashBucketFast = "StringToHashBucketFast";
    var Sub = "Sub";
    var Tan = "Tan";
    var Tanh = "Tanh";
    var Tile = "Tile";
    var TopK = "TopK";
    var Transform = "Transform";
    var Transpose = "Transpose";
    var Unique = "Unique";
    var Unpack = "Unpack";
    var UnsortedSegmentSum = "UnsortedSegmentSum";
    var UpperBound = "UpperBound";
    var ZerosLike = "ZerosLike";
    var Step = "Step";
    var FromPixels = "FromPixels";
    var RotateWithOffset = "RotateWithOffset";
    var _FusedMatMul = "_FusedMatMul";
    var FusedConv2D = "FusedConv2D";
    var FusedDepthwiseConv2D = "FusedDepthwiseConv2D";
    function warn() {
      var msg = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        msg[_i] = arguments[_i];
      }
      if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) {
        console.warn.apply(console, __spreadArray([], __read(msg), false));
      }
    }
    function log$1() {
      var msg = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        msg[_i] = arguments[_i];
      }
      if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) {
        console.log.apply(console, __spreadArray([], __read(msg), false));
      }
    }
    var kernelRegistry = getGlobal("kernelRegistry", function() {
      return /* @__PURE__ */ new Map();
    });
    var gradRegistry = getGlobal("gradRegistry", function() {
      return /* @__PURE__ */ new Map();
    });
    function getKernel(kernelName, backendName) {
      var key = makeKey(kernelName, backendName);
      return kernelRegistry.get(key);
    }
    function getGradient(kernelName) {
      return gradRegistry.get(kernelName);
    }
    function getKernelsForBackend(backendName) {
      var it = kernelRegistry.entries();
      var result = [];
      while (true) {
        var _a = it.next(), done = _a.done, value = _a.value;
        if (done) {
          break;
        }
        var _b = __read(value, 2), key = _b[0], config = _b[1];
        var _c = __read(key.split("_"), 1), backend2 = _c[0];
        if (backend2 === backendName) {
          result.push(config);
        }
      }
      return result;
    }
    function registerKernel(config) {
      var kernelName = config.kernelName, backendName = config.backendName;
      var key = makeKey(kernelName, backendName);
      if (kernelRegistry.has(key)) {
        warn("The kernel '".concat(kernelName, "' for backend ") + "'".concat(backendName, "' is already registered"));
      }
      kernelRegistry.set(key, config);
    }
    function registerGradient(config) {
      var kernelName = config.kernelName;
      if (gradRegistry.has(kernelName)) {
        if (env().getBool("DEBUG")) {
          warn("Overriding the gradient for '".concat(kernelName, "'"));
        }
      }
      gradRegistry.set(kernelName, config);
    }
    function unregisterKernel(kernelName, backendName) {
      var key = makeKey(kernelName, backendName);
      if (!kernelRegistry.has(key)) {
        throw new Error("The kernel '".concat(kernelName, "' for backend ") + "'".concat(backendName, "' is not registered"));
      }
      kernelRegistry.delete(key);
    }
    function unregisterGradient(kernelName) {
      if (!gradRegistry.has(kernelName)) {
        throw new Error("The gradient '".concat(kernelName, "' for backend is not registered"));
      }
      gradRegistry.delete(kernelName);
    }
    function copyRegisteredKernels(registeredBackendName, newBackendName) {
      var kernels = getKernelsForBackend(registeredBackendName);
      kernels.forEach(function(kernelConfig) {
        var newKernelConfig = Object.assign({}, kernelConfig, { backendName: newBackendName });
        registerKernel(newKernelConfig);
      });
    }
    function makeKey(kernelName, backendName) {
      return "".concat(backendName, "_").concat(kernelName);
    }
    function isTypedArrayBrowser(a) {
      return a instanceof Float32Array || a instanceof Int32Array || a instanceof Uint8Array || a instanceof Uint8ClampedArray;
    }
    var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
    function getDefaultExportFromCjs(x) {
      return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
    }
    var long = Long$1;
    var wasm = null;
    try {
      wasm = 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 Long$1(low, high, unsigned) {
      this.low = low | 0;
      this.high = high | 0;
      this.unsigned = !!unsigned;
    }
    Long$1.prototype.__isLong__;
    Object.defineProperty(Long$1.prototype, "__isLong__", { value: true });
    function isLong(obj) {
      return (obj && obj["__isLong__"]) === true;
    }
    Long$1.isLong = isLong;
    var INT_CACHE = {};
    var UINT_CACHE = {};
    function fromInt(value, unsigned) {
      var obj, cachedObj, cache;
      if (unsigned) {
        value >>>= 0;
        if (cache = 0 <= value && value < 256) {
          cachedObj = UINT_CACHE[value];
          if (cachedObj)
            return cachedObj;
        }
        obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
        if (cache)
          UINT_CACHE[value] = obj;
        return obj;
      } else {
        value |= 0;
        if (cache = -128 <= value && value < 128) {
          cachedObj = INT_CACHE[value];
          if (cachedObj)
            return cachedObj;
        }
        obj = fromBits(value, value < 0 ? -1 : 0, false);
        if (cache)
          INT_CACHE[value] = obj;
        return obj;
      }
    }
    Long$1.fromInt = fromInt;
    function fromNumber(value, unsigned) {
      if (isNaN(value))
        return unsigned ? UZERO : ZERO;
      if (unsigned) {
        if (value < 0)
          return UZERO;
        if (value >= TWO_PWR_64_DBL)
          return MAX_UNSIGNED_VALUE;
      } else {
        if (value <= -TWO_PWR_63_DBL)
          return MIN_VALUE;
        if (value + 1 >= TWO_PWR_63_DBL)
          return MAX_VALUE;
      }
      if (value < 0)
        return fromNumber(-value, unsigned).neg();
      return fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned);
    }
    Long$1.fromNumber = fromNumber;
    function fromBits(lowBits, highBits, unsigned) {
      return new Long$1(lowBits, highBits, unsigned);
    }
    Long$1.fromBits = fromBits;
    var pow_dbl = Math.pow;
    function fromString(str, unsigned, radix) {
      if (str.length === 0)
        throw Error("empty string");
      if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
        return ZERO;
      if (typeof unsigned === "number") {
        radix = unsigned, unsigned = false;
      } else {
        unsigned = !!unsigned;
      }
      radix = radix || 10;
      if (radix < 2 || 36 < radix)
        throw RangeError("radix");
      var p;
      if ((p = str.indexOf("-")) > 0)
        throw Error("interior hyphen");
      else if (p === 0) {
        return fromString(str.substring(1), unsigned, radix).neg();
      }
      var radixToPower = fromNumber(pow_dbl(radix, 8));
      var result = ZERO;
      for (var i = 0; i < str.length; i += 8) {
        var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
        if (size < 8) {
          var power = fromNumber(pow_dbl(radix, size));
          result = result.mul(power).add(fromNumber(value));
        } else {
          result = result.mul(radixToPower);
          result = result.add(fromNumber(value));
        }
      }
      result.unsigned = unsigned;
      return result;
    }
    Long$1.fromString = fromString;
    function fromValue(val, unsigned) {
      if (typeof val === "number")
        return fromNumber(val, unsigned);
      if (typeof val === "string")
        return fromString(val, unsigned);
      return fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned);
    }
    Long$1.fromValue = fromValue;
    var TWO_PWR_16_DBL = 1 << 16;
    var TWO_PWR_24_DBL = 1 << 24;
    var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
    var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
    var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
    var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
    var ZERO = fromInt(0);
    Long$1.ZERO = ZERO;
    var UZERO = fromInt(0, true);
    Long$1.UZERO = UZERO;
    var ONE = fromInt(1);
    Long$1.ONE = ONE;
    var UONE = fromInt(1, true);
    Long$1.UONE = UONE;
    var NEG_ONE = fromInt(-1);
    Long$1.NEG_ONE = NEG_ONE;
    var MAX_VALUE = fromBits(4294967295 | 0, 2147483647 | 0, false);
    Long$1.MAX_VALUE = MAX_VALUE;
    var MAX_UNSIGNED_VALUE = fromBits(4294967295 | 0, 4294967295 | 0, true);
    Long$1.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
    var MIN_VALUE = fromBits(0, 2147483648 | 0, false);
    Long$1.MIN_VALUE = MIN_VALUE;
    var LongPrototype = Long$1.prototype;
    LongPrototype.toInt = function toInt() {
      return this.unsigned ? this.low >>> 0 : this.low;
    };
    LongPrototype.toNumber = function toNumber() {
      if (this.unsigned)
        return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
      return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
    };
    LongPrototype.toString = function toString(radix) {
      radix = radix || 10;
      if (radix < 2 || 36 < radix)
        throw RangeError("radix");
      if (this.isZero())
        return "0";
      if (this.isNegative()) {
        if (this.eq(MIN_VALUE)) {
          var radixLong = fromNumber(radix), div2 = this.div(radixLong), rem1 = div2.mul(radixLong).sub(this);
          return div2.toString(radix) + rem1.toInt().toString(radix);
        } else
          return "-" + this.neg().toString(radix);
      }
      var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), rem = this;
      var result = "";
      while (true) {
        var remDiv = rem.div(radixToPower), intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, digits = intval.toString(radix);
        rem = remDiv;
        if (rem.isZero())
          return digits + result;
        else {
          while (digits.length < 6)
            digits = "0" + digits;
          result = "" + digits + result;
        }
      }
    };
    LongPrototype.getHighBits = function getHighBits() {
      return this.high;
    };
    LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
      return this.high >>> 0;
    };
    LongPrototype.getLowBits = function getLowBits() {
      return this.low;
    };
    LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
      return this.low >>> 0;
    };
    LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
      if (this.isNegative())
        return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
      var val = this.high != 0 ? this.high : this.low;
      for (var bit = 31; bit > 0; bit--)
        if ((val & 1 << bit) != 0)
          break;
      return this.high != 0 ? bit + 33 : bit + 1;
    };
    LongPrototype.isZero = function isZero() {
      return this.high === 0 && this.low === 0;
    };
    LongPrototype.eqz = LongPrototype.isZero;
    LongPrototype.isNegative = function isNegative() {
      return !this.unsigned && this.high < 0;
    };
    LongPrototype.isPositive = function isPositive() {
      return this.unsigned || this.high >= 0;
    };
    LongPrototype.isOdd = function isOdd() {
      return (this.low & 1) === 1;
    };
    LongPrototype.isEven = function isEven() {
      return (this.low & 1) === 0;
    };
    LongPrototype.equals = function equals(other) {
      if (!isLong(other))
        other = fromValue(other);
      if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
        return false;
      return this.high === other.high && this.low === other.low;
    };
    LongPrototype.eq = LongPrototype.equals;
    LongPrototype.notEquals = function notEquals(other) {
      return !this.eq(
        /* validates */
        other
      );
    };
    LongPrototype.neq = LongPrototype.notEquals;
    LongPrototype.ne = LongPrototype.notEquals;
    LongPrototype.lessThan = function lessThan(other) {
      return this.comp(
        /* validates */
        other
      ) < 0;
    };
    LongPrototype.lt = LongPrototype.lessThan;
    LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
      return this.comp(
        /* validates */
        other
      ) <= 0;
    };
    LongPrototype.lte = LongPrototype.lessThanOrEqual;
    LongPrototype.le = LongPrototype.lessThanOrEqual;
    LongPrototype.greaterThan = function greaterThan(other) {
      return this.comp(
        /* validates */
        other
      ) > 0;
    };
    LongPrototype.gt = LongPrototype.greaterThan;
    LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
      return this.comp(
        /* validates */
        other
      ) >= 0;
    };
    LongPrototype.gte = LongPrototype.greaterThanOrEqual;
    LongPrototype.ge = LongPrototype.greaterThanOrEqual;
    LongPrototype.compare = function compare(other) {
      if (!isLong(other))
        other = fromValue(other);
      if (this.eq(other))
        return 0;
      var thisNeg = this.isNegative(), otherNeg = other.isNegative();
      if (thisNeg && !otherNeg)
        return -1;
      if (!thisNeg && otherNeg)
        return 1;
      if (!this.unsigned)
        return this.sub(other).isNegative() ? -1 : 1;
      return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1;
    };
    LongPrototype.comp = LongPrototype.compare;
    LongPrototype.negate = function negate() {
      if (!this.unsigned && this.eq(MIN_VALUE))
        return MIN_VALUE;
      return this.not().add(ONE);
    };
    LongPrototype.neg = LongPrototype.negate;
    LongPrototype.add = function add2(addend) {
      if (!isLong(addend))
        addend = fromValue(addend);
      var a48 = this.high >>> 16;
      var a32 = this.high & 65535;
      var a16 = this.low >>> 16;
      var a00 = this.low & 65535;
      var b48 = addend.high >>> 16;
      var b32 = addend.high & 65535;
      var b16 = addend.low >>> 16;
      var b00 = addend.low & 65535;
      var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
      c00 += a00 + b00;
      c16 += c00 >>> 16;
      c00 &= 65535;
      c16 += a16 + b16;
      c32 += c16 >>> 16;
      c16 &= 65535;
      c32 += a32 + b32;
      c48 += c32 >>> 16;
      c32 &= 65535;
      c48 += a48 + b48;
      c48 &= 65535;
      return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
    };
    LongPrototype.subtract = function subtract(subtrahend) {
      if (!isLong(subtrahend))
        subtrahend = fromValue(subtrahend);
      return this.add(subtrahend.neg());
    };
    LongPrototype.sub = LongPrototype.subtract;
    LongPrototype.multiply = function multiply(multiplier) {
      if (this.isZero())
        return ZERO;
      if (!isLong(multiplier))
        multiplier = fromValue(multiplier);
      if (wasm) {
        var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
        return fromBits(low, wasm.get_high(), this.unsigned);
      }
      if (multiplier.isZero())
        return ZERO;
      if (this.eq(MIN_VALUE))
        return multiplier.isOdd() ? MIN_VALUE : ZERO;
      if (multiplier.eq(MIN_VALUE))
        return this.isOdd() ? MIN_VALUE : ZERO;
      if (this.isNegative()) {
        if (multiplier.isNegative())
          return this.neg().mul(multiplier.neg());
        else
          return this.neg().mul(multiplier).neg();
      } else if (multiplier.isNegative())
        return this.mul(multiplier.neg()).neg();
      if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
        return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
      var a48 = this.high >>> 16;
      var a32 = this.high & 65535;
      var a16 = this.low >>> 16;
      var a00 = this.low & 65535;
      var b48 = multiplier.high >>> 16;
      var b32 = multiplier.high & 65535;
      var b16 = multiplier.low >>> 16;
      var b00 = multiplier.low & 65535;
      var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
      c00 += a00 * b00;
      c16 += c00 >>> 16;
      c00 &= 65535;
      c16 += a16 * b00;
      c32 += c16 >>> 16;
      c16 &= 65535;
      c16 += a00 * b16;
      c32 += c16 >>> 16;
      c16 &= 65535;
      c32 += a32 * b00;
      c48 += c32 >>> 16;
      c32 &= 65535;
      c32 += a16 * b16;
      c48 += c32 >>> 16;
      c32 &= 65535;
      c32 += a00 * b32;
      c48 += c32 >>> 16;
      c32 &= 65535;
      c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
      c48 &= 65535;
      return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
    };
    LongPrototype.mul = LongPrototype.multiply;
    LongPrototype.divide = function divide(divisor) {
      if (!isLong(divisor))
        divisor = fromValue(divisor);
      if (divisor.isZero())
        throw Error("division by zero");
      if (wasm) {
        if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) {
          return this;
        }
        var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
        return fromBits(low, wasm.get_high(), this.unsigned);
      }
      if (this.isZero())
        return this.unsigned ? UZERO : ZERO;
      var approx, rem, res;
      if (!this.unsigned) {
        if (this.eq(MIN_VALUE)) {
          if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
            return MIN_VALUE;
          else if (divisor.eq(MIN_VALUE))
            return ONE;
          else {
            var halfThis = this.shr(1);
            approx = halfThis.div(divisor).shl(1);
            if (approx.eq(ZERO)) {
              return divisor.isNegative() ? ONE : NEG_ONE;
            } else {
              rem = this.sub(divisor.mul(approx));
              res = approx.add(rem.div(divisor));
              return res;
            }
          }
        } else if (divisor.eq(MIN_VALUE))
          return this.unsigned ? UZERO : ZERO;
        if (this.isNegative()) {
          if (divisor.isNegative())
            return this.neg().div(divisor.neg());
          return this.neg().div(divisor).neg();
        } else if (divisor.isNegative())
          return this.div(divisor.neg()).neg();
        res = ZERO;
      } else {
        if (!divisor.unsigned)
          divisor = divisor.toUnsigned();
        if (divisor.gt(this))
          return UZERO;
        if (divisor.gt(this.shru(1)))
          return UONE;
        res = UZERO;
      }
      rem = this;
      while (rem.gte(divisor)) {
        approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
        var log2 = Math.ceil(Math.log(approx) / Math.LN2), delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48), approxRes = fromNumber(approx), approxRem = approxRes.mul(divisor);
        while (approxRem.isNegative() || approxRem.gt(rem)) {
          approx -= delta;
          approxRes = fromNumber(approx, this.unsigned);
          approxRem = approxRes.mul(divisor);
        }
        if (approxRes.isZero())
          approxRes = ONE;
        res = res.add(approxRes);
        rem = rem.sub(approxRem);
      }
      return res;
    };
    LongPrototype.div = LongPrototype.divide;
    LongPrototype.modulo = function modulo(divisor) {
      if (!isLong(divisor))
        divisor = fromValue(divisor);
      if (wasm) {
        var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
        return fromBits(low, wasm.get_high(), this.unsigned);
      }
      return this.sub(this.div(divisor).mul(divisor));
    };
    LongPrototype.mod = LongPrototype.modulo;
    LongPrototype.rem = LongPrototype.modulo;
    LongPrototype.not = function not() {
      return fromBits(~this.low, ~this.high, this.unsigned);
    };
    LongPrototype.and = function and(other) {
      if (!isLong(other))
        other = fromValue(other);
      return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
    };
    LongPrototype.or = function or(other) {
      if (!isLong(other))
        other = fromValue(other);
      return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
    };
    LongPrototype.xor = function xor(other) {
      if (!isLong(other))
        other = fromValue(other);
      return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
    };
    LongPrototype.shiftLeft = function shiftLeft(numBits) {
      if (isLong(numBits))
        numBits = numBits.toInt();
      if ((numBits &= 63) === 0)
        return this;
      else if (numBits < 32)
        return fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned);
      else
        return fromBits(0, this.low << numBits - 32, this.unsigned);
    };
    LongPrototype.shl = LongPrototype.shiftLeft;
    LongPrototype.shiftRight = function shiftRight(numBits) {
      if (isLong(numBits))
        numBits = numBits.toInt();
      if ((numBits &= 63) === 0)
        return this;
      else if (numBits < 32)
        return fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned);
      else
        return fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned);
    };
    LongPrototype.shr = LongPrototype.shiftRight;
    LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
      if (isLong(numBits))
        numBits = numBits.toInt();
      numBits &= 63;
      if (numBits === 0)
        return this;
      else {
        var high = this.high;
        if (numBits < 32) {
          var low = this.low;
          return fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits, this.unsigned);
        } else if (numBits === 32)
          return fromBits(high, 0, this.unsigned);
        else
          return fromBits(high >>> numBits - 32, 0, this.unsigned);
      }
    };
    LongPrototype.shru = LongPrototype.shiftRightUnsigned;
    LongPrototype.shr_u = LongPrototype.shiftRightUnsigned;
    LongPrototype.toSigned = function toSigned() {
      if (!this.unsigned)
        return this;
      return fromBits(this.low, this.high, false);
    };
    LongPrototype.toUnsigned = function toUnsigned() {
      if (this.unsigned)
        return this;
      return fromBits(this.low, this.high, true);
    };
    LongPrototype.toBytes = function toBytes(le) {
      return le ? this.toBytesLE() : this.toBytesBE();
    };
    LongPrototype.toBytesLE = function toBytesLE() {
      var hi = this.high, lo = this.low;
      return [
        lo & 255,
        lo >>> 8 & 255,
        lo >>> 16 & 255,
        lo >>> 24,
        hi & 255,
        hi >>> 8 & 255,
        hi >>> 16 & 255,
        hi >>> 24
      ];
    };
    LongPrototype.toBytesBE = function toBytesBE() {
      var hi = this.high, lo = this.low;
      return [
        hi >>> 24,
        hi >>> 16 & 255,
        hi >>> 8 & 255,
        hi & 255,
        lo >>> 24,
        lo >>> 16 & 255,
        lo >>> 8 & 255,
        lo & 255
      ];
    };
    Long$1.fromBytes = function fromBytes(bytes, unsigned, le) {
      return le ? Long$1.fromBytesLE(bytes, unsigned) : Long$1.fromBytesBE(bytes, unsigned);
    };
    Long$1.fromBytesLE = function fromBytesLE(bytes, unsigned) {
      return new Long$1(bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, unsigned);
    };
    Long$1.fromBytesBE = function fromBytesBE(bytes, unsigned) {
      return new Long$1(bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], unsigned);
    };
    var long$1 = /* @__PURE__ */ getDefaultExportFromCjs(long);
    var LongExports = /* @__PURE__ */ _mergeNamespaces({
      __proto__: null,
      default: long$1
    }, [long]);
    var Long = (
      // tslint:disable-next-line
      long$1 || LongExports
    );
    function hexToLong(hex) {
      return Long.fromString(hex, true, 16);
    }
    var k0 = hexToLong("c3a5c85c97cb3127");
    var k1 = hexToLong("b492b66fbe98f273");
    var k2 = hexToLong("9ae16a3b2f90404f");
    function shiftMix(val) {
      return val.xor(val.shru(47));
    }
    function fetch$2(s, offset, numBytes) {
      var bytes = s.slice(offset, offset + numBytes);
      return Long.fromBytes(Array.from(bytes), true, true);
    }
    function fetch64(s, offset) {
      return fetch$2(s, offset, 8);
    }
    function fetch32(s, offset) {
      return fetch$2(s, offset, 4);
    }
    function rotate64(val, shift) {
      return shift === 0 ? val : val.shru(shift).or(val.shl(64 - shift));
    }
    function hashLen16(u, v, mul2) {
      if (mul2 === void 0) {
        mul2 = hexToLong("9ddfea08eb382d69");
      }
      var a = u.xor(v).mul(mul2);
      a = a.xor(a.shru(47));
      var b = v.xor(a).mul(mul2);
      b = b.xor(b.shru(47));
      b = b.mul(mul2);
      return b;
    }
    function weakHashLen32WithSeeds(w, x, y, z, a, b) {
      a = a.add(w);
      b = rotate64(b.add(a).add(z), 21);
      var c = a;
      a = a.add(x);
      a = a.add(y);
      b = b.add(rotate64(a, 44));
      return [a.add(z), b.add(c)];
    }
    function weakHashLen32WithSeedsStr(s, offset, a, b) {
      return weakHashLen32WithSeeds(fetch64(s, offset), fetch64(s, offset + 8), fetch64(s, offset + 16), fetch64(s, offset + 24), a, b);
    }
    function hashLen0to16(s, len) {
      if (len === void 0) {
        len = s.length;
      }
      if (len >= 8) {
        var mul2 = k2.add(len * 2);
        var a = fetch64(s, 0).add(k2);
        var b = fetch64(s, len - 8);
        var c = rotate64(b, 37).mul(mul2).add(a);
        var d = rotate64(a, 25).add(b).mul(mul2);
        return hashLen16(c, d, mul2);
      }
      if (len >= 4) {
        var mul2 = k2.add(len * 2);
        var a = fetch32(s, 0);
        return hashLen16(a.shl(3).add(len), fetch32(s, len - 4), mul2);
      }
      if (len > 0) {
        var a = s[0];
        var b = s[len >> 1];
        var c = s[len - 1];
        var y = a + (b << 8);
        var z = len + (c << 2);
        return shiftMix(k2.mul(y).xor(k0.mul(z))).mul(k2);
      }
      return k2;
    }
    function hashLen17to32(s, len) {
      if (len === void 0) {
        len = s.length;
      }
      var mul2 = k2.add(len * 2);
      var a = fetch64(s, 0).mul(k1);
      var b = fetch64(s, 8);
      var c = fetch64(s, len - 8).mul(mul2);
      var d = fetch64(s, len - 16).mul(k2);
      return hashLen16(rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d), a.add(rotate64(b.add(k2), 18)).add(c), mul2);
    }
    function hashLen33to64(s, len) {
      if (len === void 0) {
        len = s.length;
      }
      var mul2 = k2.add(len * 2);
      var a = fetch64(s, 0).mul(k2);
      var b = fetch64(s, 8);
      var c = fetch64(s, len - 8).mul(mul2);
      var d = fetch64(s, len - 16).mul(k2);
      var y = rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d);
      var z = hashLen16(y, a.add(rotate64(b.add(k2), 18)).add(c), mul2);
      var e = fetch64(s, 16).mul(mul2);
      var f = fetch64(s, 24);
      var g = y.add(fetch64(s, len - 32)).mul(mul2);
      var h = z.add(fetch64(s, len - 24)).mul(mul2);
      return hashLen16(rotate64(e.add(f), 43).add(rotate64(g, 30)).add(h), e.add(rotate64(f.add(a), 18)).add(g), mul2);
    }
    function fingerPrint64(s, len) {
      var _a, _b;
      if (len === void 0) {
        len = s.length;
      }
      var seed = Long.fromNumber(81, true);
      if (len <= 32) {
        if (len <= 16) {
          return hashLen0to16(s, len);
        } else {
          return hashLen17to32(s, len);
        }
      } else if (len <= 64) {
        return hashLen33to64(s, len);
      }
      var x = seed;
      var y = seed.mul(k1).add(113);
      var z = shiftMix(y.mul(k2).add(113)).mul(k2);
      var v = [Long.UZERO, Long.UZERO];
      var w = [Long.UZERO, Long.UZERO];
      x = x.mul(k2).add(fetch64(s, 0));
      var offset = 0;
      var end = (len - 1 >> 6) * 64;
      var last64 = end + (len - 1 & 63) - 63;
      do {
        x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(k1);
        y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(k1);
        x = x.xor(w[1]);
        y = y.add(v[0]).add(fetch64(s, offset + 40));
        z = rotate64(z.add(w[0]), 33).mul(k1);
        v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(k1), x.add(w[0]));
        w = weakHashLen32WithSeedsStr(s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));
        _a = __read([x, z], 2), z = _a[0], x = _a[1];
        offset += 64;
      } while (offset !== end);
      var mul2 = k1.add(z.and(255).shl(1));
      offset = last64;
      w[0] = w[0].add(len - 1 & 63);
      v[0] = v[0].add(w[0]);
      w[0] = w[0].add(v[0]);
      x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(mul2);
      y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(mul2);
      x = x.xor(w[1].mul(9));
      y = y.add(v[0].mul(9).add(fetch64(s, offset + 40)));
      z = rotate64(z.add(w[0]), 33).mul(mul2);
      v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(mul2), x.add(w[0]));
      w = weakHashLen32WithSeedsStr(s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));
      _b = __read([x, z], 2), z = _b[0], x = _b[1];
      return hashLen16(hashLen16(v[0], w[0], mul2).add(shiftMix(y).mul(k0)).add(z), hashLen16(v[1], w[1], mul2).add(x), mul2);
    }
    function createScalarValue(value, dtype) {
      if (dtype === "string") {
        return encodeString(value);
      }
      return toTypedArray([value], dtype);
    }
    function noConversionNeeded(a, dtype) {
      return a instanceof Float32Array && dtype === "float32" || a instanceof Int32Array && dtype === "int32" || a instanceof Uint8Array && dtype === "bool";
    }
    function toTypedArray(a, dtype) {
      if (dtype === "string") {
        throw new Error("Cannot convert a string[] to a TypedArray");
      }
      if (Array.isArray(a)) {
        a = flatten(a);
      }
      if (env().getBool("DEBUG")) {
        checkConversionForErrors(a, dtype);
      }
      if (noConversionNeeded(a, dtype)) {
        return a;
      }
      if (dtype == null || dtype === "float32" || dtype === "complex64") {
        return new Float32Array(a);
      } else if (dtype === "int32") {
        return new Int32Array(a);
      } else if (dtype === "bool") {
        var bool = new Uint8Array(a.length);
        for (var i = 0; i < bool.length; ++i) {
          if (Math.round(a[i]) !== 0) {
            bool[i] = 1;
          }
        }
        return bool;
      } else {
        throw new Error("Unknown data type ".concat(dtype));
      }
    }
    function now() {
      return env().platform.now();
    }
    function fetch$1(path, requestInits) {
      return env().platform.fetch(path, requestInits);
    }
    function encodeString(s, encoding) {
      if (encoding === void 0) {
        encoding = "utf-8";
      }
      encoding = encoding || "utf-8";
      return env().platform.encode(s, encoding);
    }
    function decodeString(bytes, encoding) {
      if (encoding === void 0) {
        encoding = "utf-8";
      }
      encoding = encoding || "utf-8";
      return env().platform.decode(bytes, encoding);
    }
    function isTypedArray(a) {
      if (env().platform.isTypedArray != null) {
        return env().platform.isTypedArray(a);
      } else {
        return isTypedArrayBrowser(a);
      }
    }
    function flatten(arr, result, skipTypedArray) {
      var e_1, _a;
      if (result === void 0) {
        result = [];
      }
      if (skipTypedArray === void 0) {
        skipTypedArray = false;
      }
      if (result == null) {
        result = [];
      }
      if (typeof arr === "boolean" || typeof arr === "number" || typeof arr === "string" || isPromise(arr) || arr == null || isTypedArray(arr) && skipTypedArray) {
        result.push(arr);
      } else if (Array.isArray(arr) || isTypedArray(arr)) {
        for (var i = 0; i < arr.length; ++i) {
          flatten(arr[i], result, skipTypedArray);
        }
      } else {
        var maxIndex = -1;
        try {
          for (var _b = __values(Object.keys(arr)), _c = _b.next(); !_c.done; _c = _b.next()) {
            var key = _c.value;
            if (/^([1-9]+[0-9]*|0)$/.test(key)) {
              maxIndex = Math.max(maxIndex, Number(key));
            }
          }
        } catch (e_1_1) {
          e_1 = { error: e_1_1 };
        } finally {
          try {
            if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
          } finally {
            if (e_1) throw e_1.error;
          }
        }
        for (var i = 0; i <= maxIndex; i++) {
          flatten(arr[i], result, skipTypedArray);
        }
      }
      return result;
    }
    var util = {
      __proto__: null,
      arraysEqual,
      arraysEqualWithNull,
      assert,
      assertNonNegativeIntegerDimensions,
      assertNonNull,
      assertShapesMatch,
      bytesFromStringArray,
      bytesPerElement,
      checkConversionForErrors,
      clamp,
      computeStrides,
      convertBackendValuesAndArrayBuffer,
      createScalarValue,
      createShuffledIndices,
      decodeString,
      distSquared,
      encodeString,
      fetch: fetch$1,
      fingerPrint64,
      flatten,
      getArrayFromDType,
      getTypedArrayFromDType,
      hasEncodingLoss,
      hexToLong,
      indexToLoc,
      inferDtype,
      inferFromImplicitShape,
      isBoolean,
      isFunction,
      isInt,
      isNumber,
      isPromise,
      isScalarShape,
      isString,
      isTypedArray,
      isValidDtype,
      locToIndex,
      makeOnesTypedArray,
      makeZerosNestedTypedArray,
      makeZerosTypedArray,
      nearestDivisor,
      nearestLargerEven,
      now,
      parseAxisParam,
      randUniform,
      repeatedTry,
      rightPad,
      shuffle,
      shuffleCombo,
      sizeFromShape,
      sizeToSquarishShape,
      squeezeShape,
      sum: sum$1,
      swap,
      tanh: tanh$1,
      toNestedArray,
      toTypedArray
    };
    var Profiler = (
      /** @class */
      function() {
        function Profiler2(backendTimer, logger) {
          this.backendTimer = backendTimer;
          this.logger = logger;
          if (logger == null) {
            this.logger = new Logger();
          }
        }
        Profiler2.prototype.profileKernel = function(kernelName, inputs, f) {
          var e_1, _a;
          var outputs;
          var holdResultWrapperFn = function() {
            outputs = f();
          };
          var timer;
          var start = now();
          if (this.backendTimer.timerAvailable()) {
            timer = this.backendTimer.time(holdResultWrapperFn);
          } else {
            holdResultWrapperFn();
            try {
              for (var outputs_1 = __values(outputs), outputs_1_1 = outputs_1.next(); !outputs_1_1.done; outputs_1_1 = outputs_1.next()) {
                var output = outputs_1_1.value;
                output.dataSync();
              }
            } catch (e_1_1) {
              e_1 = { error: e_1_1 };
            } finally {
              try {
                if (outputs_1_1 && !outputs_1_1.done && (_a = outputs_1.return)) _a.call(outputs_1);
              } finally {
                if (e_1) throw e_1.error;
              }
            }
            timer = Promise.resolve({ kernelMs: now() - start });
          }
          if (env().getBool("CHECK_COMPUTATION_FOR_ERRORS")) {
            var _loop_1 = function(i2) {
              var output2 = outputs[i2];
              output2.data().then(function(tensorVals) {
                checkComputationForErrors(tensorVals, output2.dtype, kernelName);
              });
            };
            for (var i = 0; i < outputs.length; i++) {
              _loop_1(i);
            }
          }
          var kernelProfile = {
            kernelName,
            outputs,
            inputs,
            timeMs: timer.then(function(timing) {
              return timing.kernelMs;
            }),
            extraInfo: timer.then(function(timing) {
              return timing.getExtraProfileInfo != null ? timing.getExtraProfileInfo() : "";
            })
          };
          return kernelProfile;
        };
        Profiler2.prototype.logKernelProfile = function(kernelProfile) {
          var _this = this;
          var kernelName = kernelProfile.kernelName, outputs = kernelProfile.outputs, timeMs = kernelProfile.timeMs, inputs = kernelProfile.inputs, extraInfo = kernelProfile.extraInfo;
          outputs.forEach(function(result) {
            Promise.all([result.data(), timeMs, extraInfo]).then(function(valueContainer) {
              _this.logger.logKernelProfile(kernelName, result, valueContainer[0], valueContainer[1], inputs, valueContainer[2]);
            });
          });
        };
        return Profiler2;
      }()
    );
    function checkComputationForErrors(vals, dtype, kernelName) {
      if (dtype !== "float32") {
        return false;
      }
      for (var i = 0; i < vals.length; i++) {
        var num = vals[i];
        if (isNaN(num) || !isFinite(num)) {
          console.warn("Found ".concat(num, " in the result of '").concat(kernelName, "'"));
          return true;
        }
      }
      return false;
    }
    var Logger = (
      /** @class */
      function() {
        function Logger2() {
        }
        Logger2.prototype.logKernelProfile = function(name, result, vals, timeMs, inputs, extraInfo) {
          var time2 = typeof timeMs === "number" ? rightPad("".concat(timeMs, "ms"), 9) : timeMs["error"];
          var paddedName = rightPad(name, 25);
          var rank = result.rank;
          var size = result.size;
          var shape = rightPad(result.shape.toString(), 14);
          var inputShapesDescription = "";
          for (var name_1 in inputs) {
            var input = inputs[name_1];
            if (input != null) {
              var inputShape = input.shape || result.shape;
              var inputRank = inputShape.length;
              inputShapesDescription += "".concat(name_1, ": ").concat(inputRank, "D ").concat(inputRank > 0 ? inputShape : "", " ");
            }
          }
          console.log("%c".concat(paddedName, "	%c").concat(time2, "	%c").concat(rank, "D ").concat(shape, "	%c").concat(size, "	%c").concat(inputShapesDescription, "	%c").concat(extraInfo), "font-weight:bold", "color:red", "color:blue", "color: orange", "color: green", "color: steelblue");
        };
        return Logger2;
      }()
    );
    function getFilteredNodesXToY(tape, xs, y) {
      var tensorsFromX = {};
      var nodesFromX = {};
      for (var i = 0; i < xs.length; i++) {
        tensorsFromX[xs[i].id] = true;
      }
      for (var i = 0; i < tape.length; i++) {
        var node = tape[i];
        var nodeInputs = node.inputs;
        for (var inputName in nodeInputs) {
          var input = nodeInputs[inputName];
          var anyInputFromX = false;
          for (var j = 0; j < xs.length; j++) {
            if (tensorsFromX[input.id]) {
              node.outputs.forEach(function(output) {
                return tensorsFromX[output.id] = true;
              });
              anyInputFromX = true;
              nodesFromX[node.id] = true;
              break;
            }
          }
          if (anyInputFromX) {
            break;
          }
        }
      }
      var tensorsLeadToY = {};
      tensorsLeadToY[y.id] = true;
      var nodesToY = {};
      for (var i = tape.length - 1; i >= 0; i--) {
        var node = tape[i];
        var nodeInputs = node.inputs;
        for (var j = 0; j < node.outputs.length; j++) {
          if (tensorsLeadToY[node.outputs[j].id]) {
            for (var inputName in nodeInputs) {
              tensorsLeadToY[nodeInputs[inputName].id] = true;
              nodesToY[node.id] = true;
            }
            break;
          }
        }
      }
      var filteredTape = [];
      for (var i = 0; i < tape.length; i++) {
        var node = tape[i];
        if (nodesFromX[node.id] && nodesToY[node.id]) {
          var prunedInputs = {};
          for (var inputName in node.inputs) {
            var nodeInput = node.inputs[inputName];
            if (tensorsFromX[nodeInput.id]) {
              prunedInputs[inputName] = nodeInput;
            }
          }
          var prunedNode = Object.assign({}, node);
          prunedNode.inputs = prunedInputs;
          prunedNode.outputs = node.outputs;
          filteredTape.push(prunedNode);
        }
      }
      return filteredTape;
    }
    function backpropagateGradients(tensorAccumulatedGradientMap, filteredTape, tidy2, add2) {
      var _loop_1 = function(i2) {
        var node = filteredTape[i2];
        var dys = [];
        node.outputs.forEach(function(o) {
          var gradTensor = tensorAccumulatedGradientMap[o.id];
          if (gradTensor != null) {
            dys.push(gradTensor);
          } else {
            dys.push(null);
          }
        });
        if (node.gradient == null) {
          throw new Error("Cannot compute gradient: gradient function not found " + "for ".concat(node.kernelName, "."));
        }
        var inputGradients = node.gradient(dys);
        var _loop_2 = function(inputName2) {
          if (!(inputName2 in inputGradients)) {
            throw new Error("Cannot backprop through input ".concat(inputName2, ". ") + "Available gradients found: ".concat(Object.keys(inputGradients), "."));
          }
          var dx = tidy2(function() {
            return inputGradients[inputName2]();
          });
          if (dx.dtype !== "float32") {
            throw new Error("Error in gradient for op ".concat(node.kernelName, ". The gradient of input ") + "".concat(inputName2, " must have 'float32' dtype, but has '").concat(dx.dtype, "'"));
          }
          var x = node.inputs[inputName2];
          if (!arraysEqual(dx.shape, x.shape)) {
            throw new Error("Error in gradient for op ".concat(node.kernelName, ". The gradient of input ") + "'".concat(inputName2, "' has shape '").concat(dx.shape, "', which does not match ") + "the shape of the input '".concat(x.shape, "'"));
          }
          if (tensorAccumulatedGradientMap[x.id] == null) {
            tensorAccumulatedGradientMap[x.id] = dx;
          } else {
            var curGradient = tensorAccumulatedGradientMap[x.id];
            tensorAccumulatedGradientMap[x.id] = add2(curGradient, dx);
            curGradient.dispose();
          }
        };
        for (var inputName in node.inputs) {
          _loop_2(inputName);
        }
      };
      for (var i = filteredTape.length - 1; i >= 0; i--) {
        _loop_1(i);
      }
    }
    var FORMAT_LIMIT_NUM_VALS = 20;
    var FORMAT_NUM_FIRST_LAST_VALS = 3;
    var FORMAT_NUM_SIG_DIGITS = 7;
    function tensorToString(vals, shape, dtype, verbose) {
      var strides = computeStrides(shape);
      var padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides);
      var rank = shape.length;
      var valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol);
      var lines = ["Tensor"];
      if (verbose) {
        lines.push("  dtype: ".concat(dtype));
        lines.push("  rank: ".concat(rank));
        lines.push("  shape: [".concat(shape, "]"));
        lines.push("  values:");
      }
      lines.push(valsLines.map(function(l) {
        return "    " + l;
      }).join("\n"));
      return lines.join("\n");
    }
    function computeMaxSizePerColumn(vals, shape, dtype, strides) {
      var n = sizeFromShape(shape);
      var numCols = strides[strides.length - 1];
      var padPerCol = new Array(numCols).fill(0);
      var rank = shape.length;
      var valuesOrTuples = dtype === "complex64" ? createComplexTuples(vals) : vals;
      if (rank > 1) {
        for (var row = 0; row < n / numCols; row++) {
          var offset = row * numCols;
          for (var j = 0; j < numCols; j++) {
            padPerCol[j] = Math.max(padPerCol[j], valToString(valuesOrTuples[offset + j], 0, dtype).length);
          }
        }
      }
      return padPerCol;
    }
    function valToString(val, pad2, dtype) {
      var valStr;
      if (Array.isArray(val)) {
        valStr = "".concat(parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS)), " + ") + "".concat(parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS)), "j");
      } else if (isString(val)) {
        valStr = "'".concat(val, "'");
      } else if (dtype === "bool") {
        valStr = boolNumToString(val);
      } else {
        valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString();
      }
      return rightPad(valStr, pad2);
    }
    function boolNumToString(v) {
      return v === 0 ? "false" : "true";
    }
    function subTensorToString(vals, shape, dtype, strides, padPerCol, isLast) {
      if (isLast === void 0) {
        isLast = true;
      }
      var storagePerElement = dtype === "complex64" ? 2 : 1;
      var size = shape[0];
      var rank = shape.length;
      if (rank === 0) {
        if (dtype === "complex64") {
          var complexTuple = createComplexTuples(vals);
          return [valToString(complexTuple[0], 0, dtype)];
        }
        if (dtype === "bool") {
          return [boolNumToString(vals[0])];
        }
        return [vals[0].toString()];
      }
      if (rank === 1) {
        if (size > FORMAT_LIMIT_NUM_VALS) {
          var firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement;
          var firstVals = Array.from(vals.slice(0, firstValsSize));
          var lastVals = Array.from(vals.slice((size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement, size * storagePerElement));
          if (dtype === "complex64") {
            firstVals = createComplexTuples(firstVals);
            lastVals = createComplexTuples(lastVals);
          }
          return [
            "[" + firstVals.map(function(x, i2) {
              return valToString(x, padPerCol[i2], dtype);
            }).join(", ") + ", ..., " + lastVals.map(function(x, i2) {
              return valToString(x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i2], dtype);
            }).join(", ") + "]"
          ];
        }
        var displayVals = dtype === "complex64" ? createComplexTuples(vals) : Array.from(vals);
        return [
          "[" + displayVals.map(function(x, i2) {
            return valToString(x, padPerCol[i2], dtype);
          }).join(", ") + "]"
        ];
      }
      var subshape = shape.slice(1);
      var substrides = strides.slice(1);
      var stride = strides[0] * storagePerElement;
      var lines = [];
      if (size > FORMAT_LIMIT_NUM_VALS) {
        for (var i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {
          var start = i * stride;
          var end = start + stride;
          lines.push.apply(lines, __spreadArray([], __read(subTensorToString(
            vals.slice(start, end),
            subshape,
            dtype,
            substrides,
            padPerCol,
            false
            /* isLast */
          )), false));
        }
        lines.push("...");
        for (var i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {
          var start = i * stride;
          var end = start + stride;
          lines.push.apply(lines, __spreadArray([], __read(subTensorToString(
            vals.slice(start, end),
            subshape,
            dtype,
            substrides,
            padPerCol,
            i === size - 1
            /* isLast */
          )), false));
        }
      } else {
        for (var i = 0; i < size; i++) {
          var start = i * stride;
          var end = start + stride;
          lines.push.apply(lines, __spreadArray([], __read(subTensorToString(
            vals.slice(start, end),
            subshape,
            dtype,
            substrides,
            padPerCol,
            i === size - 1
            /* isLast */
          )), false));
        }
      }
      var sep = rank === 2 ? "," : "";
      lines[0] = "[" + (size > 0 ? lines[0] + sep : "");
      for (var i = 1; i < lines.length - 1; i++) {
        lines[i] = " " + lines[i] + sep;
      }
      var newLineSep = ",\n";
      for (var i = 2; i < rank; i++) {
        newLineSep += "\n";
      }
      lines[lines.length - 1] = " " + lines[lines.length - 1] + "]" + (isLast ? "" : newLineSep);
      return lines;
    }
    function createComplexTuples(vals) {
      var complexTuples = [];
      for (var i = 0; i < vals.length; i += 2) {
        complexTuples.push([vals[i], vals[i + 1]]);
      }
      return complexTuples;
    }
    var TensorBuffer = (
      /** @class */
      function() {
        function TensorBuffer2(shape, dtype, values) {
          var _this = this;
          this.dtype = dtype;
          this.shape = shape.slice();
          this.size = sizeFromShape(shape);
          if (values != null) {
            var n_1 = values.length;
            assert(n_1 === this.size, function() {
              return "Length of values '".concat(n_1, "' does not match the size ") + "inferred by the shape '".concat(_this.size, "'.");
            });
          }
          if (dtype === "complex64") {
            throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");
          }
          this.values = values || getArrayFromDType(dtype, this.size);
          this.strides = computeStrides(shape);
        }
        TensorBuffer2.prototype.set = function(value) {
          var _this = this;
          var locs = [];
          for (var _i = 1; _i < arguments.length; _i++) {
            locs[_i - 1] = arguments[_i];
          }
          if (locs.length === 0) {
            locs = [0];
          }
          assert(locs.length === this.rank, function() {
            return "The number of provided coordinates (".concat(locs.length, ") must ") + "match the rank (".concat(_this.rank, ")");
          });
          var index = this.locToIndex(locs);
          this.values[index] = value;
        };
        TensorBuffer2.prototype.get = function() {
          var e_1, _b;
          var locs = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            locs[_i] = arguments[_i];
          }
          if (locs.length === 0) {
            locs = [0];
          }
          var i = 0;
          try {
            for (var locs_1 = __values(locs), locs_1_1 = locs_1.next(); !locs_1_1.done; locs_1_1 = locs_1.next()) {
              var loc = locs_1_1.value;
              if (loc < 0 || loc >= this.shape[i]) {
                var msg = "Requested out of range element at ".concat(locs, ". ") + "  Buffer shape=".concat(this.shape);
                throw new Error(msg);
              }
              i++;
            }
          } catch (e_1_1) {
            e_1 = { error: e_1_1 };
          } finally {
            try {
              if (locs_1_1 && !locs_1_1.done && (_b = locs_1.return)) _b.call(locs_1);
            } finally {
              if (e_1) throw e_1.error;
            }
          }
          var index = locs[locs.length - 1];
          for (var i_1 = 0; i_1 < locs.length - 1; ++i_1) {
            index += this.strides[i_1] * locs[i_1];
          }
          return this.values[index];
        };
        TensorBuffer2.prototype.locToIndex = function(locs) {
          if (this.rank === 0) {
            return 0;
          } else if (this.rank === 1) {
            return locs[0];
          }
          var index = locs[locs.length - 1];
          for (var i = 0; i < locs.length - 1; ++i) {
            index += this.strides[i] * locs[i];
          }
          return index;
        };
        TensorBuffer2.prototype.indexToLoc = function(index) {
          if (this.rank === 0) {
            return [];
          } else if (this.rank === 1) {
            return [index];
          }
          var locs = new Array(this.shape.length);
          for (var i = 0; i < locs.length - 1; ++i) {
            locs[i] = Math.floor(index / this.strides[i]);
            index -= locs[i] * this.strides[i];
          }
          locs[locs.length - 1] = index;
          return locs;
        };
        Object.defineProperty(TensorBuffer2.prototype, "rank", {
          get: function() {
            return this.shape.length;
          },
          enumerable: false,
          configurable: true
        });
        TensorBuffer2.prototype.toTensor = function() {
          return trackerFn().makeTensor(this.values, this.shape, this.dtype);
        };
        return TensorBuffer2;
      }()
    );
    var trackerFn = null;
    var opHandler$1 = null;
    function setTensorTracker(fn) {
      trackerFn = fn;
    }
    function setOpHandler(handler) {
      opHandler$1 = handler;
    }
    var Tensor = (
      /** @class */
      function() {
        function Tensor2(shape, dtype, dataId, id) {
          this.kept = false;
          this.isDisposedInternal = false;
          this.shape = shape.slice();
          this.dtype = dtype || "float32";
          this.size = sizeFromShape(shape);
          this.strides = computeStrides(shape);
          this.dataId = dataId;
          this.id = id;
          this.rankType = this.rank < 5 ? this.rank.toString() : "higher";
        }
        Object.defineProperty(Tensor2.prototype, "rank", {
          get: function() {
            return this.shape.length;
          },
          enumerable: false,
          configurable: true
        });
        Tensor2.prototype.buffer = function() {
          return __awaiter(this, void 0, void 0, function() {
            var vals;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  return [4, this.data()];
                case 1:
                  vals = _b.sent();
                  return [2, opHandler$1.buffer(this.shape, this.dtype, vals)];
              }
            });
          });
        };
        Tensor2.prototype.bufferSync = function() {
          return opHandler$1.buffer(this.shape, this.dtype, this.dataSync());
        };
        Tensor2.prototype.array = function() {
          return __awaiter(this, void 0, void 0, function() {
            var vals;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  return [4, this.data()];
                case 1:
                  vals = _b.sent();
                  return [2, toNestedArray(this.shape, vals, this.dtype === "complex64")];
              }
            });
          });
        };
        Tensor2.prototype.arraySync = function() {
          return toNestedArray(this.shape, this.dataSync(), this.dtype === "complex64");
        };
        Tensor2.prototype.data = function() {
          return __awaiter(this, void 0, void 0, function() {
            var data, bytes;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  this.throwIfDisposed();
                  data = trackerFn().read(this.dataId);
                  if (!(this.dtype === "string")) return [3, 2];
                  return [4, data];
                case 1:
                  bytes = _b.sent();
                  try {
                    return [2, bytes.map(function(b) {
                      return decodeString(b);
                    })];
                  } catch (_a) {
                    throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");
                  }
                  _b.label = 2;
                case 2:
                  return [2, data];
              }
            });
          });
        };
        Tensor2.prototype.dataToGPU = function(options) {
          this.throwIfDisposed();
          return trackerFn().readToGPU(this.dataId, options);
        };
        Tensor2.prototype.dataSync = function() {
          this.throwIfDisposed();
          var data = trackerFn().readSync(this.dataId);
          if (this.dtype === "string") {
            try {
              return data.map(function(b) {
                return decodeString(b);
              });
            } catch (_a) {
              throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");
            }
          }
          return data;
        };
        Tensor2.prototype.bytes = function() {
          return __awaiter(this, void 0, void 0, function() {
            var data;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  this.throwIfDisposed();
                  return [4, trackerFn().read(this.dataId)];
                case 1:
                  data = _b.sent();
                  if (this.dtype === "string") {
                    return [2, data];
                  } else {
                    return [2, new Uint8Array(data.buffer)];
                  }
              }
            });
          });
        };
        Tensor2.prototype.dispose = function() {
          if (this.isDisposed) {
            return;
          }
          if (this.kerasMask) {
            this.kerasMask.dispose();
          }
          trackerFn().disposeTensor(this);
          this.isDisposedInternal = true;
        };
        Object.defineProperty(Tensor2.prototype, "isDisposed", {
          get: function() {
            return this.isDisposedInternal;
          },
          enumerable: false,
          configurable: true
        });
        Tensor2.prototype.throwIfDisposed = function() {
          if (this.isDisposed) {
            throw new Error("Tensor is disposed.");
          }
        };
        Tensor2.prototype.print = function(verbose) {
          if (verbose === void 0) {
            verbose = false;
          }
          return opHandler$1.print(this, verbose);
        };
        Tensor2.prototype.clone = function() {
          this.throwIfDisposed();
          return opHandler$1.clone(this);
        };
        Tensor2.prototype.toString = function(verbose) {
          if (verbose === void 0) {
            verbose = false;
          }
          var vals = this.dataSync();
          return tensorToString(vals, this.shape, this.dtype, verbose);
        };
        Tensor2.prototype.cast = function(dtype) {
          this.throwIfDisposed();
          return opHandler$1.cast(this, dtype);
        };
        Tensor2.prototype.variable = function(trainable, name, dtype) {
          if (trainable === void 0) {
            trainable = true;
          }
          this.throwIfDisposed();
          return trackerFn().makeVariable(this, trainable, name, dtype);
        };
        return Tensor2;
      }()
    );
    Object.defineProperty(Tensor, Symbol.hasInstance, {
      value: function(instance) {
        return !!instance && instance.data != null && instance.dataSync != null && instance.throwIfDisposed != null;
      }
    });
    function getGlobalTensorClass() {
      return getGlobal("Tensor", function() {
        return Tensor;
      });
    }
    getGlobalTensorClass();
    var Variable = (
      /** @class */
      function(_super) {
        __extends(Variable2, _super);
        function Variable2(initialValue, trainable, name, tensorId) {
          var _this = _super.call(this, initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId) || this;
          _this.trainable = trainable;
          _this.name = name;
          return _this;
        }
        Variable2.prototype.assign = function(newValue) {
          if (newValue.dtype !== this.dtype) {
            throw new Error("dtype of the new value (".concat(newValue.dtype, ") and ") + "previous value (".concat(this.dtype, ") must match"));
          }
          if (!arraysEqual(newValue.shape, this.shape)) {
            throw new Error("shape of the new value (".concat(newValue.shape, ") and ") + "previous value (".concat(this.shape, ") must match"));
          }
          trackerFn().disposeTensor(this);
          this.dataId = newValue.dataId;
          trackerFn().incRef(
            this,
            null
            /* backend */
          );
        };
        Variable2.prototype.dispose = function() {
          trackerFn().disposeVariable(this);
          this.isDisposedInternal = true;
        };
        return Variable2;
      }(Tensor)
    );
    Object.defineProperty(Variable, Symbol.hasInstance, {
      value: function(instance) {
        return instance instanceof Tensor && instance.assign != null && instance.assign instanceof Function;
      }
    });
    exports2.Rank = void 0;
    (function(Rank) {
      Rank["R0"] = "R0";
      Rank["R1"] = "R1";
      Rank["R2"] = "R2";
      Rank["R3"] = "R3";
      Rank["R4"] = "R4";
      Rank["R5"] = "R5";
      Rank["R6"] = "R6";
    })(exports2.Rank || (exports2.Rank = {}));
    var UpcastInt32AndMap;
    (function(UpcastInt32AndMap2) {
      UpcastInt32AndMap2["float32"] = "float32";
      UpcastInt32AndMap2["int32"] = "int32";
      UpcastInt32AndMap2["bool"] = "int32";
      UpcastInt32AndMap2["complex64"] = "complex64";
    })(UpcastInt32AndMap || (UpcastInt32AndMap = {}));
    var UpcastBoolAndMap;
    (function(UpcastBoolAndMap2) {
      UpcastBoolAndMap2["float32"] = "float32";
      UpcastBoolAndMap2["int32"] = "int32";
      UpcastBoolAndMap2["bool"] = "bool";
      UpcastBoolAndMap2["complex64"] = "complex64";
    })(UpcastBoolAndMap || (UpcastBoolAndMap = {}));
    var UpcastFloat32AndMap;
    (function(UpcastFloat32AndMap2) {
      UpcastFloat32AndMap2["float32"] = "float32";
      UpcastFloat32AndMap2["int32"] = "float32";
      UpcastFloat32AndMap2["bool"] = "float32";
      UpcastFloat32AndMap2["complex64"] = "complex64";
    })(UpcastFloat32AndMap || (UpcastFloat32AndMap = {}));
    var UpcastComplex64AndMap;
    (function(UpcastComplex64AndMap2) {
      UpcastComplex64AndMap2["float32"] = "complex64";
      UpcastComplex64AndMap2["int32"] = "complex64";
      UpcastComplex64AndMap2["bool"] = "complex64";
      UpcastComplex64AndMap2["complex64"] = "complex64";
    })(UpcastComplex64AndMap || (UpcastComplex64AndMap = {}));
    var upcastTypeMap = {
      "float32": UpcastFloat32AndMap,
      "int32": UpcastInt32AndMap,
      "bool": UpcastBoolAndMap,
      "complex64": UpcastComplex64AndMap
    };
    function upcastType(typeA, typeB) {
      if (typeA === "string" || typeB === "string") {
        if (typeA === "string" && typeB === "string") {
          return "string";
        }
        throw new Error("Can not upcast ".concat(typeA, " with ").concat(typeB));
      }
      return upcastTypeMap[typeA][typeB];
    }
    function sumOutType(type) {
      return upcastType(type, "int32");
    }
    function isWebGLData(values) {
      return values != null && typeof values === "object" && "texture" in values && values.texture instanceof WebGLTexture;
    }
    function isWebGPUData(values) {
      return typeof GPUBuffer !== "undefined" && values != null && typeof values === "object" && "buffer" in values && values.buffer instanceof GPUBuffer;
    }
    function makeTypesMatch(a, b) {
      if (a.dtype === b.dtype) {
        return [a, b];
      }
      var dtype = upcastType(a.dtype, b.dtype);
      return [a.cast(dtype), b.cast(dtype)];
    }
    function assertTypesMatch(a, b) {
      assert(a.dtype === b.dtype, function() {
        return "The dtypes of the first(".concat(a.dtype, ") and") + " second(".concat(b.dtype, ") input must match");
      });
    }
    function isTensorInList(tensor2, tensorList) {
      return tensorList.some(function(x) {
        return x.id === tensor2.id;
      });
    }
    function getTensorsInContainer(result) {
      var list = [];
      var seen = /* @__PURE__ */ new Set();
      walkTensorContainer(result, list, seen);
      return list;
    }
    function walkTensorContainer(container, list, seen) {
      if (container == null) {
        return;
      }
      if (container instanceof Tensor) {
        list.push(container);
        return;
      }
      if (!isIterable(container)) {
        return;
      }
      var iterable = container;
      for (var k in iterable) {
        var val = iterable[k];
        if (!seen.has(val)) {
          seen.add(val);
          walkTensorContainer(val, list, seen);
        }
      }
    }
    function isIterable(obj) {
      return Array.isArray(obj) || typeof obj === "object";
    }
    var tensor_util = {
      __proto__: null,
      assertTypesMatch,
      getTensorsInContainer,
      isTensorInList,
      makeTypesMatch
    };
    function isRegisteredKernelInvocation(kernelInvocation) {
      return kernelInvocation.kernelName != null;
    }
    var EngineState = (
      /** @class */
      function() {
        function EngineState2() {
          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 = /* @__PURE__ */ new WeakMap();
          this.profiling = false;
          this.activeProfile = {
            newBytes: 0,
            newTensors: 0,
            peakBytes: 0,
            kernels: [],
            result: null,
            get kernelNames() {
              return Array.from(new Set(this.kernels.map(function(k) {
                return k.name;
              })));
            }
          };
        }
        EngineState2.prototype.dispose = function() {
          for (var variableName in this.registeredVariables) {
            this.registeredVariables[variableName].dispose();
          }
        };
        return EngineState2;
      }()
    );
    var Engine = (
      /** @class */
      function() {
        function Engine2(ENV2) {
          this.ENV = ENV2;
          this.registry = {};
          this.registryFactory = {};
          this.pendingBackendInitId = 0;
          this.state = new EngineState();
        }
        Engine2.prototype.ready = function() {
          return __awaiter(this, void 0, void 0, function() {
            var sortedBackends, i, backendName, success;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  if (this.pendingBackendInit != null) {
                    return [2, this.pendingBackendInit.then(function() {
                    })];
                  }
                  if (this.backendInstance != null) {
                    return [
                      2
                      /*return*/
                    ];
                  }
                  sortedBackends = this.getSortedBackends();
                  i = 0;
                  _a.label = 1;
                case 1:
                  if (!(i < sortedBackends.length)) return [3, 5];
                  backendName = sortedBackends[i];
                  return [4, this.initializeBackend(backendName).success];
                case 2:
                  success = _a.sent();
                  if (!success) return [3, 4];
                  return [4, this.setBackend(backendName)];
                case 3:
                  _a.sent();
                  return [
                    2
                    /*return*/
                  ];
                case 4:
                  i++;
                  return [3, 1];
                case 5:
                  throw new Error("Could not initialize any backends, all backend initializations failed.");
              }
            });
          });
        };
        Object.defineProperty(Engine2.prototype, "backend", {
          get: function() {
            if (this.pendingBackendInit != null) {
              throw new Error("Backend '".concat(this.backendName, "' has not yet been initialized. Make ") + "sure to await tf.ready() or await tf.setBackend() before calling other methods");
            }
            if (this.backendInstance == null) {
              var _a = this.initializeBackendsAndReturnBest(), name = _a.name, asyncInit = _a.asyncInit;
              if (asyncInit) {
                throw new Error("The highest priority backend '".concat(name, "' has not yet been ") + "initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods");
              }
              this.setBackend(name);
            }
            return this.backendInstance;
          },
          enumerable: false,
          configurable: true
        });
        Engine2.prototype.backendNames = function() {
          return Object.keys(this.registryFactory);
        };
        Engine2.prototype.findBackend = function(backendName) {
          if (!(backendName in this.registry)) {
            if (backendName in this.registryFactory) {
              var asyncInit = this.initializeBackend(backendName).asyncInit;
              if (asyncInit) {
                return null;
              }
            } else {
              return null;
            }
          }
          return this.registry[backendName];
        };
        Engine2.prototype.findBackendFactory = function(backendName) {
          if (!(backendName in this.registryFactory)) {
            return null;
          }
          return this.registryFactory[backendName].factory;
        };
        Engine2.prototype.registerBackend = function(backendName, factory, priority) {
          if (priority === void 0) {
            priority = 1;
          }
          if (backendName in this.registryFactory) {
            warn("".concat(backendName, " backend was already registered. ") + "Reusing existing backend factory.");
            return false;
          }
          this.registryFactory[backendName] = { factory, priority };
          return true;
        };
        Engine2.prototype.setBackend = function(backendName) {
          return __awaiter(this, void 0, void 0, function() {
            var _a, success, asyncInit, result, _b;
            return __generator(this, function(_c) {
              switch (_c.label) {
                case 0:
                  if (this.registryFactory[backendName] == null) {
                    throw new Error("Backend name '".concat(backendName, "' not found in registry"));
                  }
                  this.backendName = backendName;
                  if (!(this.registry[backendName] == null)) return [3, 4];
                  this.backendInstance = null;
                  _a = this.initializeBackend(backendName), success = _a.success, asyncInit = _a.asyncInit;
                  if (!asyncInit) return [3, 2];
                  return [4, success];
                case 1:
                  _b = _c.sent();
                  return [3, 3];
                case 2:
                  _b = success;
                  _c.label = 3;
                case 3:
                  result = _b;
                  if (!result) {
                    return [2, false];
                  }
                  _c.label = 4;
                case 4:
                  this.backendInstance = this.registry[backendName];
                  this.setupRegisteredKernels();
                  this.profiler = new Profiler(this.backendInstance);
                  return [2, true];
              }
            });
          });
        };
        Engine2.prototype.setupRegisteredKernels = function() {
          var _this = this;
          var kernels = getKernelsForBackend(this.backendName);
          kernels.forEach(function(kernel) {
            if (kernel.setupFunc != null) {
              kernel.setupFunc(_this.backendInstance);
            }
          });
        };
        Engine2.prototype.disposeRegisteredKernels = function(backendName) {
          var _this = this;
          var kernels = getKernelsForBackend(backendName);
          kernels.forEach(function(kernel) {
            if (kernel.disposeFunc != null) {
              kernel.disposeFunc(_this.registry[backendName]);
            }
          });
        };
        Engine2.prototype.initializeBackend = function(backendName) {
          var _this = this;
          var registryFactoryEntry = this.registryFactory[backendName];
          if (registryFactoryEntry == null) {
            throw new Error("Cannot initialize backend ".concat(backendName, ", no registration found."));
          }
          try {
            var backend2 = registryFactoryEntry.factory();
            if (backend2 && !(backend2 instanceof KernelBackend) && typeof backend2.then === "function") {
              var promiseId_1 = ++this.pendingBackendInitId;
              var success = backend2.then(function(backendInstance) {
                if (promiseId_1 < _this.pendingBackendInitId) {
                  return false;
                }
                _this.registry[backendName] = backendInstance;
                _this.pendingBackendInit = null;
                return true;
              }).catch(function(err) {
                if (promiseId_1 < _this.pendingBackendInitId) {
                  return false;
                }
                _this.pendingBackendInit = null;
                warn("Initialization of backend ".concat(backendName, " failed"));
                warn(err.stack || err.message);
                return false;
              });
              this.pendingBackendInit = success;
              return { success, asyncInit: true };
            } else {
              this.registry[backendName] = backend2;
              return { success: true, asyncInit: false };
            }
          } catch (err) {
            warn("Initialization of backend ".concat(backendName, " failed"));
            warn(err.stack || err.message);
            return { success: false, asyncInit: false };
          }
        };
        Engine2.prototype.removeBackend = function(backendName) {
          if (!(backendName in this.registryFactory)) {
            throw new Error("".concat(backendName, " backend not found in registry"));
          }
          if (this.backendName === backendName && this.pendingBackendInit != null) {
            this.pendingBackendInitId++;
          }
          if (backendName in this.registry) {
            this.disposeRegisteredKernels(backendName);
            this.registry[backendName].dispose();
            delete this.registry[backendName];
          }
          delete this.registryFactory[backendName];
          if (this.backendName === backendName) {
            this.pendingBackendInit = null;
            this.backendName = null;
            this.backendInstance = null;
          }
        };
        Engine2.prototype.getSortedBackends = function() {
          var _this = this;
          if (Object.keys(this.registryFactory).length === 0) {
            throw new Error("No backend found in registry.");
          }
          return Object.keys(this.registryFactory).sort(function(a, b) {
            return _this.registryFactory[b].priority - _this.registryFactory[a].priority;
          });
        };
        Engine2.prototype.initializeBackendsAndReturnBest = function() {
          var sortedBackends = this.getSortedBackends();
          for (var i = 0; i < sortedBackends.length; i++) {
            var backendName = sortedBackends[i];
            var _a = this.initializeBackend(backendName), success = _a.success, asyncInit = _a.asyncInit;
            if (asyncInit || success) {
              return { name: backendName, asyncInit };
            }
          }
          throw new Error("Could not initialize any backends, all backend initializations failed.");
        };
        Engine2.prototype.moveData = function(backend2, dataId) {
          var info = this.state.tensorInfo.get(dataId);
          var srcBackend = info.backend;
          var values = this.readSync(dataId);
          var refCount = srcBackend.refCount(dataId);
          srcBackend.disposeData(dataId, true);
          info.backend = backend2;
          backend2.move(dataId, values, info.shape, info.dtype, refCount);
          if (this.shouldCheckForMemLeaks()) {
            this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;
          }
        };
        Engine2.prototype.tidy = function(nameOrFn, fn) {
          var _this = this;
          var name = null;
          if (fn == null) {
            if (typeof nameOrFn !== "function") {
              throw new Error("Please provide a function to tidy()");
            }
            fn = nameOrFn;
          } else {
            if (typeof nameOrFn !== "string" && !(nameOrFn instanceof String)) {
              throw new Error("When calling with two arguments, the first argument to tidy() must be a string");
            }
            if (typeof fn !== "function") {
              throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");
            }
            name = nameOrFn;
          }
          var result;
          return this.scopedRun(function() {
            return _this.startScope(name);
          }, function() {
            return _this.endScope(result);
          }, function() {
            result = fn();
            if (result instanceof Promise) {
              console.error("Cannot return a Promise inside of tidy.");
            }
            return result;
          });
        };
        Engine2.prototype.scopedRun = function(start, end, f) {
          start();
          try {
            var res = f();
            end();
            return res;
          } catch (ex) {
            end();
            throw ex;
          }
        };
        Engine2.prototype.nextTensorId = function() {
          return Engine2.nextTensorId++;
        };
        Engine2.prototype.nextVariableId = function() {
          return Engine2.nextVariableId++;
        };
        Engine2.prototype.clone = function(x) {
          var y = ENGINE.runKernel(Identity, { x });
          var inputs = { x };
          var grad2 = function(dy) {
            return {
              x: function() {
                var dtype = "float32";
                var gradInputs = { x: dy };
                var attrs = { dtype };
                return ENGINE.runKernel(
                  Cast,
                  gradInputs,
                  // tslint:disable-next-line: no-unnecessary-type-assertion
                  attrs
                );
              }
            };
          };
          var saved = [];
          this.addTapeNode(this.state.activeScope.name, inputs, [y], grad2, saved, {});
          return y;
        };
        Engine2.prototype.runKernel = function(kernelName, inputs, attrs) {
          if (this.backendName == null) {
            this.backend;
          }
          var hasKernel = getKernel(kernelName, this.backendName) != null;
          if (!hasKernel) {
            throw new Error("Kernel '".concat(kernelName, "' not registered for backend '").concat(this.backendName, "'"));
          }
          return this.runKernelFunc({ kernelName, inputs, attrs });
        };
        Engine2.prototype.shouldCheckForMemLeaks = function() {
          return this.ENV.getBool("IS_TEST");
        };
        Engine2.prototype.checkKernelForMemLeak = function(kernelName, numDataIdsBefore, outInfos) {
          var numDataIdsAfter = this.backend.numDataIds();
          var numOutputDataIds = 0;
          outInfos.forEach(function(info) {
            numOutputDataIds += info.dtype === "complex64" ? 3 : 1;
          });
          var numMoves = this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1];
          var dataIdsLeaked = numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves;
          if (dataIdsLeaked > 0) {
            throw new Error("Backend '".concat(this.backendName, "' has an internal memory leak ") + "(".concat(dataIdsLeaked, " data ids) after running '").concat(kernelName, "'"));
          }
        };
        Engine2.prototype.runKernelFunc = function(kernelParams) {
          var _this = this;
          var outputs;
          var saved = [];
          var isTapeOn = this.isTapeOn();
          var startingBytecount = this.state.numBytes;
          var startingNumTensors = this.state.numTensors;
          if (this.shouldCheckForMemLeaks()) {
            this.state.numDataMovesStack.push(0);
          }
          var kernelFunc;
          if (this.backendName == null) {
            this.backend;
          }
          var out;
          var kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ? kernelParams.kernelName : this.state.activeScope != null ? this.state.activeScope.name : "";
          if (isRegisteredKernelInvocation(kernelParams)) {
            var kernelName_1 = kernelParams.kernelName, inputs_1 = kernelParams.inputs, attrs_1 = kernelParams.attrs;
            if (this.backendName == null) {
              this.backend;
            }
            var kernel_1 = getKernel(kernelName_1, this.backendName);
            assert(kernel_1 != null, function() {
              return "Cannot find registered kernel '".concat(kernelName_1, "' for backend '").concat(_this.backendName, "'");
            });
            kernelFunc = function() {
              var numDataIdsBefore = _this.backend.numDataIds();
              out = kernel_1.kernelFunc({ inputs: inputs_1, attrs: attrs_1, backend: _this.backend });
              var outInfos = Array.isArray(out) ? out : [out];
              if (_this.shouldCheckForMemLeaks()) {
                _this.checkKernelForMemLeak(kernelName_1, numDataIdsBefore, outInfos);
              }
              var outTensors = outInfos.map(function(outInfo) {
                if (outInfo.rank != null) {
                  return outInfo;
                }
                return _this.makeTensorFromTensorInfo(outInfo);
              });
              if (isTapeOn) {
                var tensorsToSave = _this.getTensorsForGradient(kernelName_1, inputs_1, outTensors);
                saved = _this.saveTensorsForBackwardMode(tensorsToSave);
              }
              return outTensors;
            };
          } else {
            var forwardFunc_1 = kernelParams.forwardFunc;
            var saveFunc_1 = function(tensors) {
              if (!isTapeOn) {
                return;
              }
              saved = tensors.map(function(tensor2) {
                return _this.keep(_this.clone(tensor2));
              });
            };
            kernelFunc = function() {
              var numDataIdsBefore = _this.backend.numDataIds();
              out = _this.tidy(function() {
                return forwardFunc_1(_this.backend, saveFunc_1);
              });
              var outs = Array.isArray(out) ? out : [out];
              if (_this.shouldCheckForMemLeaks()) {
                _this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs);
              }
              return outs;
            };
          }
          var inputs = kernelParams.inputs, attrs = kernelParams.attrs;
          var backwardsFunc = isRegisteredKernelInvocation(kernelParams) ? null : kernelParams.backwardsFunc;
          var kernelProfile;
          this.scopedRun(
            // Stop recording to a tape when running a kernel.
            function() {
              return _this.state.kernelDepth++;
            },
            function() {
              return _this.state.kernelDepth--;
            },
            function() {
              if (!_this.ENV.getBool("DEBUG") && !_this.state.profiling) {
                outputs = kernelFunc();
              } else {
                kernelProfile = _this.profiler.profileKernel(kernelOrScopeName, inputs, function() {
                  return kernelFunc();
                });
                if (_this.ENV.getBool("DEBUG")) {
                  _this.profiler.logKernelProfile(kernelProfile);
                }
                outputs = kernelProfile.outputs;
              }
            }
          );
          if (isTapeOn) {
            this.addTapeNode(kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs);
          }
          if (this.state.profiling) {
            this.state.activeProfile.kernels.push({
              name: kernelOrScopeName,
              bytesAdded: this.state.numBytes - startingBytecount,
              totalBytesSnapshot: this.state.numBytes,
              tensorsAdded: this.state.numTensors - startingNumTensors,
              totalTensorsSnapshot: this.state.numTensors,
              inputShapes: Object.keys(inputs).map(function(key) {
                return inputs[key] != null ? inputs[key].shape : null;
              }),
              outputShapes: outputs.map(function(item) {
                return item.shape;
              }),
              kernelTimeMs: kernelProfile.timeMs,
              extraInfo: kernelProfile.extraInfo
            });
          }
          return Array.isArray(out) ? outputs : outputs[0];
        };
        Engine2.prototype.saveTensorsForBackwardMode = function(tensors) {
          var _this = this;
          var saved = tensors.map(function(tensor2) {
            return _this.keep(_this.clone(tensor2));
          });
          return saved;
        };
        Engine2.prototype.getTensorsForGradient = function(kernelName, inputs, outputs) {
          var gradConfig = getGradient(kernelName);
          if (gradConfig != null) {
            var inputsToSave = gradConfig.inputsToSave || [];
            var outputsToSave_1 = gradConfig.outputsToSave || [];
            var inputTensorsToSave = void 0;
            if (gradConfig.saveAllInputs) {
              assert(Array.isArray(inputs), function() {
                return "saveAllInputs is true, expected inputs to be an array.";
              });
              inputTensorsToSave = Object.keys(inputs).map(function(key) {
                return inputs[key];
              });
            } else {
              inputTensorsToSave = inputsToSave.map(function(inputName) {
                return inputs[inputName];
              });
            }
            var outputTensorsToSave = outputs.filter(function(_, i) {
              return outputsToSave_1[i];
            });
            return inputTensorsToSave.concat(outputTensorsToSave);
          }
          return [];
        };
        Engine2.prototype.makeTensor = function(values, shape, dtype, backend2) {
          if (values == null) {
            throw new Error("Values passed to engine.makeTensor() are null");
          }
          dtype = dtype || "float32";
          backend2 = backend2 || this.backend;
          var backendVals = values;
          if (dtype === "string" && isString(values[0])) {
            backendVals = values.map(function(d) {
              return encodeString(d);
            });
          }
          var dataId = backend2.write(backendVals, shape, dtype);
          var t = new Tensor(shape, dtype, dataId, this.nextTensorId());
          this.trackTensor(t, backend2);
          if (dtype === "string") {
            var info = this.state.tensorInfo.get(dataId);
            var newBytes = bytesFromStringArray(backendVals);
            this.state.numBytes += newBytes - info.bytes;
            info.bytes = newBytes;
          }
          return t;
        };
        Engine2.prototype.makeTensorFromDataId = function(dataId, shape, dtype, backend2) {
          dtype = dtype || "float32";
          var tensorInfo = { dataId, shape, dtype };
          return this.makeTensorFromTensorInfo(tensorInfo, backend2);
        };
        Engine2.prototype.makeTensorFromTensorInfo = function(tensorInfo, backend2) {
          var dataId = tensorInfo.dataId, shape = tensorInfo.shape, dtype = tensorInfo.dtype;
          var t = new Tensor(shape, dtype, dataId, this.nextTensorId());
          this.trackTensor(t, backend2);
          return t;
        };
        Engine2.prototype.makeVariable = function(initialValue, trainable, name, dtype) {
          if (trainable === void 0) {
            trainable = true;
          }
          name = name || this.nextVariableId().toString();
          if (dtype != null && dtype !== initialValue.dtype) {
            initialValue = initialValue.cast(dtype);
          }
          var v = new Variable(initialValue, trainable, name, this.nextTensorId());
          if (this.state.registeredVariables[v.name] != null) {
            throw new Error("Variable with name ".concat(v.name, " was already registered"));
          }
          this.state.registeredVariables[v.name] = v;
          this.incRef(v, this.backend);
          return v;
        };
        Engine2.prototype.trackTensor = function(a, backend2) {
          this.state.numTensors++;
          if (a.dtype === "string") {
            this.state.numStringTensors++;
          }
          var bytes = 0;
          if (a.dtype !== "complex64" && a.dtype !== "string") {
            bytes = a.size * bytesPerElement(a.dtype);
          }
          this.state.numBytes += bytes;
          if (!this.state.tensorInfo.has(a.dataId)) {
            this.state.numDataBuffers++;
            this.state.tensorInfo.set(a.dataId, {
              backend: backend2 || this.backend,
              dtype: a.dtype,
              shape: a.shape,
              bytes
            });
          }
          if (!(a instanceof Variable)) {
            this.track(a);
          }
        };
        Engine2.prototype.incRef = function(a, backend2) {
          this.trackTensor(a, backend2);
          this.backend.incRef(a.dataId);
        };
        Engine2.prototype.removeDataId = function(dataId, backend2) {
          if (this.state.tensorInfo.has(dataId) && this.state.tensorInfo.get(dataId).backend === backend2) {
            this.state.tensorInfo.delete(dataId);
            this.state.numDataBuffers--;
          }
        };
        Engine2.prototype.disposeTensor = function(a) {
          if (!this.state.tensorInfo.has(a.dataId)) {
            return;
          }
          var info = this.state.tensorInfo.get(a.dataId);
          this.state.numTensors--;
          if (a.dtype === "string") {
            this.state.numStringTensors--;
            this.state.numBytes -= info.bytes;
          }
          if (a.dtype !== "complex64" && a.dtype !== "string") {
            var bytes = a.size * bytesPerElement(a.dtype);
            this.state.numBytes -= bytes;
          }
          if (info.backend.disposeData(a.dataId)) {
            this.removeDataId(a.dataId, info.backend);
          }
        };
        Engine2.prototype.disposeVariables = function() {
          for (var varName in this.state.registeredVariables) {
            var v = this.state.registeredVariables[varName];
            this.disposeVariable(v);
          }
        };
        Engine2.prototype.disposeVariable = function(v) {
          this.disposeTensor(v);
          if (this.state.registeredVariables[v.name] != null) {
            delete this.state.registeredVariables[v.name];
          }
        };
        Engine2.prototype.memory = function() {
          var info = this.backend.memory();
          info.numTensors = this.state.numTensors;
          info.numDataBuffers = this.state.numDataBuffers;
          info.numBytes = this.state.numBytes;
          if (this.state.numStringTensors > 0) {
            info.unreliable = true;
            if (info.reasons == null) {
              info.reasons = [];
            }
            info.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)");
          }
          return info;
        };
        Engine2.prototype.profile = function(query) {
          return __awaiter(this, void 0, void 0, function() {
            var startBytes, startNumTensors, _a, _b, _c, kernel, _d, _e, e_1_1;
            var e_1, _f;
            return __generator(this, function(_g) {
              switch (_g.label) {
                case 0:
                  this.state.profiling = true;
                  startBytes = this.state.numBytes;
                  startNumTensors = this.state.numTensors;
                  this.state.activeProfile.kernels = [];
                  _a = this.state.activeProfile;
                  return [4, query()];
                case 1:
                  _a.result = _g.sent();
                  this.state.profiling = false;
                  this.state.activeProfile.peakBytes = Math.max.apply(Math, __spreadArray([], __read(this.state.activeProfile.kernels.map(function(d) {
                    return d.totalBytesSnapshot;
                  })), false));
                  this.state.activeProfile.newBytes = this.state.numBytes - startBytes;
                  this.state.activeProfile.newTensors = this.state.numTensors - startNumTensors;
                  _g.label = 2;
                case 2:
                  _g.trys.push([2, 8, 9, 10]);
                  _b = __values(this.state.activeProfile.kernels), _c = _b.next();
                  _g.label = 3;
                case 3:
                  if (!!_c.done) return [3, 7];
                  kernel = _c.value;
                  _d = kernel;
                  return [4, kernel.kernelTimeMs];
                case 4:
                  _d.kernelTimeMs = _g.sent();
                  _e = kernel;
                  return [4, kernel.extraInfo];
                case 5:
                  _e.extraInfo = _g.sent();
                  _g.label = 6;
                case 6:
                  _c = _b.next();
                  return [3, 3];
                case 7:
                  return [3, 10];
                case 8:
                  e_1_1 = _g.sent();
                  e_1 = { error: e_1_1 };
                  return [3, 10];
                case 9:
                  try {
                    if (_c && !_c.done && (_f = _b.return)) _f.call(_b);
                  } finally {
                    if (e_1) throw e_1.error;
                  }
                  return [
                    7
                    /*endfinally*/
                  ];
                case 10:
                  return [2, this.state.activeProfile];
              }
            });
          });
        };
        Engine2.prototype.isTapeOn = function() {
          return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;
        };
        Engine2.prototype.addTapeNode = function(kernelName, inputs, outputs, gradientsFunc, saved, attrs) {
          var _this = this;
          var tapeNode = { id: this.state.nextTapeNodeId++, kernelName, inputs, outputs, saved };
          var gradConfig = getGradient(kernelName);
          if (gradConfig != null) {
            gradientsFunc = gradConfig.gradFunc;
          }
          if (gradientsFunc != null) {
            tapeNode.gradient = function(dys) {
              dys = dys.map(function(dy, i) {
                if (dy == null) {
                  var output = outputs[i];
                  var vals = makeZerosTypedArray(output.size, output.dtype);
                  return _this.makeTensor(vals, output.shape, output.dtype);
                }
                return dy;
              });
              return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs);
            };
          }
          this.state.activeTape.push(tapeNode);
        };
        Engine2.prototype.keep = function(result) {
          result.kept = true;
          return result;
        };
        Engine2.prototype.startTape = function() {
          if (this.state.gradientDepth === 0) {
            this.state.activeTape = [];
          }
          this.state.gradientDepth++;
        };
        Engine2.prototype.endTape = function() {
          this.state.gradientDepth--;
        };
        Engine2.prototype.startScope = function(name) {
          var scopeInfo = {
            track: [],
            name: "unnamed scope",
            id: this.state.nextScopeId++
          };
          if (name) {
            scopeInfo.name = name;
          }
          this.state.scopeStack.push(scopeInfo);
          this.state.activeScope = scopeInfo;
        };
        Engine2.prototype.endScope = function(result) {
          var _this = this;
          var tensorsToTrackInParent = getTensorsInContainer(result);
          var tensorsToTrackInParentSet = new Set(tensorsToTrackInParent.map(function(t) {
            return t.id;
          }));
          for (var i = 0; i < this.state.activeScope.track.length; i++) {
            var tensor2 = this.state.activeScope.track[i];
            if (!tensor2.kept && !tensorsToTrackInParentSet.has(tensor2.id)) {
              tensor2.dispose();
            }
          }
          var oldScope = this.state.scopeStack.pop();
          this.state.activeScope = this.state.scopeStack.length === 0 ? null : this.state.scopeStack[this.state.scopeStack.length - 1];
          tensorsToTrackInParent.forEach(function(tensor3) {
            if (!tensor3.kept && tensor3.scopeId === oldScope.id) {
              _this.track(tensor3);
            }
          });
        };
        Engine2.prototype.gradients = function(f, xs, dy, allowNoGradients) {
          var _this = this;
          if (allowNoGradients === void 0) {
            allowNoGradients = false;
          }
          assert(xs.length > 0, function() {
            return "gradients() received an empty list of xs.";
          });
          if (dy != null && dy.dtype !== "float32") {
            throw new Error("dy must have 'float32' dtype, but has '".concat(dy.dtype, "'"));
          }
          var y = this.scopedRun(function() {
            return _this.startTape();
          }, function() {
            return _this.endTape();
          }, function() {
            return _this.tidy("forward", f);
          });
          assert(y instanceof Tensor, function() {
            return "The result y returned by f() must be a tensor.";
          });
          var filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y);
          if (!allowNoGradients && filteredTape.length === 0 && xs.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", function() {
            var accumulatedGradientMap = {};
            accumulatedGradientMap[y.id] = dy == null ? ones$1(y.shape) : dy;
            backpropagateGradients(
              accumulatedGradientMap,
              filteredTape,
              // Pass the tidy function to avoid circular dep with `tape.ts`.
              function(f2) {
                return _this.tidy(f2);
              },
              // Pass an add function to avoide a circular dep with `tape.ts`.
              add$1
            );
            var grads2 = xs.map(function(x) {
              return accumulatedGradientMap[x.id];
            });
            if (_this.state.gradientDepth === 0) {
              _this.state.activeTape.forEach(function(node) {
                var e_2, _a;
                try {
                  for (var _b = __values(node.saved), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var tensor2 = _c.value;
                    tensor2.dispose();
                  }
                } catch (e_2_1) {
                  e_2 = { error: e_2_1 };
                } finally {
                  try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                  } finally {
                    if (e_2) throw e_2.error;
                  }
                }
              });
              _this.state.activeTape = null;
            }
            return { value: y, grads: grads2 };
          });
        };
        Engine2.prototype.customGrad = function(f) {
          var _this = this;
          assert(isFunction(f), function() {
            return "The f passed in customGrad(f) must be a function.";
          });
          return function() {
            var inputs = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              inputs[_i] = arguments[_i];
            }
            assert(inputs.every(function(t) {
              return t instanceof Tensor;
            }), function() {
              return "The args passed in customGrad(f)(x1, x2,...) must all be tensors";
            });
            var res;
            var inputMap = {};
            inputs.forEach(function(input, i) {
              inputMap[i] = input;
            });
            var forwardFunc = function(_, save) {
              res = f.apply(void 0, __spreadArray([], __read(__spreadArray(__spreadArray([], __read(inputs), false), [save], false)), false));
              assert(res.value instanceof Tensor, function() {
                return "The function f passed in customGrad(f) must return an object where `obj.value` is a tensor";
              });
              assert(isFunction(res.gradFunc), function() {
                return "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.";
              });
              return res.value;
            };
            var backwardsFunc = function(dy, saved) {
              var gradRes = res.gradFunc(dy, saved);
              var grads2 = Array.isArray(gradRes) ? gradRes : [gradRes];
              assert(grads2.length === inputs.length, function() {
                return "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(...).";
              });
              assert(grads2.every(function(t) {
                return t instanceof Tensor;
              }), function() {
                return "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.";
              });
              var gradMap = {};
              grads2.forEach(function(grad2, i) {
                gradMap[i] = function() {
                  return grad2;
                };
              });
              return gradMap;
            };
            return _this.runKernelFunc({
              forwardFunc,
              backwardsFunc,
              inputs: inputMap
            });
          };
        };
        Engine2.prototype.readSync = function(dataId) {
          var info = this.state.tensorInfo.get(dataId);
          return info.backend.readSync(dataId);
        };
        Engine2.prototype.read = function(dataId) {
          var info = this.state.tensorInfo.get(dataId);
          return info.backend.read(dataId);
        };
        Engine2.prototype.readToGPU = function(dataId, options) {
          var info = this.state.tensorInfo.get(dataId);
          return info.backend.readToGPU(dataId, options);
        };
        Engine2.prototype.time = function(query) {
          return __awaiter(this, void 0, void 0, function() {
            var start, timingInfo;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  start = now();
                  return [4, this.backend.time(query)];
                case 1:
                  timingInfo = _a.sent();
                  timingInfo.wallMs = now() - start;
                  return [2, timingInfo];
              }
            });
          });
        };
        Engine2.prototype.track = function(result) {
          if (this.state.activeScope != null) {
            result.scopeId = this.state.activeScope.id;
            this.state.activeScope.track.push(result);
          }
          return result;
        };
        Object.defineProperty(Engine2.prototype, "registeredVariables", {
          get: function() {
            return this.state.registeredVariables;
          },
          enumerable: false,
          configurable: true
        });
        Engine2.prototype.reset = function() {
          this.pendingBackendInitId++;
          this.state.dispose();
          this.ENV.reset();
          this.state = new EngineState();
          for (var backendName in this.registry) {
            this.disposeRegisteredKernels(backendName);
            this.registry[backendName].dispose();
            delete this.registry[backendName];
          }
          this.backendName = null;
          this.backendInstance = null;
          this.pendingBackendInit = null;
        };
        return Engine2;
      }()
    );
    Engine.nextTensorId = 0;
    Engine.nextVariableId = 0;
    function ones$1(shape) {
      var values = makeOnesTypedArray(sizeFromShape(shape), "float32");
      return ENGINE.makeTensor(values, shape, "float32");
    }
    function getOrMakeEngine() {
      var ns = getGlobalNamespace();
      if (ns._tfengine == null) {
        var environment = new Environment(ns);
        ns._tfengine = new Engine(environment);
      }
      setEnvironmentGlobal(ns._tfengine.ENV);
      setTensorTracker(function() {
        return ns._tfengine;
      });
      return ns._tfengine;
    }
    var ENGINE = getOrMakeEngine();
    function add$1(a, b) {
      var inputs = { a, b };
      return ENGINE.runKernel(Add, inputs);
    }
    function _isNavigatorDefined() {
      return typeof navigator !== "undefined" && navigator != null;
    }
    var isMobileMockValue;
    function mockIsMobile(value) {
      isMobileMockValue = value;
    }
    function isMobile(nav) {
      if (isMobileMockValue !== void 0) {
        return isMobileMockValue;
      }
      if (nav || _isNavigatorDefined()) {
        if (!nav) {
          nav = navigator;
        }
        if (nav.product === "ReactNative") {
          return true;
        }
        var a = nav.userAgent || nav.vendor || // tslint:disable-next-line:no-any
        (typeof window !== "undefined" ? window.opera : "");
        if (!a) {
          var navAny = nav;
          return navAny.userAgentData && navAny.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(a) || // tslint:disable-next-line:max-line-length
        /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(a.substr(0, 4));
      }
      return false;
    }
    function isBrowser() {
      return typeof window !== "undefined" && window.document != null || //@ts-ignore
      typeof WorkerGlobalScope !== "undefined";
    }
    var device_util = {
      __proto__: null,
      isBrowser,
      isMobile,
      mockIsMobile
    };
    var ENV = env();
    ENV.registerFlag("DEBUG", function() {
      return false;
    }, function(debugValue) {
      if (debugValue) {
        console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.");
      }
    });
    ENV.registerFlag("IS_BROWSER", function() {
      return isBrowser();
    });
    ENV.registerFlag("IS_NODE", function() {
      return typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined";
    });
    ENV.registerFlag("IS_CHROME", function() {
      return typeof navigator !== "undefined" && navigator != null && navigator.userAgent != null && /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
    });
    ENV.registerFlag("IS_SAFARI", function() {
      return typeof navigator !== "undefined" && navigator != null && navigator.userAgent != null && /Safari/.test(navigator.userAgent) && /Apple/.test(navigator.vendor);
    });
    ENV.registerFlag("PROD", function() {
      return false;
    });
    ENV.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY", function() {
      return ENV.getBool("DEBUG");
    });
    ENV.registerFlag("DEPRECATION_WARNINGS_ENABLED", function() {
      return true;
    });
    ENV.registerFlag("IS_TEST", function() {
      return false;
    });
    ENV.registerFlag("CHECK_COMPUTATION_FOR_ERRORS", function() {
      return ENV.getBool("DEBUG");
    });
    ENV.registerFlag("WRAP_TO_IMAGEBITMAP", function() {
      return false;
    });
    ENV.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU", function() {
      return false;
    });
    ENV.registerFlag("USE_SETTIMEOUTCUSTOM", function() {
      return false;
    });
    function inferShape(val, dtype) {
      var firstElem = val;
      if (isTypedArray(val)) {
        return dtype === "string" ? [] : [val.length];
      }
      if (isWebGLData(val)) {
        var usedChannels = val.channels || "RGBA";
        return [val.height, val.width * usedChannels.length];
      } else if (isWebGPUData(val)) {
        return [val.buffer.size / (dtype == null ? 4 : bytesPerElement(dtype))];
      }
      if (!Array.isArray(val)) {
        return [];
      }
      var shape = [];
      while (Array.isArray(firstElem) || isTypedArray(firstElem) && dtype !== "string") {
        shape.push(firstElem.length);
        firstElem = firstElem[0];
      }
      if (Array.isArray(val) && env().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")) {
        deepAssertShapeConsistency(val, shape, []);
      }
      return shape;
    }
    function deepAssertShapeConsistency(val, shape, indices) {
      indices = indices || [];
      if (!Array.isArray(val) && !isTypedArray(val)) {
        assert(shape.length === 0, function() {
          return "Element arr[".concat(indices.join("]["), "] is a primitive, ") + "but should be an array/TypedArray of ".concat(shape[0], " elements");
        });
        return;
      }
      assert(shape.length > 0, function() {
        return "Element arr[".concat(indices.join("]["), "] should be a primitive, ") + "but is an array of ".concat(val.length, " elements");
      });
      assert(val.length === shape[0], function() {
        return "Element arr[".concat(indices.join("]["), "] should have ").concat(shape[0], " ") + "elements, but has ".concat(val.length, " elements");
      });
      var subShape = shape.slice(1);
      for (var i = 0; i < val.length; ++i) {
        deepAssertShapeConsistency(val[i], subShape, indices.concat(i));
      }
    }
    function assertDtype(expectedDtype, actualDType, argName, functionName) {
      if (expectedDtype === "string_or_numeric") {
        return;
      }
      if (expectedDtype == null) {
        throw new Error("Expected dtype cannot be null.");
      }
      if (expectedDtype !== "numeric" && expectedDtype !== actualDType || expectedDtype === "numeric" && actualDType === "string") {
        throw new Error("Argument '".concat(argName, "' passed to '").concat(functionName, "' must ") + "be ".concat(expectedDtype, " tensor, but got ").concat(actualDType, " tensor"));
      }
    }
    function convertToTensor(x, argName, functionName, parseAsDtype) {
      if (parseAsDtype === void 0) {
        parseAsDtype = "numeric";
      }
      if (x instanceof getGlobalTensorClass()) {
        assertDtype(parseAsDtype, x.dtype, argName, functionName);
        return x;
      }
      var inferredDtype = inferDtype(x);
      if (inferredDtype !== "string" && ["bool", "int32", "float32"].indexOf(parseAsDtype) >= 0) {
        inferredDtype = parseAsDtype;
      }
      assertDtype(parseAsDtype, inferredDtype, argName, functionName);
      if (x == null || !isTypedArray(x) && !Array.isArray(x) && typeof x !== "number" && typeof x !== "boolean" && typeof x !== "string") {
        var type = x == null ? "null" : x.constructor.name;
        throw new Error("Argument '".concat(argName, "' passed to '").concat(functionName, "' must be a ") + "Tensor or TensorLike, but got '".concat(type, "'"));
      }
      var inferredShape = inferShape(x, inferredDtype);
      if (!isTypedArray(x) && !Array.isArray(x)) {
        x = [x];
      }
      var skipTypedArray = true;
      var values = inferredDtype !== "string" ? toTypedArray(x, inferredDtype) : flatten(x, [], skipTypedArray);
      return ENGINE.makeTensor(values, inferredShape, inferredDtype);
    }
    function convertToTensorArray(arg, argName, functionName, parseAsDtype) {
      if (parseAsDtype === void 0) {
        parseAsDtype = "numeric";
      }
      if (!Array.isArray(arg)) {
        throw new Error("Argument ".concat(argName, " passed to ").concat(functionName, " must be a ") + "`Tensor[]` or `TensorLike[]`");
      }
      var tensors = arg;
      return tensors.map(function(t, i) {
        return convertToTensor(t, "".concat(argName, "[").concat(i, "]"), functionName, parseAsDtype);
      });
    }
    var OP_SCOPE_SUFFIX = "__op";
    function op(f) {
      var keys = Object.keys(f);
      if (keys.length !== 1) {
        throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with " + "".concat(keys.length, " keys."));
      }
      var opName = keys[0];
      var fn = f[opName];
      if (opName.endsWith("_")) {
        opName = opName.substring(0, opName.length - 1);
      }
      opName = opName + OP_SCOPE_SUFFIX;
      var f2 = function() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        ENGINE.startScope(opName);
        try {
          var result = fn.apply(void 0, __spreadArray([], __read(args), false));
          if (isPromise(result)) {
            console.error("Cannot return a Promise inside of tidy.");
          }
          ENGINE.endScope(result);
          return result;
        } catch (ex) {
          ENGINE.endScope(null);
          throw ex;
        }
      };
      Object.defineProperty(f2, "name", { value: opName, configurable: true });
      return f2;
    }
    function complex_(real2, imag2) {
      var $real = convertToTensor(real2, "real", "complex");
      var $imag = convertToTensor(imag2, "imag", "complex");
      assertShapesMatch($real.shape, $imag.shape, "real and imag shapes, ".concat($real.shape, " and ").concat($imag.shape, ", ") + "must match in call to tf.complex().");
      var inputs = { real: $real, imag: $imag };
      return ENGINE.runKernel(Complex, inputs);
    }
    var complex = /* @__PURE__ */ op({ complex_ });
    function makeTensor(values, shape, inferredShape, dtype) {
      if (dtype == null) {
        dtype = inferDtype(values);
      } else if (dtype === "complex64") {
        throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");
      }
      if (isWebGPUData(values) || isWebGLData(values)) {
        if (dtype !== "float32" && dtype !== "int32") {
          throw new Error("Creating tensor from GPU data only supports " + "'float32'|'int32' dtype, while the dtype is ".concat(dtype, "."));
        }
        return ENGINE.backend.createTensorFromGPUData(values, shape || inferredShape, dtype);
      }
      if (!isTypedArray(values) && !Array.isArray(values) && typeof values !== "number" && typeof values !== "boolean" && typeof values !== "string") {
        throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");
      }
      if (shape != null) {
        assertNonNegativeIntegerDimensions(shape);
        var providedSize_1 = sizeFromShape(shape);
        var inferredSize_1 = sizeFromShape(inferredShape);
        assert(providedSize_1 === inferredSize_1, function() {
          return "Based on the provided shape, [".concat(shape, "], the tensor should have ") + "".concat(providedSize_1, " values but has ").concat(inferredSize_1);
        });
        for (var i = 0; i < inferredShape.length; ++i) {
          var inferred = inferredShape[i];
          var flatDimsDontMatch = i === inferredShape.length - 1 ? inferred !== sizeFromShape(shape.slice(i)) : true;
          assert(inferredShape[i] === shape[i] || !flatDimsDontMatch, function() {
            return "Error creating a new Tensor. Inferred shape " + "(".concat(inferredShape, ") does not match the provided ") + "shape (".concat(shape, "). ");
          });
        }
      }
      if (!isTypedArray(values) && !Array.isArray(values)) {
        values = [values];
      }
      shape = shape || inferredShape;
      values = dtype !== "string" ? toTypedArray(values, dtype) : flatten(values, [], true);
      return ENGINE.makeTensor(values, shape, dtype);
    }
    function tensor(values, shape, dtype) {
      var inferredShape = inferShape(values, dtype);
      return makeTensor(values, shape, inferredShape, dtype);
    }
    var DTYPE_VALUE_SIZE_MAP = {
      "float32": 4,
      "float16": 2,
      "int32": 4,
      "uint16": 2,
      "uint8": 1,
      "bool": 1,
      "complex64": 8
    };
    var CompositeArrayBuffer = (
      /** @class */
      function() {
        function CompositeArrayBuffer2(buffers) {
          this.shards = [];
          this.previousShardIndex = 0;
          if (buffers == null) {
            return;
          }
          if (!(buffers instanceof Array)) {
            buffers = [buffers];
          }
          buffers = buffers.map(function(bufferOrTypedArray) {
            if (isTypedArray(bufferOrTypedArray)) {
              return bufferOrTypedArray.buffer;
            }
            return bufferOrTypedArray;
          });
          if (buffers.length === 0) {
            return;
          }
          this.bufferUniformSize = buffers[0].byteLength;
          var start = 0;
          for (var i = 0; i < buffers.length; i++) {
            var buffer2 = buffers[i];
            if (i !== buffers.length - 1 && buffer2.byteLength !== this.bufferUniformSize) {
              this.bufferUniformSize = void 0;
            }
            var end = start + buffer2.byteLength;
            this.shards.push({ buffer: buffer2, start, end });
            start = end;
          }
          if (this.shards.length === 0) {
            this.byteLength = 0;
          }
          this.byteLength = this.shards[this.shards.length - 1].end;
        }
        CompositeArrayBuffer2.join = function(buffers) {
          return new CompositeArrayBuffer2(buffers).slice();
        };
        CompositeArrayBuffer2.prototype.slice = function(start, end) {
          if (start === void 0) {
            start = 0;
          }
          if (end === void 0) {
            end = this.byteLength;
          }
          if (this.shards.length === 0) {
            return new ArrayBuffer(0);
          }
          start = isNaN(Number(start)) ? 0 : start;
          end = isNaN(Number(end)) ? 0 : end;
          start = Math.max(0, start);
          end = Math.min(this.byteLength, end);
          if (end <= start) {
            return new ArrayBuffer(0);
          }
          var startShardIndex = this.findShardForByte(start);
          if (startShardIndex === -1) {
            throw new Error("Could not find start shard for byte ".concat(start));
          }
          var size = end - start;
          var outputBuffer = new ArrayBuffer(size);
          var outputArray = new Uint8Array(outputBuffer);
          var sliced = 0;
          for (var i = startShardIndex; i < this.shards.length; i++) {
            var shard = this.shards[i];
            var globalStart = start + sliced;
            var localStart = globalStart - shard.start;
            var outputStart = sliced;
            var globalEnd = Math.min(end, shard.end);
            var localEnd = globalEnd - shard.start;
            var outputSlice = new Uint8Array(shard.buffer, localStart, localEnd - localStart);
            outputArray.set(outputSlice, outputStart);
            sliced += outputSlice.length;
            if (end < shard.end) {
              break;
            }
          }
          return outputBuffer;
        };
        CompositeArrayBuffer2.prototype.findShardForByte = function(byteIndex) {
          if (this.shards.length === 0 || byteIndex < 0 || byteIndex >= this.byteLength) {
            return -1;
          }
          if (this.bufferUniformSize != null) {
            this.previousShardIndex = Math.floor(byteIndex / this.bufferUniformSize);
            return this.previousShardIndex;
          }
          function check(shard) {
            if (byteIndex < shard.start) {
              return -1;
            }
            if (byteIndex >= shard.end) {
              return 1;
            }
            return 0;
          }
          if (check(this.shards[this.previousShardIndex]) === 0) {
            return this.previousShardIndex;
          }
          var index = search(this.shards, check);
          if (index === -1) {
            return -1;
          }
          this.previousShardIndex = index;
          return this.previousShardIndex;
        };
        return CompositeArrayBuffer2;
      }()
    );
    function search(sortedArray, compare) {
      var min2 = 0;
      var max2 = sortedArray.length;
      while (min2 <= max2) {
        var middle = Math.floor((max2 - min2) / 2) + min2;
        var side = compare(sortedArray[middle]);
        if (side === 0) {
          return middle;
        } else if (side < 0) {
          max2 = middle;
        } else {
          min2 = middle + 1;
        }
      }
      return -1;
    }
    function enableProdMode() {
      env().set("PROD", true);
    }
    function enableDebugMode() {
      env().set("DEBUG", true);
    }
    function disableDeprecationWarnings() {
      env().set("DEPRECATION_WARNINGS_ENABLED", false);
      console.warn("TensorFlow.js deprecation warnings have been disabled.");
    }
    function deprecationWarn(msg) {
      if (env().getBool("DEPRECATION_WARNINGS_ENABLED")) {
        console.warn(msg + " You can disable deprecation warnings with tf.disableDeprecationWarnings().");
      }
    }
    function disposeVariables() {
      ENGINE.disposeVariables();
    }
    function engine() {
      return ENGINE;
    }
    function memory() {
      return ENGINE.memory();
    }
    function profile(f) {
      return ENGINE.profile(f);
    }
    function tidy(nameOrFn, fn) {
      return ENGINE.tidy(nameOrFn, fn);
    }
    function dispose(container) {
      var tensors = getTensorsInContainer(container);
      tensors.forEach(function(tensor2) {
        return tensor2.dispose();
      });
    }
    function keep(result) {
      return ENGINE.keep(result);
    }
    function time(f) {
      return ENGINE.time(f);
    }
    function setBackend(backendName) {
      return ENGINE.setBackend(backendName);
    }
    function ready() {
      return ENGINE.ready();
    }
    function getBackend() {
      return ENGINE.backendName;
    }
    function removeBackend(name) {
      ENGINE.removeBackend(name);
    }
    function findBackend(name) {
      return ENGINE.findBackend(name);
    }
    function findBackendFactory(name) {
      return ENGINE.findBackendFactory(name);
    }
    function registerBackend(name, factory, priority) {
      if (priority === void 0) {
        priority = 1;
      }
      return ENGINE.registerBackend(name, factory, priority);
    }
    function backend() {
      return ENGINE.backend;
    }
    function setPlatform(platformName, platform) {
      env().setPlatform(platformName, platform);
    }
    var NUM_BYTES_STRING_LENGTH = 4;
    function encodeWeights(tensors, group) {
      return __awaiter(this, void 0, void 0, function() {
        var specs, dataPromises, names, _loop_1, i, tensorValues;
        var _this = this;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              specs = [];
              dataPromises = [];
              names = Array.isArray(tensors) ? tensors.map(function(tensor2) {
                return tensor2.name;
              }) : Object.keys(tensors);
              _loop_1 = function(i2) {
                var name = names[i2];
                var t = Array.isArray(tensors) ? tensors[i2].tensor : tensors[name];
                if (t.dtype !== "float32" && t.dtype !== "int32" && t.dtype !== "bool" && t.dtype !== "string" && t.dtype !== "complex64") {
                  throw new Error("Unsupported dtype in weight '".concat(name, "': ").concat(t.dtype));
                }
                var spec = { name, shape: t.shape, dtype: t.dtype };
                if (t.dtype === "string") {
                  var utf8bytes = new Promise(function(resolve) {
                    return __awaiter(_this, void 0, void 0, function() {
                      var vals, totalNumBytes, bytes, offset, i_1, val, bytesOfLength;
                      return __generator(this, function(_a2) {
                        switch (_a2.label) {
                          case 0:
                            return [4, t.bytes()];
                          case 1:
                            vals = _a2.sent();
                            totalNumBytes = vals.reduce(function(p, c) {
                              return p + c.length;
                            }, 0) + NUM_BYTES_STRING_LENGTH * vals.length;
                            bytes = new Uint8Array(totalNumBytes);
                            offset = 0;
                            for (i_1 = 0; i_1 < vals.length; i_1++) {
                              val = vals[i_1];
                              bytesOfLength = new Uint8Array(new Uint32Array([val.length]).buffer);
                              bytes.set(bytesOfLength, offset);
                              offset += NUM_BYTES_STRING_LENGTH;
                              bytes.set(val, offset);
                              offset += val.length;
                            }
                            resolve(bytes);
                            return [
                              2
                              /*return*/
                            ];
                        }
                      });
                    });
                  });
                  dataPromises.push(utf8bytes);
                } else {
                  dataPromises.push(t.data());
                }
                if (group != null) {
                  spec.group = group;
                }
                specs.push(spec);
              };
              for (i = 0; i < names.length; ++i) {
                _loop_1(i);
              }
              return [4, Promise.all(dataPromises)];
            case 1:
              tensorValues = _a.sent();
              return [2, { data: concatenateTypedArrays(tensorValues), specs }];
          }
        });
      });
    }
    function decodeWeights(weightData, specs) {
      var e_1, _a;
      var compositeBuffer = new CompositeArrayBuffer(weightData);
      var out = {};
      var offset = 0;
      try {
        for (var specs_1 = __values(specs), specs_1_1 = specs_1.next(); !specs_1_1.done; specs_1_1 = specs_1.next()) {
          var spec = specs_1_1.value;
          var byteLength = getWeightBytelength(spec, function(start, end) {
            return compositeBuffer.slice(offset + start, offset + end);
          });
          out[spec.name] = decodeWeight(spec, compositeBuffer.slice(offset, offset + byteLength));
          offset += byteLength;
        }
      } catch (e_1_1) {
        e_1 = { error: e_1_1 };
      } finally {
        try {
          if (specs_1_1 && !specs_1_1.done && (_a = specs_1.return)) _a.call(specs_1);
        } finally {
          if (e_1) throw e_1.error;
        }
      }
      return out;
    }
    function getWeightBytelength(spec, slice2) {
      var size = sizeFromShape(spec.shape);
      var bytesPerValue;
      if ("quantization" in spec) {
        var quantization = spec.quantization;
        bytesPerValue = DTYPE_VALUE_SIZE_MAP[quantization.dtype];
      } else if (spec.dtype === "string") {
        var byteLength = 0;
        for (var i = 0; i < size; i++) {
          byteLength += NUM_BYTES_STRING_LENGTH + new Uint32Array(slice2(byteLength, byteLength + NUM_BYTES_STRING_LENGTH))[0];
        }
        return byteLength;
      } else {
        bytesPerValue = DTYPE_VALUE_SIZE_MAP[spec.dtype];
      }
      return size * bytesPerValue;
    }
    function getWeightBytelengthAsync(spec, slice2) {
      return __awaiter(this, void 0, void 0, function() {
        var size, bytesPerValue, quantization, byteLength, i, _a, _b, _c;
        return __generator(this, function(_d) {
          switch (_d.label) {
            case 0:
              size = sizeFromShape(spec.shape);
              if (!("quantization" in spec)) return [3, 1];
              quantization = spec.quantization;
              bytesPerValue = DTYPE_VALUE_SIZE_MAP[quantization.dtype];
              return [3, 7];
            case 1:
              if (!(spec.dtype === "string")) return [3, 6];
              byteLength = 0;
              i = 0;
              _d.label = 2;
            case 2:
              if (!(i < size)) return [3, 5];
              _a = byteLength;
              _b = NUM_BYTES_STRING_LENGTH;
              _c = Uint32Array.bind;
              return [4, slice2(byteLength, byteLength + NUM_BYTES_STRING_LENGTH)];
            case 3:
              byteLength = _a + (_b + new (_c.apply(Uint32Array, [void 0, _d.sent()]))()[0]);
              _d.label = 4;
            case 4:
              i++;
              return [3, 2];
            case 5:
              return [2, byteLength];
            case 6:
              bytesPerValue = DTYPE_VALUE_SIZE_MAP[spec.dtype];
              _d.label = 7;
            case 7:
              return [2, size * bytesPerValue];
          }
        });
      });
    }
    function decodeWeight(spec, byteBuffer) {
      var name = spec.name;
      var dtype = spec.dtype;
      var shape = spec.shape;
      var size = sizeFromShape(shape);
      var values;
      var offset = 0;
      if ("quantization" in spec) {
        var quantization = spec.quantization;
        if (quantization.dtype === "uint8" || quantization.dtype === "uint16") {
          if (!("min" in quantization && "scale" in quantization)) {
            throw new Error("Weight ".concat(spec.name, " with quantization ").concat(quantization.dtype, " ") + "doesn't have corresponding metadata min and scale.");
          }
        } else if (quantization.dtype === "float16") {
          if (dtype !== "float32") {
            throw new Error("Weight ".concat(spec.name, " is quantized with ").concat(quantization.dtype, " ") + "which only supports weights of type float32 not ".concat(dtype, "."));
          }
        } else {
          throw new Error("Weight ".concat(spec.name, " has unknown ") + "quantization dtype ".concat(quantization.dtype, ". ") + "Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.");
        }
        var quantizationSizeFactor = DTYPE_VALUE_SIZE_MAP[quantization.dtype];
        var quantizedArray = quantization.dtype === "uint8" ? new Uint8Array(byteBuffer) : new Uint16Array(byteBuffer);
        if (dtype === "float32") {
          if (quantization.dtype === "uint8" || quantization.dtype === "uint16") {
            values = new Float32Array(quantizedArray.length);
            for (var i = 0; i < quantizedArray.length; i++) {
              var v = quantizedArray[i];
              values[i] = v * quantization.scale + quantization.min;
            }
          } else if (quantization.dtype === "float16") {
            var float16Decode = getFloat16Decoder();
            values = float16Decode(quantizedArray);
          } else {
            throw new Error("Unsupported quantization type ".concat(quantization.dtype, " ") + "for weight type float32.");
          }
        } else if (dtype === "int32") {
          if (quantization.dtype !== "uint8" && quantization.dtype !== "uint16") {
            throw new Error("Unsupported quantization type ".concat(quantization.dtype, " ") + "for weight type int32.");
          }
          values = new Int32Array(quantizedArray.length);
          for (var i = 0; i < quantizedArray.length; i++) {
            var v = quantizedArray[i];
            values[i] = Math.round(v * quantization.scale + quantization.min);
          }
        } else {
          throw new Error("Unsupported dtype in weight '".concat(name, "': ").concat(dtype));
        }
        offset += size * quantizationSizeFactor;
      } else if (dtype === "string") {
        var size_1 = sizeFromShape(spec.shape);
        values = [];
        for (var i = 0; i < size_1; i++) {
          var byteLength = new Uint32Array(byteBuffer.slice(offset, offset + NUM_BYTES_STRING_LENGTH))[0];
          offset += NUM_BYTES_STRING_LENGTH;
          var bytes = new Uint8Array(byteBuffer.slice(offset, offset + byteLength));
          values.push(bytes);
          offset += byteLength;
        }
      } else {
        var dtypeFactor = DTYPE_VALUE_SIZE_MAP[dtype];
        if (dtype === "float32") {
          values = new Float32Array(byteBuffer);
        } else if (dtype === "int32") {
          values = new Int32Array(byteBuffer);
        } else if (dtype === "bool") {
          values = new Uint8Array(byteBuffer);
        } else if (dtype === "complex64") {
          values = new Float32Array(byteBuffer);
          var real2 = new Float32Array(values.length / 2);
          var image2 = new Float32Array(values.length / 2);
          for (var i = 0; i < real2.length; i++) {
            real2[i] = values[i * 2];
            image2[i] = values[i * 2 + 1];
          }
          var realTensor = tensor(real2, shape, "float32");
          var imageTensor = tensor(image2, shape, "float32");
          var complexTensor = complex(realTensor, imageTensor);
          realTensor.dispose();
          imageTensor.dispose();
          return complexTensor;
        } else {
          throw new Error("Unsupported dtype in weight '".concat(name, "': ").concat(dtype));
        }
        offset += size * dtypeFactor;
      }
      return tensor(values, shape, dtype);
    }
    function readToLength(reader, initialData, length) {
      return __awaiter(this, void 0, void 0, function() {
        var data, _a, done, value, missing, newData;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              data = new Uint8Array(initialData);
              _b.label = 1;
            case 1:
              if (!(data.byteLength < length)) return [3, 3];
              return [4, reader.read()];
            case 2:
              _a = _b.sent(), done = _a.done, value = _a.value;
              if (done && value == null) {
                missing = length - data.byteLength;
                throw new Error("Reader is done but ".concat(missing, " bytes are still expected"));
              }
              newData = new Uint8Array(data.length + value.byteLength);
              newData.set(data, 0);
              newData.set(new Uint8Array(value), data.length);
              data = newData;
              return [3, 1];
            case 3:
              return [2, data.buffer];
          }
        });
      });
    }
    function decodeWeightsStream(weightStream, specs) {
      return __awaiter(this, void 0, void 0, function() {
        var tensors, reader, data, specs_2, specs_2_1, spec, byteLength, tensorData, weightTensor, b, e_2_1;
        var e_2, _a;
        var _this = this;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              tensors = {};
              reader = weightStream.getReader();
              data = new ArrayBuffer(0);
              _b.label = 1;
            case 1:
              _b.trys.push([1, 7, 8, 9]);
              specs_2 = __values(specs), specs_2_1 = specs_2.next();
              _b.label = 2;
            case 2:
              if (!!specs_2_1.done) return [3, 6];
              spec = specs_2_1.value;
              return [4, getWeightBytelengthAsync(spec, function(start, end) {
                return __awaiter(_this, void 0, void 0, function() {
                  return __generator(this, function(_a2) {
                    switch (_a2.label) {
                      case 0:
                        return [4, readToLength(reader, data, end)];
                      case 1:
                        data = _a2.sent();
                        return [2, data.slice(start, end)];
                    }
                  });
                });
              })];
            case 3:
              byteLength = _b.sent();
              return [4, readToLength(reader, data, byteLength)];
            case 4:
              data = _b.sent();
              tensorData = data.slice(0, byteLength);
              data = data.slice(byteLength);
              weightTensor = decodeWeight(spec, tensorData);
              tensors[spec.name] = weightTensor;
              if (getBackend() === "webgpu") {
                b = backend();
                if ("uploadToGPU" in b && sizeFromShape(weightTensor.shape) >= env().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")) {
                  b.uploadToGPU(weightTensor.dataId);
                }
              }
              _b.label = 5;
            case 5:
              specs_2_1 = specs_2.next();
              return [3, 2];
            case 6:
              return [3, 9];
            case 7:
              e_2_1 = _b.sent();
              e_2 = { error: e_2_1 };
              return [3, 9];
            case 8:
              try {
                if (specs_2_1 && !specs_2_1.done && (_a = specs_2.return)) _a.call(specs_2);
              } finally {
                if (e_2) throw e_2.error;
              }
              return [
                7
                /*endfinally*/
              ];
            case 9:
              return [2, tensors];
          }
        });
      });
    }
    function concatenateTypedArrays(xs) {
      if (xs === null) {
        throw new Error("Invalid input value: ".concat(JSON.stringify(xs)));
      }
      var totalByteLength = 0;
      var normalizedXs = [];
      xs.forEach(function(x) {
        totalByteLength += x.byteLength;
        normalizedXs.push(x.byteLength === x.buffer.byteLength ? x : new x.constructor(x));
        if (!(x instanceof Float32Array || x instanceof Int32Array || x instanceof Uint8Array)) {
          throw new Error("Unsupported TypedArray subtype: ".concat(x.constructor.name));
        }
      });
      var y = new Uint8Array(totalByteLength);
      var offset = 0;
      normalizedXs.forEach(function(x) {
        y.set(new Uint8Array(x.buffer), offset);
        offset += x.byteLength;
      });
      return y.buffer;
    }
    var useNodeBuffer = typeof Buffer !== "undefined" && (typeof Blob === "undefined" || typeof atob === "undefined" || typeof btoa === "undefined");
    function stringByteLength(str) {
      if (useNodeBuffer) {
        return Buffer.byteLength(str, "utf8");
      }
      return new Blob([str]).size;
    }
    function arrayBufferToBase64String(buffer2) {
      if (useNodeBuffer) {
        return Buffer.from(buffer2).toString("base64");
      }
      var buf = new Uint8Array(buffer2);
      var s = "";
      for (var i = 0, l = buf.length; i < l; i++) {
        s += String.fromCharCode(buf[i]);
      }
      return btoa(s);
    }
    function base64StringToArrayBuffer(str) {
      if (useNodeBuffer) {
        var buf = Buffer.from(str, "base64");
        return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
      }
      var s = atob(str);
      var buffer2 = new Uint8Array(s.length);
      for (var i = 0; i < s.length; ++i) {
        buffer2.set([s.charCodeAt(i)], i);
      }
      return buffer2.buffer;
    }
    function concatenateArrayBuffers(buffers) {
      return CompositeArrayBuffer.join(buffers);
    }
    function basename(path) {
      var SEPARATOR = "/";
      path = path.trim();
      while (path.endsWith(SEPARATOR)) {
        path = path.slice(0, path.length - 1);
      }
      var items = path.split(SEPARATOR);
      return items[items.length - 1];
    }
    function getModelJSONForModelArtifacts(artifacts, manifest) {
      var result = {
        modelTopology: artifacts.modelTopology,
        format: artifacts.format,
        generatedBy: artifacts.generatedBy,
        convertedBy: artifacts.convertedBy,
        weightsManifest: manifest
      };
      if (artifacts.signature != null) {
        result.signature = artifacts.signature;
      }
      if (artifacts.userDefinedMetadata != null) {
        result.userDefinedMetadata = artifacts.userDefinedMetadata;
      }
      if (artifacts.modelInitializer != null) {
        result.modelInitializer = artifacts.modelInitializer;
      }
      if (artifacts.initializerSignature != null) {
        result.initializerSignature = artifacts.initializerSignature;
      }
      if (artifacts.trainingConfig != null) {
        result.trainingConfig = artifacts.trainingConfig;
      }
      return result;
    }
    function getModelArtifactsForJSONSync(modelJSON, weightSpecs, weightData) {
      var modelArtifacts = {
        modelTopology: modelJSON.modelTopology,
        format: modelJSON.format,
        generatedBy: modelJSON.generatedBy,
        convertedBy: modelJSON.convertedBy
      };
      if (modelJSON.trainingConfig != null) {
        modelArtifacts.trainingConfig = modelJSON.trainingConfig;
      }
      if (modelJSON.weightsManifest != null) {
        if (!weightSpecs) {
          throw new Error("modelJSON has weightsManifest but weightSpecs is null");
        }
        if (!weightData) {
          throw new Error("modelJSON has weightsManifest but weightData is null");
        }
        modelArtifacts.weightSpecs = weightSpecs;
        modelArtifacts.weightData = weightData;
      }
      if (modelJSON.signature != null) {
        modelArtifacts.signature = modelJSON.signature;
      }
      if (modelJSON.userDefinedMetadata != null) {
        modelArtifacts.userDefinedMetadata = modelJSON.userDefinedMetadata;
      }
      if (modelJSON.modelInitializer != null) {
        modelArtifacts.modelInitializer = modelJSON.modelInitializer;
      }
      if (modelJSON.initializerSignature != null) {
        modelArtifacts.initializerSignature = modelJSON.initializerSignature;
      }
      return modelArtifacts;
    }
    function getModelArtifactsForJSON(modelJSON, loadWeights2) {
      return __awaiter(this, void 0, void 0, function() {
        var weightSpecs, weightData;
        var _a;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              if (!(modelJSON.weightsManifest != null)) return [3, 2];
              return [4, loadWeights2(modelJSON.weightsManifest)];
            case 1:
              _a = __read.apply(void 0, [_b.sent(), 2]), weightSpecs = _a[0], weightData = _a[1];
              _b.label = 2;
            case 2:
              return [2, getModelArtifactsForJSONSync(modelJSON, weightSpecs, weightData)];
          }
        });
      });
    }
    function getModelArtifactsInfoForJSON(modelArtifacts) {
      if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
        throw new Error("Expected JSON model topology, received ArrayBuffer.");
      }
      return {
        dateSaved: /* @__PURE__ */ new Date(),
        modelTopologyType: "JSON",
        modelTopologyBytes: modelArtifacts.modelTopology == null ? 0 : stringByteLength(JSON.stringify(modelArtifacts.modelTopology)),
        weightSpecsBytes: modelArtifacts.weightSpecs == null ? 0 : stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)),
        weightDataBytes: modelArtifacts.weightData == null ? 0 : new CompositeArrayBuffer(modelArtifacts.weightData).byteLength
      };
    }
    function getWeightSpecs(weightsManifest) {
      var e_3, _a;
      var weightSpecs = [];
      try {
        for (var weightsManifest_1 = __values(weightsManifest), weightsManifest_1_1 = weightsManifest_1.next(); !weightsManifest_1_1.done; weightsManifest_1_1 = weightsManifest_1.next()) {
          var entry = weightsManifest_1_1.value;
          weightSpecs.push.apply(weightSpecs, __spreadArray([], __read(entry.weights), false));
        }
      } catch (e_3_1) {
        e_3 = { error: e_3_1 };
      } finally {
        try {
          if (weightsManifest_1_1 && !weightsManifest_1_1.done && (_a = weightsManifest_1.return)) _a.call(weightsManifest_1);
        } finally {
          if (e_3) throw e_3.error;
        }
      }
      return weightSpecs;
    }
    function computeFloat16MantisaTable() {
      var convertMantissa = function(i2) {
        var m = i2 << 13;
        var e = 0;
        while ((m & 8388608) === 0) {
          e -= 8388608;
          m <<= 1;
        }
        m &= ~8388608;
        e += 947912704;
        return m | e;
      };
      var mantisaTable = new Uint32Array(2048);
      mantisaTable[0] = 0;
      for (var i = 1; i < 1024; i++) {
        mantisaTable[i] = convertMantissa(i);
      }
      for (var i = 1024; i < 2048; i++) {
        mantisaTable[i] = 939524096 + (i - 1024 << 13);
      }
      return mantisaTable;
    }
    function computeFloat16ExponentTable() {
      var exponentTable = new Uint32Array(64);
      exponentTable[0] = 0;
      exponentTable[31] = 1199570944;
      exponentTable[32] = 2147483648;
      exponentTable[63] = 3347054592;
      for (var i = 1; i < 31; i++) {
        exponentTable[i] = i << 23;
      }
      for (var i = 33; i < 63; i++) {
        exponentTable[i] = 2147483648 + (i - 32 << 23);
      }
      return exponentTable;
    }
    function computeFloat16OffsetTable() {
      var offsetTable = new Uint32Array(64);
      for (var i = 0; i < 64; i++) {
        offsetTable[i] = 1024;
      }
      offsetTable[0] = offsetTable[32] = 0;
      return offsetTable;
    }
    function getFloat16Decoder() {
      var mantisaTable = computeFloat16MantisaTable();
      var exponentTable = computeFloat16ExponentTable();
      var offsetTable = computeFloat16OffsetTable();
      return function(quantizedArray) {
        var buffer2 = new ArrayBuffer(4 * quantizedArray.length);
        var bufferUint32View = new Uint32Array(buffer2);
        for (var index = 0; index < quantizedArray.length; index++) {
          var float16Bits = quantizedArray[index];
          var float32Bits = mantisaTable[offsetTable[float16Bits >> 10] + (float16Bits & 1023)] + exponentTable[float16Bits >> 10];
          bufferUint32View[index] = float32Bits;
        }
        return new Float32Array(buffer2);
      };
    }
    var IORouterRegistry = (
      /** @class */
      function() {
        function IORouterRegistry2() {
          this.saveRouters = [];
          this.loadRouters = [];
        }
        IORouterRegistry2.getInstance = function() {
          if (IORouterRegistry2.instance == null) {
            IORouterRegistry2.instance = new IORouterRegistry2();
          }
          return IORouterRegistry2.instance;
        };
        IORouterRegistry2.registerSaveRouter = function(saveRouter) {
          IORouterRegistry2.getInstance().saveRouters.push(saveRouter);
        };
        IORouterRegistry2.registerLoadRouter = function(loadRouter) {
          IORouterRegistry2.getInstance().loadRouters.push(loadRouter);
        };
        IORouterRegistry2.getSaveHandlers = function(url) {
          return IORouterRegistry2.getHandlers(url, "save");
        };
        IORouterRegistry2.getLoadHandlers = function(url, loadOptions) {
          return IORouterRegistry2.getHandlers(url, "load", loadOptions);
        };
        IORouterRegistry2.getHandlers = function(url, handlerType, loadOptions) {
          var validHandlers = [];
          var routers = handlerType === "load" ? IORouterRegistry2.getInstance().loadRouters : IORouterRegistry2.getInstance().saveRouters;
          routers.forEach(function(router) {
            var handler = router(url, loadOptions);
            if (handler !== null) {
              validHandlers.push(handler);
            }
          });
          return validHandlers;
        };
        return IORouterRegistry2;
      }()
    );
    var registerSaveRouter = function(loudRouter) {
      return IORouterRegistry.registerSaveRouter(loudRouter);
    };
    var registerLoadRouter = function(loudRouter) {
      return IORouterRegistry.registerLoadRouter(loudRouter);
    };
    var getSaveHandlers = function(url) {
      return IORouterRegistry.getSaveHandlers(url);
    };
    var getLoadHandlers = function(url, loadOptions) {
      return IORouterRegistry.getLoadHandlers(url, loadOptions);
    };
    var DATABASE_NAME = "tensorflowjs";
    var DATABASE_VERSION = 1;
    var MODEL_STORE_NAME = "models_store";
    var INFO_STORE_NAME = "model_info_store";
    function getIndexedDBFactory() {
      if (!env().getBool("IS_BROWSER")) {
        throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");
      }
      var theWindow = typeof window === "undefined" ? self : window;
      var factory = theWindow.indexedDB || theWindow.mozIndexedDB || theWindow.webkitIndexedDB || theWindow.msIndexedDB || theWindow.shimIndexedDB;
      if (factory == null) {
        throw new Error("The current browser does not appear to support IndexedDB.");
      }
      return factory;
    }
    function setUpDatabase(openRequest) {
      var db = openRequest.result;
      db.createObjectStore(MODEL_STORE_NAME, { keyPath: "modelPath" });
      db.createObjectStore(INFO_STORE_NAME, { keyPath: "modelPath" });
    }
    var BrowserIndexedDB = (
      /** @class */
      function() {
        function BrowserIndexedDB2(modelPath) {
          this.indexedDB = getIndexedDBFactory();
          if (modelPath == null || !modelPath) {
            throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");
          }
          this.modelPath = modelPath;
        }
        BrowserIndexedDB2.prototype.save = function(modelArtifacts) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
                throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");
              }
              return [2, this.databaseAction(this.modelPath, modelArtifacts)];
            });
          });
        };
        BrowserIndexedDB2.prototype.load = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              return [2, this.databaseAction(this.modelPath)];
            });
          });
        };
        BrowserIndexedDB2.prototype.databaseAction = function(modelPath, modelArtifacts) {
          var _this = this;
          return new Promise(function(resolve, reject) {
            var openRequest = _this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
            openRequest.onupgradeneeded = function() {
              return setUpDatabase(openRequest);
            };
            openRequest.onsuccess = function() {
              var db = openRequest.result;
              if (modelArtifacts == null) {
                var modelTx = db.transaction(MODEL_STORE_NAME, "readonly");
                var modelStore = modelTx.objectStore(MODEL_STORE_NAME);
                var getRequest_1 = modelStore.get(_this.modelPath);
                getRequest_1.onsuccess = function() {
                  if (getRequest_1.result == null) {
                    db.close();
                    return reject(new Error("Cannot find model with path '".concat(_this.modelPath, "' ") + "in IndexedDB."));
                  } else {
                    resolve(getRequest_1.result.modelArtifacts);
                  }
                };
                getRequest_1.onerror = function(error) {
                  db.close();
                  return reject(getRequest_1.error);
                };
                modelTx.oncomplete = function() {
                  return db.close();
                };
              } else {
                modelArtifacts.weightData = CompositeArrayBuffer.join(modelArtifacts.weightData);
                var modelArtifactsInfo_1 = getModelArtifactsInfoForJSON(modelArtifacts);
                var infoTx_1 = db.transaction(INFO_STORE_NAME, "readwrite");
                var infoStore_1 = infoTx_1.objectStore(INFO_STORE_NAME);
                var putInfoRequest_1;
                try {
                  putInfoRequest_1 = infoStore_1.put({ modelPath: _this.modelPath, modelArtifactsInfo: modelArtifactsInfo_1 });
                } catch (error) {
                  return reject(error);
                }
                var modelTx_1;
                putInfoRequest_1.onsuccess = function() {
                  modelTx_1 = db.transaction(MODEL_STORE_NAME, "readwrite");
                  var modelStore2 = modelTx_1.objectStore(MODEL_STORE_NAME);
                  var putModelRequest;
                  try {
                    putModelRequest = modelStore2.put({
                      modelPath: _this.modelPath,
                      modelArtifacts,
                      modelArtifactsInfo: modelArtifactsInfo_1
                    });
                  } catch (error) {
                    return reject(error);
                  }
                  putModelRequest.onsuccess = function() {
                    return resolve({ modelArtifactsInfo: modelArtifactsInfo_1 });
                  };
                  putModelRequest.onerror = function(error) {
                    infoStore_1 = infoTx_1.objectStore(INFO_STORE_NAME);
                    var deleteInfoRequest = infoStore_1.delete(_this.modelPath);
                    deleteInfoRequest.onsuccess = function() {
                      db.close();
                      return reject(putModelRequest.error);
                    };
                    deleteInfoRequest.onerror = function(error2) {
                      db.close();
                      return reject(putModelRequest.error);
                    };
                  };
                };
                putInfoRequest_1.onerror = function(error) {
                  db.close();
                  return reject(putInfoRequest_1.error);
                };
                infoTx_1.oncomplete = function() {
                  if (modelTx_1 == null) {
                    db.close();
                  } else {
                    modelTx_1.oncomplete = function() {
                      return db.close();
                    };
                  }
                };
              }
            };
            openRequest.onerror = function(error) {
              return reject(openRequest.error);
            };
          });
        };
        return BrowserIndexedDB2;
      }()
    );
    BrowserIndexedDB.URL_SCHEME = "indexeddb://";
    var indexedDBRouter = function(url) {
      if (!env().getBool("IS_BROWSER")) {
        return null;
      } else {
        if (!Array.isArray(url) && url.startsWith(BrowserIndexedDB.URL_SCHEME)) {
          return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length));
        } else {
          return null;
        }
      }
    };
    IORouterRegistry.registerSaveRouter(indexedDBRouter);
    IORouterRegistry.registerLoadRouter(indexedDBRouter);
    function browserIndexedDB(modelPath) {
      return new BrowserIndexedDB(modelPath);
    }
    function maybeStripScheme$1(key) {
      return key.startsWith(BrowserIndexedDB.URL_SCHEME) ? key.slice(BrowserIndexedDB.URL_SCHEME.length) : key;
    }
    var BrowserIndexedDBManager = (
      /** @class */
      function() {
        function BrowserIndexedDBManager2() {
          this.indexedDB = getIndexedDBFactory();
        }
        BrowserIndexedDBManager2.prototype.listModels = function() {
          return __awaiter(this, void 0, void 0, function() {
            var _this = this;
            return __generator(this, function(_a) {
              return [2, new Promise(function(resolve, reject) {
                var openRequest = _this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
                openRequest.onupgradeneeded = function() {
                  return setUpDatabase(openRequest);
                };
                openRequest.onsuccess = function() {
                  var db = openRequest.result;
                  var tx = db.transaction(INFO_STORE_NAME, "readonly");
                  var store = tx.objectStore(INFO_STORE_NAME);
                  var getAllInfoRequest = store.getAll();
                  getAllInfoRequest.onsuccess = function() {
                    var e_1, _a2;
                    var out = {};
                    try {
                      for (var _b = __values(getAllInfoRequest.result), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var item = _c.value;
                        out[item.modelPath] = item.modelArtifactsInfo;
                      }
                    } catch (e_1_1) {
                      e_1 = { error: e_1_1 };
                    } finally {
                      try {
                        if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
                      } finally {
                        if (e_1) throw e_1.error;
                      }
                    }
                    resolve(out);
                  };
                  getAllInfoRequest.onerror = function(error) {
                    db.close();
                    return reject(getAllInfoRequest.error);
                  };
                  tx.oncomplete = function() {
                    return db.close();
                  };
                };
                openRequest.onerror = function(error) {
                  return reject(openRequest.error);
                };
              })];
            });
          });
        };
        BrowserIndexedDBManager2.prototype.removeModel = function(path) {
          return __awaiter(this, void 0, void 0, function() {
            var _this = this;
            return __generator(this, function(_a) {
              path = maybeStripScheme$1(path);
              return [2, new Promise(function(resolve, reject) {
                var openRequest = _this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
                openRequest.onupgradeneeded = function() {
                  return setUpDatabase(openRequest);
                };
                openRequest.onsuccess = function() {
                  var db = openRequest.result;
                  var infoTx = db.transaction(INFO_STORE_NAME, "readwrite");
                  var infoStore = infoTx.objectStore(INFO_STORE_NAME);
                  var getInfoRequest = infoStore.get(path);
                  var modelTx;
                  getInfoRequest.onsuccess = function() {
                    if (getInfoRequest.result == null) {
                      db.close();
                      return reject(new Error("Cannot find model with path '".concat(path, "' ") + "in IndexedDB."));
                    } else {
                      var deleteInfoRequest = infoStore.delete(path);
                      var deleteModelData_1 = function() {
                        modelTx = db.transaction(MODEL_STORE_NAME, "readwrite");
                        var modelStore = modelTx.objectStore(MODEL_STORE_NAME);
                        var deleteModelRequest = modelStore.delete(path);
                        deleteModelRequest.onsuccess = function() {
                          return resolve(getInfoRequest.result.modelArtifactsInfo);
                        };
                        deleteModelRequest.onerror = function(error) {
                          return reject(getInfoRequest.error);
                        };
                      };
                      deleteInfoRequest.onsuccess = deleteModelData_1;
                      deleteInfoRequest.onerror = function(error) {
                        deleteModelData_1();
                        db.close();
                        return reject(getInfoRequest.error);
                      };
                    }
                  };
                  getInfoRequest.onerror = function(error) {
                    db.close();
                    return reject(getInfoRequest.error);
                  };
                  infoTx.oncomplete = function() {
                    if (modelTx == null) {
                      db.close();
                    } else {
                      modelTx.oncomplete = function() {
                        return db.close();
                      };
                    }
                  };
                };
                openRequest.onerror = function(error) {
                  return reject(openRequest.error);
                };
              })];
            });
          });
        };
        return BrowserIndexedDBManager2;
      }()
    );
    var PATH_SEPARATOR = "/";
    var PATH_PREFIX = "tensorflowjs_models";
    var INFO_SUFFIX = "info";
    var MODEL_TOPOLOGY_SUFFIX = "model_topology";
    var WEIGHT_SPECS_SUFFIX = "weight_specs";
    var WEIGHT_DATA_SUFFIX = "weight_data";
    var MODEL_METADATA_SUFFIX = "model_metadata";
    function getModelKeys(path) {
      return {
        info: [PATH_PREFIX, path, INFO_SUFFIX].join(PATH_SEPARATOR),
        topology: [PATH_PREFIX, path, MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR),
        weightSpecs: [PATH_PREFIX, path, WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR),
        weightData: [PATH_PREFIX, path, WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR),
        modelMetadata: [PATH_PREFIX, path, MODEL_METADATA_SUFFIX].join(PATH_SEPARATOR)
      };
    }
    function removeItems(keys) {
      var e_1, _a;
      try {
        for (var _b = __values(Object.values(keys)), _c = _b.next(); !_c.done; _c = _b.next()) {
          var key = _c.value;
          window.localStorage.removeItem(key);
        }
      } catch (e_1_1) {
        e_1 = { error: e_1_1 };
      } finally {
        try {
          if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
        } finally {
          if (e_1) throw e_1.error;
        }
      }
    }
    function getModelPathFromKey(key) {
      var items = key.split(PATH_SEPARATOR);
      if (items.length < 3) {
        throw new Error("Invalid key format: ".concat(key));
      }
      return items.slice(1, items.length - 1).join(PATH_SEPARATOR);
    }
    function maybeStripScheme(key) {
      return key.startsWith(BrowserLocalStorage.URL_SCHEME) ? key.slice(BrowserLocalStorage.URL_SCHEME.length) : key;
    }
    var BrowserLocalStorage = (
      /** @class */
      function() {
        function BrowserLocalStorage2(modelPath) {
          if (!env().getBool("IS_BROWSER") || typeof window === "undefined" || typeof window.localStorage === "undefined") {
            throw new Error("The current environment does not support local storage.");
          }
          this.LS = window.localStorage;
          if (modelPath == null || !modelPath) {
            throw new Error("For local storage, modelPath must not be null, undefined or empty.");
          }
          this.modelPath = modelPath;
          this.keys = getModelKeys(this.modelPath);
        }
        BrowserLocalStorage2.prototype.save = function(modelArtifacts) {
          return __awaiter(this, void 0, void 0, function() {
            var topology, weightSpecs, modelArtifactsInfo, weightBuffer, metadata;
            return __generator(this, function(_a) {
              if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
                throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");
              } else {
                topology = JSON.stringify(modelArtifacts.modelTopology);
                weightSpecs = JSON.stringify(modelArtifacts.weightSpecs);
                modelArtifactsInfo = getModelArtifactsInfoForJSON(modelArtifacts);
                weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);
                try {
                  this.LS.setItem(this.keys.info, JSON.stringify(modelArtifactsInfo));
                  this.LS.setItem(this.keys.topology, topology);
                  this.LS.setItem(this.keys.weightSpecs, weightSpecs);
                  this.LS.setItem(this.keys.weightData, arrayBufferToBase64String(weightBuffer));
                  metadata = {
                    format: modelArtifacts.format,
                    generatedBy: modelArtifacts.generatedBy,
                    convertedBy: modelArtifacts.convertedBy,
                    signature: modelArtifacts.signature != null ? modelArtifacts.signature : void 0,
                    userDefinedMetadata: modelArtifacts.userDefinedMetadata != null ? modelArtifacts.userDefinedMetadata : void 0,
                    modelInitializer: modelArtifacts.modelInitializer != null ? modelArtifacts.modelInitializer : void 0,
                    initializerSignature: modelArtifacts.initializerSignature != null ? modelArtifacts.initializerSignature : void 0,
                    trainingConfig: modelArtifacts.trainingConfig != null ? modelArtifacts.trainingConfig : void 0
                  };
                  this.LS.setItem(this.keys.modelMetadata, JSON.stringify(metadata));
                  return [2, { modelArtifactsInfo }];
                } catch (err) {
                  removeItems(this.keys);
                  throw new Error("Failed to save model '".concat(this.modelPath, "' to local storage: ") + "size quota being exceeded is a possible cause of this failure: " + "modelTopologyBytes=".concat(modelArtifactsInfo.modelTopologyBytes, ", ") + "weightSpecsBytes=".concat(modelArtifactsInfo.weightSpecsBytes, ", ") + "weightDataBytes=".concat(modelArtifactsInfo.weightDataBytes, "."));
                }
              }
              return [
                2
                /*return*/
              ];
            });
          });
        };
        BrowserLocalStorage2.prototype.load = function() {
          return __awaiter(this, void 0, void 0, function() {
            var info, out, topology, weightSpecs, metadataString, metadata, weightDataBase64;
            return __generator(this, function(_a) {
              info = JSON.parse(this.LS.getItem(this.keys.info));
              if (info == null) {
                throw new Error("In local storage, there is no model with name '".concat(this.modelPath, "'"));
              }
              if (info.modelTopologyType !== "JSON") {
                throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");
              }
              out = {};
              topology = JSON.parse(this.LS.getItem(this.keys.topology));
              if (topology == null) {
                throw new Error("In local storage, the topology of model '".concat(this.modelPath, "' ") + "is missing.");
              }
              out.modelTopology = topology;
              weightSpecs = JSON.parse(this.LS.getItem(this.keys.weightSpecs));
              if (weightSpecs == null) {
                throw new Error("In local storage, the weight specs of model '".concat(this.modelPath, "' ") + "are missing.");
              }
              out.weightSpecs = weightSpecs;
              metadataString = this.LS.getItem(this.keys.modelMetadata);
              if (metadataString != null) {
                metadata = JSON.parse(metadataString);
                out.format = metadata.format;
                out.generatedBy = metadata.generatedBy;
                out.convertedBy = metadata.convertedBy;
                if (metadata.signature != null) {
                  out.signature = metadata.signature;
                }
                if (metadata.userDefinedMetadata != null) {
                  out.userDefinedMetadata = metadata.userDefinedMetadata;
                }
                if (metadata.modelInitializer != null) {
                  out.modelInitializer = metadata.modelInitializer;
                }
                if (metadata.initializerSignature != null) {
                  out.initializerSignature = metadata.initializerSignature;
                }
                if (metadata.trainingConfig != null) {
                  out.trainingConfig = metadata.trainingConfig;
                }
              }
              weightDataBase64 = this.LS.getItem(this.keys.weightData);
              if (weightDataBase64 == null) {
                throw new Error("In local storage, the binary weight values of model " + "'".concat(this.modelPath, "' are missing."));
              }
              out.weightData = base64StringToArrayBuffer(weightDataBase64);
              return [2, out];
            });
          });
        };
        return BrowserLocalStorage2;
      }()
    );
    BrowserLocalStorage.URL_SCHEME = "localstorage://";
    var localStorageRouter = function(url) {
      if (!env().getBool("IS_BROWSER")) {
        return null;
      } else {
        if (!Array.isArray(url) && url.startsWith(BrowserLocalStorage.URL_SCHEME)) {
          return browserLocalStorage(url.slice(BrowserLocalStorage.URL_SCHEME.length));
        } else {
          return null;
        }
      }
    };
    IORouterRegistry.registerSaveRouter(localStorageRouter);
    IORouterRegistry.registerLoadRouter(localStorageRouter);
    function browserLocalStorage(modelPath) {
      return new BrowserLocalStorage(modelPath);
    }
    var BrowserLocalStorageManager = (
      /** @class */
      function() {
        function BrowserLocalStorageManager2() {
          assert(env().getBool("IS_BROWSER"), function() {
            return "Current environment is not a web browser";
          });
          assert(typeof window === "undefined" || typeof window.localStorage !== "undefined", function() {
            return "Current browser does not appear to support localStorage";
          });
          this.LS = window.localStorage;
        }
        BrowserLocalStorageManager2.prototype.listModels = function() {
          return __awaiter(this, void 0, void 0, function() {
            var out, prefix, suffix, i, key, modelPath;
            return __generator(this, function(_a) {
              out = {};
              prefix = PATH_PREFIX + PATH_SEPARATOR;
              suffix = PATH_SEPARATOR + INFO_SUFFIX;
              for (i = 0; i < this.LS.length; ++i) {
                key = this.LS.key(i);
                if (key.startsWith(prefix) && key.endsWith(suffix)) {
                  modelPath = getModelPathFromKey(key);
                  out[modelPath] = JSON.parse(this.LS.getItem(key));
                }
              }
              return [2, out];
            });
          });
        };
        BrowserLocalStorageManager2.prototype.removeModel = function(path) {
          return __awaiter(this, void 0, void 0, function() {
            var keys, info;
            return __generator(this, function(_a) {
              path = maybeStripScheme(path);
              keys = getModelKeys(path);
              if (this.LS.getItem(keys.info) == null) {
                throw new Error("Cannot find model at path '".concat(path, "'"));
              }
              info = JSON.parse(this.LS.getItem(keys.info));
              removeItems(keys);
              return [2, info];
            });
          });
        };
        return BrowserLocalStorageManager2;
      }()
    );
    var URL_SCHEME_SUFFIX = "://";
    var ModelStoreManagerRegistry = (
      /** @class */
      function() {
        function ModelStoreManagerRegistry2() {
          this.managers = {};
        }
        ModelStoreManagerRegistry2.getInstance = function() {
          if (ModelStoreManagerRegistry2.instance == null) {
            ModelStoreManagerRegistry2.instance = new ModelStoreManagerRegistry2();
          }
          return ModelStoreManagerRegistry2.instance;
        };
        ModelStoreManagerRegistry2.registerManager = function(scheme, manager) {
          assert(scheme != null, function() {
            return "scheme must not be undefined or null.";
          });
          if (scheme.endsWith(URL_SCHEME_SUFFIX)) {
            scheme = scheme.slice(0, scheme.indexOf(URL_SCHEME_SUFFIX));
          }
          assert(scheme.length > 0, function() {
            return "scheme must not be an empty string.";
          });
          var registry = ModelStoreManagerRegistry2.getInstance();
          assert(registry.managers[scheme] == null, function() {
            return "A model store manager is already registered for scheme '".concat(scheme, "'.");
          });
          registry.managers[scheme] = manager;
        };
        ModelStoreManagerRegistry2.getManager = function(scheme) {
          var manager = ModelStoreManagerRegistry2.getInstance().managers[scheme];
          if (manager == null) {
            throw new Error("Cannot find model manager for scheme '".concat(scheme, "'"));
          }
          return manager;
        };
        ModelStoreManagerRegistry2.getSchemes = function() {
          return Object.keys(ModelStoreManagerRegistry2.getInstance().managers);
        };
        return ModelStoreManagerRegistry2;
      }()
    );
    function parseURL(url) {
      if (url.indexOf(URL_SCHEME_SUFFIX) === -1) {
        throw new Error("The url string provided does not contain a scheme. Supported schemes are: " + "".concat(ModelStoreManagerRegistry.getSchemes().join(",")));
      }
      return {
        scheme: url.split(URL_SCHEME_SUFFIX)[0],
        path: url.split(URL_SCHEME_SUFFIX)[1]
      };
    }
    function cloneModelInternal(sourceURL, destURL, deleteSource) {
      if (deleteSource === void 0) {
        deleteSource = false;
      }
      return __awaiter(this, void 0, void 0, function() {
        var loadHandlers, loadHandler, saveHandlers, saveHandler, sourceScheme, sourcePath, sameMedium, modelArtifacts, saveResult;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              assert(sourceURL !== destURL, function() {
                return "Old path and new path are the same: '".concat(sourceURL, "'");
              });
              loadHandlers = IORouterRegistry.getLoadHandlers(sourceURL);
              assert(loadHandlers.length > 0, function() {
                return "Copying failed because no load handler is found for source URL ".concat(sourceURL, ".");
              });
              assert(loadHandlers.length < 2, function() {
                return "Copying failed because more than one (".concat(loadHandlers.length, ") ") + "load handlers for source URL ".concat(sourceURL, ".");
              });
              loadHandler = loadHandlers[0];
              saveHandlers = IORouterRegistry.getSaveHandlers(destURL);
              assert(saveHandlers.length > 0, function() {
                return "Copying failed because no save handler is found for destination " + "URL ".concat(destURL, ".");
              });
              assert(saveHandlers.length < 2, function() {
                return "Copying failed because more than one (".concat(loadHandlers.length, ") ") + "save handlers for destination URL ".concat(destURL, ".");
              });
              saveHandler = saveHandlers[0];
              sourceScheme = parseURL(sourceURL).scheme;
              sourcePath = parseURL(sourceURL).path;
              sameMedium = sourceScheme === parseURL(sourceURL).scheme;
              return [4, loadHandler.load()];
            case 1:
              modelArtifacts = _a.sent();
              if (!(deleteSource && sameMedium)) return [3, 3];
              return [4, ModelStoreManagerRegistry.getManager(sourceScheme).removeModel(sourcePath)];
            case 2:
              _a.sent();
              _a.label = 3;
            case 3:
              return [4, saveHandler.save(modelArtifacts)];
            case 4:
              saveResult = _a.sent();
              if (!(deleteSource && !sameMedium)) return [3, 6];
              return [4, ModelStoreManagerRegistry.getManager(sourceScheme).removeModel(sourcePath)];
            case 5:
              _a.sent();
              _a.label = 6;
            case 6:
              return [2, saveResult.modelArtifactsInfo];
          }
        });
      });
    }
    function listModels() {
      return __awaiter(this, void 0, void 0, function() {
        var schemes, out, schemes_1, schemes_1_1, scheme, schemeOut, path, url, e_1_1;
        var e_1, _a;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              schemes = ModelStoreManagerRegistry.getSchemes();
              out = {};
              _b.label = 1;
            case 1:
              _b.trys.push([1, 6, 7, 8]);
              schemes_1 = __values(schemes), schemes_1_1 = schemes_1.next();
              _b.label = 2;
            case 2:
              if (!!schemes_1_1.done) return [3, 5];
              scheme = schemes_1_1.value;
              return [4, ModelStoreManagerRegistry.getManager(scheme).listModels()];
            case 3:
              schemeOut = _b.sent();
              for (path in schemeOut) {
                url = scheme + URL_SCHEME_SUFFIX + path;
                out[url] = schemeOut[path];
              }
              _b.label = 4;
            case 4:
              schemes_1_1 = schemes_1.next();
              return [3, 2];
            case 5:
              return [3, 8];
            case 6:
              e_1_1 = _b.sent();
              e_1 = { error: e_1_1 };
              return [3, 8];
            case 7:
              try {
                if (schemes_1_1 && !schemes_1_1.done && (_a = schemes_1.return)) _a.call(schemes_1);
              } finally {
                if (e_1) throw e_1.error;
              }
              return [
                7
                /*endfinally*/
              ];
            case 8:
              return [2, out];
          }
        });
      });
    }
    function removeModel(url) {
      return __awaiter(this, void 0, void 0, function() {
        var schemeAndPath, manager;
        return __generator(this, function(_a) {
          schemeAndPath = parseURL(url);
          manager = ModelStoreManagerRegistry.getManager(schemeAndPath.scheme);
          return [2, manager.removeModel(schemeAndPath.path)];
        });
      });
    }
    function copyModel(sourceURL, destURL) {
      return __awaiter(this, void 0, void 0, function() {
        var deleteSource;
        return __generator(this, function(_a) {
          deleteSource = false;
          return [2, cloneModelInternal(sourceURL, destURL, deleteSource)];
        });
      });
    }
    function moveModel(sourceURL, destURL) {
      return __awaiter(this, void 0, void 0, function() {
        var deleteSource;
        return __generator(this, function(_a) {
          deleteSource = true;
          return [2, cloneModelInternal(sourceURL, destURL, deleteSource)];
        });
      });
    }
    var PlatformBrowser = (
      /** @class */
      function() {
        function PlatformBrowser2() {
          this.messageName = "setTimeoutCustom";
          this.functionRefs = [];
          this.handledMessageCount = 0;
          this.hasEventListener = false;
        }
        PlatformBrowser2.prototype.fetch = function(path, init) {
          return fetch(path, init);
        };
        PlatformBrowser2.prototype.now = function() {
          return performance.now();
        };
        PlatformBrowser2.prototype.encode = function(text, encoding) {
          if (encoding !== "utf-8" && encoding !== "utf8") {
            throw new Error("Browser's encoder only supports utf-8, but got ".concat(encoding));
          }
          if (this.textEncoder == null) {
            this.textEncoder = new TextEncoder();
          }
          return this.textEncoder.encode(text);
        };
        PlatformBrowser2.prototype.decode = function(bytes, encoding) {
          return new TextDecoder(encoding).decode(bytes);
        };
        PlatformBrowser2.prototype.setTimeoutCustom = function(functionRef, delay) {
          var _this = this;
          if (typeof window === "undefined" || !env().getBool("USE_SETTIMEOUTCUSTOM")) {
            setTimeout(functionRef, delay);
            return;
          }
          this.functionRefs.push(functionRef);
          setTimeout(function() {
            window.postMessage({ name: _this.messageName, index: _this.functionRefs.length - 1 }, "*");
          }, delay);
          if (!this.hasEventListener) {
            this.hasEventListener = true;
            window.addEventListener("message", function(event) {
              if (event.source === window && event.data.name === _this.messageName) {
                event.stopPropagation();
                var functionRef_1 = _this.functionRefs[event.data.index];
                functionRef_1();
                _this.handledMessageCount++;
                if (_this.handledMessageCount === _this.functionRefs.length) {
                  _this.functionRefs = [];
                  _this.handledMessageCount = 0;
                }
              }
            }, true);
          }
        };
        PlatformBrowser2.prototype.isTypedArray = function(a) {
          return isTypedArrayBrowser(a);
        };
        return PlatformBrowser2;
      }()
    );
    if (env().get("IS_BROWSER")) {
      env().setPlatform("browser", new PlatformBrowser());
      try {
        ModelStoreManagerRegistry.registerManager(BrowserLocalStorage.URL_SCHEME, new BrowserLocalStorageManager());
      } catch (err) {
      }
      try {
        ModelStoreManagerRegistry.registerManager(BrowserIndexedDB.URL_SCHEME, new BrowserIndexedDBManager());
      } catch (err) {
      }
    }
    var getNodeFetch = {
      // tslint:disable-next-line:no-require-imports
      importFetch: function() {
        return require_lib2();
      }
    };
    var systemFetch;
    var PlatformNode = (
      /** @class */
      function() {
        function PlatformNode2() {
          this.util = require("util");
          this.textEncoder = new this.util.TextEncoder();
        }
        PlatformNode2.prototype.fetch = function(path, requestInits) {
          if (env().global.fetch != null) {
            return env().global.fetch(path, requestInits);
          }
          if (systemFetch == null) {
            systemFetch = getNodeFetch.importFetch();
          }
          return systemFetch(path, requestInits);
        };
        PlatformNode2.prototype.now = function() {
          var time2 = process.hrtime();
          return time2[0] * 1e3 + time2[1] / 1e6;
        };
        PlatformNode2.prototype.encode = function(text, encoding) {
          if (encoding !== "utf-8" && encoding !== "utf8") {
            throw new Error("Node built-in encoder only supports utf-8, but got ".concat(encoding));
          }
          return this.textEncoder.encode(text);
        };
        PlatformNode2.prototype.decode = function(bytes, encoding) {
          if (bytes.length === 0) {
            return "";
          }
          return new this.util.TextDecoder(encoding).decode(bytes);
        };
        PlatformNode2.prototype.isTypedArray = function(a) {
          return this.util.types.isFloat32Array(a) || this.util.types.isInt32Array(a) || this.util.types.isUint8Array(a) || this.util.types.isUint8ClampedArray(a);
        };
        return PlatformNode2;
      }()
    );
    if (env().get("IS_NODE") && !env().get("IS_BROWSER")) {
      env().setPlatform("node", new PlatformNode());
    }
    function buffer(shape, dtype, values) {
      if (dtype === void 0) {
        dtype = "float32";
      }
      dtype = dtype || "float32";
      assertNonNegativeIntegerDimensions(shape);
      return new TensorBuffer(shape, dtype, values);
    }
    function cast_(x, dtype) {
      var $x = convertToTensor(x, "x", "cast");
      if (!isValidDtype(dtype)) {
        throw new Error("Failed to cast to unknown dtype ".concat(dtype));
      }
      if (dtype === "string" && $x.dtype !== "string" || dtype !== "string" && $x.dtype === "string") {
        throw new Error("Only strings can be casted to strings");
      }
      var inputs = { x: $x };
      var attrs = { dtype };
      return ENGINE.runKernel(Cast, inputs, attrs);
    }
    var cast = /* @__PURE__ */ op({ cast_ });
    function clone_(x) {
      var $x = convertToTensor(x, "x", "clone", "string_or_numeric");
      var inputs = { x: $x };
      return ENGINE.runKernel(Identity, inputs);
    }
    var clone = /* @__PURE__ */ op({ clone_ });
    function print(x, verbose) {
      if (verbose === void 0) {
        verbose = false;
      }
      console.log(x.toString(verbose));
    }
    getOrMakeEngine();
    var opHandler = {
      buffer,
      cast,
      clone,
      print
    };
    setOpHandler(opHandler);
    function add_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "add");
      var $b = convertToTensor(b, "b", "add");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Add, inputs);
    }
    var add = /* @__PURE__ */ op({ add_ });
    function floorDiv_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "floorDiv");
      var $b = convertToTensor(b, "b", "floorDiv");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(FloorDiv, inputs);
    }
    var floorDiv = /* @__PURE__ */ op({ floorDiv_ });
    function div_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "div");
      var $b = convertToTensor(b, "b", "div");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      if ($a.dtype === "int32" && $b.dtype === "int32") {
        return floorDiv($a, $b);
      }
      var inputs = { a: $a, b: $b };
      var attrs = {};
      return ENGINE.runKernel(RealDiv, inputs, attrs);
    }
    var div = /* @__PURE__ */ op({ div_ });
    function mul_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "mul");
      var $b = convertToTensor(b, "b", "mul");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Multiply, inputs);
    }
    var mul = /* @__PURE__ */ op({ mul_ });
    function abs_(x) {
      var $x = convertToTensor(x, "x", "abs");
      if ($x.dtype === "complex64") {
        var inputs = { x: $x };
        return ENGINE.runKernel(ComplexAbs, inputs);
      } else {
        var inputs = { x: $x };
        return ENGINE.runKernel(Abs, inputs);
      }
    }
    var abs = /* @__PURE__ */ op({ abs_ });
    function acos_(x) {
      var $x = convertToTensor(x, "x", "acos");
      var inputs = { x: $x };
      return ENGINE.runKernel(Acos, inputs);
    }
    var acos = /* @__PURE__ */ op({ acos_ });
    function acosh_(x) {
      var $x = convertToTensor(x, "x", "acosh");
      var inputs = { x: $x };
      return ENGINE.runKernel(Acosh, inputs);
    }
    var acosh = /* @__PURE__ */ op({ acosh_ });
    function addN_(tensors) {
      assert(Array.isArray(tensors), function() {
        return "The argument passed to tf.addN() must be a list of tensors";
      });
      assert(tensors.length >= 1, function() {
        return "Must pass at least one tensor to tf.addN(), but got " + "".concat(tensors.length);
      });
      var $tensors = tensors.map(function(t, i) {
        return convertToTensor(t, "tensors".concat(i), "addN");
      });
      var firstTensor = $tensors[0];
      $tensors.forEach(function(t) {
        if (t.dtype !== firstTensor.dtype) {
          throw new Error("All tensors passed to tf.addN() must have the same dtype");
        }
      });
      $tensors.forEach(function(t) {
        if (!arraysEqual(t.shape, firstTensor.shape)) {
          throw new Error("All tensors passed to tf.addN() must have the same shape");
        }
      });
      var inputs = $tensors;
      return ENGINE.runKernel(AddN, inputs);
    }
    var addN = /* @__PURE__ */ op({ addN_ });
    function all_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "all", "bool");
      var inputs = { x: $x };
      var attrs = { axis, keepDims };
      return ENGINE.runKernel(All, inputs, attrs);
    }
    var all = /* @__PURE__ */ op({ all_ });
    function any_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "any", "bool");
      var inputs = { x: $x };
      var attrs = { axis, keepDims };
      return ENGINE.runKernel(Any, inputs, attrs);
    }
    var any = /* @__PURE__ */ op({ any_ });
    function argMax_(x, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $x = convertToTensor(x, "x", "argMax");
      var inputs = { x: $x };
      var attrs = { axis };
      return ENGINE.runKernel(ArgMax, inputs, attrs);
    }
    var argMax = /* @__PURE__ */ op({ argMax_ });
    function argMin_(x, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $x = convertToTensor(x, "x", "argMin");
      var inputs = { x: $x };
      var attrs = { axis };
      return ENGINE.runKernel(ArgMin, inputs, attrs);
    }
    var argMin = /* @__PURE__ */ op({ argMin_ });
    function asin_(x) {
      var $x = convertToTensor(x, "x", "asin");
      var inputs = { x: $x };
      return ENGINE.runKernel(Asin, inputs);
    }
    var asin = /* @__PURE__ */ op({ asin_ });
    function asinh_(x) {
      var $x = convertToTensor(x, "x", "asinh");
      var inputs = { x: $x };
      return ENGINE.runKernel(Asinh, inputs);
    }
    var asinh = /* @__PURE__ */ op({ asinh_ });
    function atan_(x) {
      var $x = convertToTensor(x, "x", "atan");
      var inputs = { x: $x };
      return ENGINE.runKernel(Atan, inputs);
    }
    var atan = /* @__PURE__ */ op({ atan_ });
    function atan2_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "atan2");
      var $b = convertToTensor(b, "b", "atan2");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Atan2, inputs);
    }
    var atan2 = /* @__PURE__ */ op({ atan2_ });
    function atanh_(x) {
      var $x = convertToTensor(x, "x", "atanh");
      var inputs = { x: $x };
      return ENGINE.runKernel(Atanh, inputs);
    }
    var atanh = /* @__PURE__ */ op({ atanh_ });
    function computeDilation2DInfo(inputShape, filterShape, strides, pad2, dataFormat, dilations) {
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      var inputChannels = inputShape[3];
      var $filterShape = __spreadArray(__spreadArray([], __read(filterShape), false), [inputChannels], false);
      var $dataFormat = convertConv2DDataFormat(dataFormat);
      return computeConv2DInfo(inputShape, $filterShape, strides, dilations, pad2, null, null, $dataFormat);
    }
    function computePool2DInfo(inShape, filterSize, strides, dilations, pad2, roundingMode, dataFormat) {
      if (dataFormat === void 0) {
        dataFormat = "channelsLast";
      }
      var _a = __read(parseTupleParam(filterSize), 2), filterHeight = _a[0], filterWidth = _a[1];
      var filterShape;
      if (dataFormat === "channelsLast") {
        filterShape = [filterHeight, filterWidth, inShape[3], inShape[3]];
      } else if (dataFormat === "channelsFirst") {
        filterShape = [filterHeight, filterWidth, inShape[1], inShape[1]];
      } else {
        throw new Error("Unknown dataFormat ".concat(dataFormat));
      }
      return computeConv2DInfo(inShape, filterShape, strides, dilations, pad2, roundingMode, false, dataFormat);
    }
    function computePool3DInfo(inShape, filterSize, strides, dilations, pad2, roundingMode, dataFormat) {
      if (dataFormat === void 0) {
        dataFormat = "NDHWC";
      }
      var _a = __read(parse3TupleParam(filterSize), 3), filterDepth = _a[0], filterHeight = _a[1], filterWidth = _a[2];
      var filterShape;
      var $dataFormat;
      if (dataFormat === "NDHWC") {
        $dataFormat = "channelsLast";
        filterShape = [filterDepth, filterHeight, filterWidth, inShape[4], inShape[4]];
      } else if (dataFormat === "NCDHW") {
        $dataFormat = "channelsFirst";
        filterShape = [filterDepth, filterHeight, filterWidth, inShape[1], inShape[1]];
      } else {
        throw new Error("Unknown dataFormat ".concat(dataFormat));
      }
      return computeConv3DInfo(inShape, filterShape, strides, dilations, pad2, false, $dataFormat, roundingMode);
    }
    function computeConv2DInfo(inShape, filterShape, strides, dilations, pad2, roundingMode, depthwise, dataFormat) {
      var _a, _b;
      if (depthwise === void 0) {
        depthwise = false;
      }
      if (dataFormat === void 0) {
        dataFormat = "channelsLast";
      }
      var _c = __read([-1, -1, -1, -1], 4), batchSize = _c[0], inHeight = _c[1], inWidth = _c[2], inChannels = _c[3];
      if (dataFormat === "channelsLast") {
        _a = __read(inShape, 4), batchSize = _a[0], inHeight = _a[1], inWidth = _a[2], inChannels = _a[3];
      } else if (dataFormat === "channelsFirst") {
        _b = __read(inShape, 4), batchSize = _b[0], inChannels = _b[1], inHeight = _b[2], inWidth = _b[3];
      } else {
        throw new Error("Unknown dataFormat ".concat(dataFormat));
      }
      var _d = __read(filterShape, 4), filterHeight = _d[0], filterWidth = _d[1], filterChannels = _d[3];
      var _e = __read(parseTupleParam(strides), 2), strideHeight = _e[0], strideWidth = _e[1];
      var _f = __read(parseTupleParam(dilations), 2), dilationHeight = _f[0], dilationWidth = _f[1];
      var effectiveFilterHeight = getEffectiveFilterSize(filterHeight, dilationHeight);
      var effectiveFilterWidth = getEffectiveFilterSize(filterWidth, dilationWidth);
      var _g = getPadAndOutInfo(pad2, inHeight, inWidth, strideHeight, strideWidth, effectiveFilterHeight, effectiveFilterWidth, roundingMode, dataFormat), padInfo = _g.padInfo, outHeight = _g.outHeight, outWidth = _g.outWidth;
      var outChannels = depthwise ? filterChannels * inChannels : filterChannels;
      var outShape;
      if (dataFormat === "channelsFirst") {
        outShape = [batchSize, outChannels, outHeight, outWidth];
      } else if (dataFormat === "channelsLast") {
        outShape = [batchSize, outHeight, outWidth, outChannels];
      }
      return {
        batchSize,
        dataFormat,
        inHeight,
        inWidth,
        inChannels,
        outHeight,
        outWidth,
        outChannels,
        padInfo,
        strideHeight,
        strideWidth,
        filterHeight,
        filterWidth,
        effectiveFilterHeight,
        effectiveFilterWidth,
        dilationHeight,
        dilationWidth,
        inShape,
        outShape,
        filterShape
      };
    }
    function computeConv3DInfo(inShape, filterShape, strides, dilations, pad2, depthwise, dataFormat, roundingMode) {
      var _a, _b;
      if (depthwise === void 0) {
        depthwise = false;
      }
      if (dataFormat === void 0) {
        dataFormat = "channelsLast";
      }
      var _c = __read([-1, -1, -1, -1, -1], 5), batchSize = _c[0], inDepth = _c[1], inHeight = _c[2], inWidth = _c[3], inChannels = _c[4];
      if (dataFormat === "channelsLast") {
        _a = __read(inShape, 5), batchSize = _a[0], inDepth = _a[1], inHeight = _a[2], inWidth = _a[3], inChannels = _a[4];
      } else if (dataFormat === "channelsFirst") {
        _b = __read(inShape, 5), batchSize = _b[0], inChannels = _b[1], inDepth = _b[2], inHeight = _b[3], inWidth = _b[4];
      } else {
        throw new Error("Unknown dataFormat ".concat(dataFormat));
      }
      var _d = __read(filterShape, 5), filterDepth = _d[0], filterHeight = _d[1], filterWidth = _d[2], filterChannels = _d[4];
      var _e = __read(parse3TupleParam(strides), 3), strideDepth = _e[0], strideHeight = _e[1], strideWidth = _e[2];
      var _f = __read(parse3TupleParam(dilations), 3), dilationDepth = _f[0], dilationHeight = _f[1], dilationWidth = _f[2];
      var effectiveFilterDepth = getEffectiveFilterSize(filterDepth, dilationDepth);
      var effectiveFilterHeight = getEffectiveFilterSize(filterHeight, dilationHeight);
      var effectiveFilterWidth = getEffectiveFilterSize(filterWidth, dilationWidth);
      var _g = get3DPadAndOutInfo(pad2, inDepth, inHeight, inWidth, strideDepth, strideHeight, strideWidth, effectiveFilterDepth, effectiveFilterHeight, effectiveFilterWidth, roundingMode), padInfo = _g.padInfo, outDepth = _g.outDepth, outHeight = _g.outHeight, outWidth = _g.outWidth;
      var outChannels = depthwise ? filterChannels * inChannels : filterChannels;
      var outShape;
      if (dataFormat === "channelsFirst") {
        outShape = [batchSize, outChannels, outDepth, outHeight, outWidth];
      } else if (dataFormat === "channelsLast") {
        outShape = [batchSize, outDepth, outHeight, outWidth, outChannels];
      }
      return {
        batchSize,
        dataFormat,
        inDepth,
        inHeight,
        inWidth,
        inChannels,
        outDepth,
        outHeight,
        outWidth,
        outChannels,
        padInfo,
        strideDepth,
        strideHeight,
        strideWidth,
        filterDepth,
        filterHeight,
        filterWidth,
        effectiveFilterDepth,
        effectiveFilterHeight,
        effectiveFilterWidth,
        dilationDepth,
        dilationHeight,
        dilationWidth,
        inShape,
        outShape,
        filterShape
      };
    }
    function computeOutputShape2D(inShape, fieldSize, stride, zeroPad, roundingMode) {
      if (zeroPad == null) {
        zeroPad = computeDefaultPad(inShape, fieldSize, stride);
      }
      var inputRows = inShape[0];
      var inputCols = inShape[1];
      var outputRows = round$1((inputRows - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
      var outputCols = round$1((inputCols - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
      return [outputRows, outputCols];
    }
    function computeOutputShape4D(inShape, filterShape, outChannels, strides, zeroPad, roundingMode) {
      if (zeroPad == null) {
        zeroPad = computeDefaultPad(inShape, filterShape[0], strides[0]);
      }
      var outShape = [0, 0, 0, outChannels];
      for (var index = 0; index < 3; index++) {
        if (inShape[index] + 2 * zeroPad >= filterShape[index]) {
          outShape[index] = round$1((inShape[index] - filterShape[index] + 2 * zeroPad) / strides[index] + 1, roundingMode);
        }
      }
      return outShape;
    }
    function computeDefaultPad(inputShape, fieldSize, stride, dilation) {
      if (dilation === void 0) {
        dilation = 1;
      }
      var effectiveFieldSize = getEffectiveFilterSize(fieldSize, dilation);
      return Math.floor((inputShape[0] * (stride - 1) - stride + effectiveFieldSize) / 2);
    }
    function parseTupleParam(param) {
      if (typeof param === "number") {
        return [param, param, param];
      }
      if (param.length === 2) {
        return [param[0], param[1], 1];
      }
      return param;
    }
    function parse3TupleParam(param) {
      return typeof param === "number" ? [param, param, param] : param;
    }
    function getEffectiveFilterSize(filterSize, dilation) {
      if (dilation <= 1) {
        return filterSize;
      }
      return filterSize + (filterSize - 1) * (dilation - 1);
    }
    function getPadAndOutInfo(pad2, inHeight, inWidth, strideHeight, strideWidth, filterHeight, filterWidth, roundingMode, dataFormat) {
      var padInfo;
      var outHeight;
      var outWidth;
      if (typeof pad2 === "number") {
        var padType = pad2 === 0 ? "VALID" : "NUMBER";
        padInfo = { top: pad2, bottom: pad2, left: pad2, right: pad2, type: padType };
        var outShape = computeOutputShape2D([inHeight, inWidth], filterHeight, strideHeight, pad2, roundingMode);
        outHeight = outShape[0];
        outWidth = outShape[1];
      } else if (pad2 === "same") {
        outHeight = Math.ceil(inHeight / strideHeight);
        outWidth = Math.ceil(inWidth / strideWidth);
        var padAlongHeight = Math.max(0, (outHeight - 1) * strideHeight + filterHeight - inHeight);
        var padAlongWidth = Math.max(0, (outWidth - 1) * strideWidth + filterWidth - inWidth);
        var top = Math.floor(padAlongHeight / 2);
        var bottom = padAlongHeight - top;
        var left = Math.floor(padAlongWidth / 2);
        var right = padAlongWidth - left;
        padInfo = { top, bottom, left, right, type: "SAME" };
      } else if (pad2 === "valid") {
        padInfo = { top: 0, bottom: 0, left: 0, right: 0, type: "VALID" };
        outHeight = Math.ceil((inHeight - filterHeight + 1) / strideHeight);
        outWidth = Math.ceil((inWidth - filterWidth + 1) / strideWidth);
      } else if (typeof pad2 === "object") {
        var top = dataFormat === "channelsLast" ? pad2[1][0] : pad2[2][0];
        var bottom = dataFormat === "channelsLast" ? pad2[1][1] : pad2[2][1];
        var left = dataFormat === "channelsLast" ? pad2[2][0] : pad2[3][0];
        var right = dataFormat === "channelsLast" ? pad2[2][1] : pad2[3][1];
        var padType = top === 0 && bottom === 0 && left === 0 && right === 0 ? "VALID" : "EXPLICIT";
        padInfo = { top, bottom, left, right, type: padType };
        outHeight = round$1((inHeight - filterHeight + top + bottom) / strideHeight + 1, roundingMode);
        outWidth = round$1((inWidth - filterWidth + left + right) / strideWidth + 1, roundingMode);
      } else {
        throw Error("Unknown padding parameter: ".concat(pad2));
      }
      return { padInfo, outHeight, outWidth };
    }
    function get3DPadAndOutInfo(pad2, inDepth, inHeight, inWidth, strideDepth, strideHeight, strideWidth, filterDepth, filterHeight, filterWidth, roundingMode) {
      var padInfo;
      var outDepth;
      var outHeight;
      var outWidth;
      if (pad2 === "valid") {
        pad2 = 0;
      }
      if (typeof pad2 === "number") {
        var padType = pad2 === 0 ? "VALID" : "NUMBER";
        padInfo = {
          top: pad2,
          bottom: pad2,
          left: pad2,
          right: pad2,
          front: pad2,
          back: pad2,
          type: padType
        };
        var outShape = computeOutputShape4D([inDepth, inHeight, inWidth, 1], [filterDepth, filterHeight, filterWidth], 1, [strideDepth, strideHeight, strideWidth], pad2, roundingMode);
        outDepth = outShape[0];
        outHeight = outShape[1];
        outWidth = outShape[2];
      } else if (pad2 === "same") {
        outDepth = Math.ceil(inDepth / strideDepth);
        outHeight = Math.ceil(inHeight / strideHeight);
        outWidth = Math.ceil(inWidth / strideWidth);
        var padAlongDepth = (outDepth - 1) * strideDepth + filterDepth - inDepth;
        var padAlongHeight = (outHeight - 1) * strideHeight + filterHeight - inHeight;
        var padAlongWidth = (outWidth - 1) * strideWidth + filterWidth - inWidth;
        var front = Math.floor(padAlongDepth / 2);
        var back = padAlongDepth - front;
        var top = Math.floor(padAlongHeight / 2);
        var bottom = padAlongHeight - top;
        var left = Math.floor(padAlongWidth / 2);
        var right = padAlongWidth - left;
        padInfo = { top, bottom, left, right, front, back, type: "SAME" };
      } else {
        throw Error("Unknown padding parameter: ".concat(pad2));
      }
      return { padInfo, outDepth, outHeight, outWidth };
    }
    function round$1(value, roundingMode) {
      if (!roundingMode) {
        return Math.trunc(value);
      }
      switch (roundingMode) {
        case "round":
          return Math.round(value);
        case "ceil":
          return Math.ceil(value);
        case "floor":
          return Math.floor(value);
        default:
          throw new Error("Unknown roundingMode ".concat(roundingMode));
      }
    }
    function tupleValuesAreOne(param) {
      var _a = __read(parseTupleParam(param), 3), dimA = _a[0], dimB = _a[1], dimC = _a[2];
      return dimA === 1 && dimB === 1 && dimC === 1;
    }
    function eitherStridesOrDilationsAreOne(strides, dilations) {
      return tupleValuesAreOne(strides) || tupleValuesAreOne(dilations);
    }
    function stridesOrDilationsArePositive(values) {
      return parseTupleParam(values).every(function(value) {
        return value > 0;
      });
    }
    function convertConv2DDataFormat(dataFormat) {
      if (dataFormat === "NHWC") {
        return "channelsLast";
      } else if (dataFormat === "NCHW") {
        return "channelsFirst";
      } else {
        throw new Error("Unknown dataFormat ".concat(dataFormat));
      }
    }
    function checkPadOnDimRoundingMode(opDesc, pad2, dimRoundingMode) {
      if (dimRoundingMode != null) {
        if (typeof pad2 === "string") {
          throw Error("Error in ".concat(opDesc, ": pad must be an integer when using ") + "dimRoundingMode ".concat(dimRoundingMode, " but got pad ").concat(pad2, "."));
        } else if (typeof pad2 === "number") {
          assert(isInt(pad2), function() {
            return "Error in ".concat(opDesc, ": pad must be an integer when using ") + "dimRoundingMode ".concat(dimRoundingMode, " but got pad ").concat(pad2, ".");
          });
        } else if (typeof pad2 === "object") {
          pad2.forEach(function(p) {
            p.forEach(function(v) {
              assert(isInt(v), function() {
                return "Error in ".concat(opDesc, ": pad must be an integer when using ") + "dimRoundingMode ".concat(dimRoundingMode, " but got pad ").concat(v, ".");
              });
            });
          });
        } else {
          throw Error("Error in ".concat(opDesc, ": Unknown padding parameter: ").concat(pad2));
        }
      }
    }
    function reshape_(x, shape) {
      var $x = convertToTensor(x, "x", "reshape", "string_or_numeric");
      var inputs = { x: $x };
      var attrs = { shape };
      return ENGINE.runKernel(Reshape, inputs, attrs);
    }
    var reshape = /* @__PURE__ */ op({ reshape_ });
    function avgPool_(x, filterSize, strides, pad2, dimRoundingMode) {
      var $x = convertToTensor(x, "x", "avgPool", "float32");
      var dilations = 1;
      assert(eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in avgPool: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, function() {
        return "Error in avgPool: x must be rank 4 but got rank ".concat(x4D.rank, ".");
      });
      checkPadOnDimRoundingMode("avgPool", pad2, dimRoundingMode);
      var inputs = { x: x4D };
      var attrs = { filterSize, strides, pad: pad2, dimRoundingMode };
      var res = ENGINE.runKernel(AvgPool, inputs, attrs);
      res = cast(res, $x.dtype);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var avgPool = /* @__PURE__ */ op({ avgPool_ });
    function avgPool3d_(x, filterSize, strides, pad2, dimRoundingMode, dataFormat) {
      if (dataFormat === void 0) {
        dataFormat = "NDHWC";
      }
      var $x = convertToTensor(x, "x", "avgPool3d", "float32");
      var x5D = $x;
      var reshapedTo5D = false;
      if ($x.rank === 4) {
        reshapedTo5D = true;
        x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
      }
      assert(x5D.rank === 5, function() {
        return "Error in avgPool3d: x must be rank 5 but got rank ".concat(x5D.rank, ".");
      });
      assert(dataFormat === "NDHWC", function() {
        return "Error in avgPool3d: Only NDHWC is currently supported, " + "but got dataFormat of ".concat(dataFormat);
      });
      assert(typeof strides === "number" && strides > 0 || Array.isArray(strides) && strides[0] > 0 && strides[1] > 0 && strides[2] > 0, function() {
        return "Error in avgPool3d: Stride must be > 0, but got '".concat(strides, "'");
      });
      checkPadOnDimRoundingMode("avgPool3d", pad2, dimRoundingMode);
      var inputs = { x: x5D };
      var attrs = { filterSize, strides, pad: pad2, dimRoundingMode, dataFormat };
      var res = ENGINE.runKernel(AvgPool3D, inputs, attrs);
      res = cast(res, x5D.dtype);
      if (reshapedTo5D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
      }
      return res;
    }
    var avgPool3d = /* @__PURE__ */ op({ avgPool3d_ });
    function concat_(tensors, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      assert(tensors.length >= 1, function() {
        return "Pass at least one tensor to concat";
      });
      var $tensors = convertToTensorArray(tensors, "tensors", "concat", "string_or_numeric");
      if ($tensors[0].dtype === "complex64") {
        $tensors.forEach(function(tensor2) {
          if (tensor2.dtype !== "complex64") {
            throw new Error("Cannot concatenate complex64 tensors with a tensor\n          with dtype ".concat(tensor2.dtype, ". "));
          }
        });
      }
      if ($tensors.length === 1) {
        return clone($tensors[0]);
      }
      var inputs = $tensors;
      var attr = { axis };
      return ENGINE.runKernel(Concat, inputs, attr);
    }
    var concat = /* @__PURE__ */ op({ concat_ });
    function matMul_(a, b, transposeA, transposeB) {
      var _a;
      if (transposeA === void 0) {
        transposeA = false;
      }
      if (transposeB === void 0) {
        transposeB = false;
      }
      var $a = convertToTensor(a, "a", "matMul");
      var $b = convertToTensor(b, "b", "matMul");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      var inputs = { a: $a, b: $b };
      var attrs = { transposeA, transposeB };
      return ENGINE.runKernel(BatchMatMul, inputs, attrs);
    }
    var matMul$1 = /* @__PURE__ */ op({ matMul_ });
    function sigmoid_(x) {
      var $x = convertToTensor(x, "x", "sigmoid", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Sigmoid, inputs);
    }
    var sigmoid = /* @__PURE__ */ op({ sigmoid_ });
    function slice_(x, begin, size) {
      var $x = convertToTensor(x, "x", "slice", "string_or_numeric");
      if ($x.rank === 0) {
        throw new Error("Slicing scalar is not possible");
      }
      var inputs = { x: $x };
      var attrs = { begin, size };
      return ENGINE.runKernel(Slice, inputs, attrs);
    }
    var slice = /* @__PURE__ */ op({ slice_ });
    function tanh_(x) {
      var $x = convertToTensor(x, "x", "tanh", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Tanh, inputs);
    }
    var tanh = /* @__PURE__ */ op({ tanh_ });
    function basicLSTMCell_(forgetBias, lstmKernel, lstmBias, data, c, h) {
      var $forgetBias = convertToTensor(forgetBias, "forgetBias", "basicLSTMCell");
      var $lstmKernel = convertToTensor(lstmKernel, "lstmKernel", "basicLSTMCell");
      var $lstmBias = convertToTensor(lstmBias, "lstmBias", "basicLSTMCell");
      var $data = convertToTensor(data, "data", "basicLSTMCell");
      var $c = convertToTensor(c, "c", "basicLSTMCell");
      var $h = convertToTensor(h, "h", "basicLSTMCell");
      var combined = concat([$data, $h], 1);
      var weighted = matMul$1(combined, $lstmKernel);
      var res = add(weighted, $lstmBias);
      var batchSize = res.shape[0];
      var sliceCols = res.shape[1] / 4;
      var sliceSize = [batchSize, sliceCols];
      var i = slice(res, [0, 0], sliceSize);
      var j = slice(res, [0, sliceCols], sliceSize);
      var f = slice(res, [0, sliceCols * 2], sliceSize);
      var o = slice(res, [0, sliceCols * 3], sliceSize);
      var newC = add(mul(sigmoid(i), tanh(j)), mul($c, sigmoid(add($forgetBias, f))));
      var newH = mul(tanh(newC), sigmoid(o));
      return [newC, newH];
    }
    var basicLSTMCell = /* @__PURE__ */ op({ basicLSTMCell_ });
    function batchToSpaceND_(x, blockShape, crops) {
      var $x = convertToTensor(x, "x", "batchToSpaceND");
      var prod2 = blockShape.reduce(function(a, b) {
        return a * b;
      });
      assert($x.rank >= 1 + blockShape.length, function() {
        return "input rank is ".concat($x.rank, " but should be > than blockShape.length ").concat(blockShape.length);
      });
      assert(crops.length === blockShape.length, function() {
        return "crops.length is ".concat(crops.length, " but should be equal to blockShape.length  ").concat(blockShape.length);
      });
      assert($x.shape[0] % prod2 === 0, function() {
        return "input tensor batch is ".concat($x.shape[0], " but is not divisible by the product of ") + "the elements of blockShape ".concat(blockShape.join(" * "), " === ").concat(prod2);
      });
      var inputs = { x: $x };
      var attrs = { blockShape, crops };
      return ENGINE.runKernel(BatchToSpaceND, inputs, attrs);
    }
    var batchToSpaceND = /* @__PURE__ */ op({ batchToSpaceND_ });
    function xAs4D(x) {
      var x4D;
      if (x.rank === 0 || x.rank === 1) {
        x4D = reshape(x, [1, 1, 1, x.size]);
      } else if (x.rank === 2) {
        x4D = reshape(x, [1, 1, x.shape[0], x.shape[1]]);
      } else if (x.rank === 3) {
        x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
      } else {
        x4D = x;
      }
      return x4D;
    }
    function batchNorm_(x, mean2, variance, offset, scale, varianceEpsilon) {
      if (varianceEpsilon == null) {
        varianceEpsilon = 1e-3;
      }
      var $x = convertToTensor(x, "x", "batchNorm");
      var $mean = convertToTensor(mean2, "mean", "batchNorm");
      var $variance = convertToTensor(variance, "variance", "batchNorm");
      var $scale;
      if (scale != null) {
        $scale = convertToTensor(scale, "scale", "batchNorm");
      }
      var $offset;
      if (offset != null) {
        $offset = convertToTensor(offset, "offset", "batchNorm");
      }
      assert($mean.rank === $variance.rank, function() {
        return "Batch normalization gradient requires mean and variance to have equal ranks.";
      });
      assert($offset == null || $mean.rank === $offset.rank, function() {
        return "Batch normalization gradient requires mean and offset to have equal ranks.";
      });
      assert($scale == null || $mean.rank === $scale.rank, function() {
        return "Batch normalization gradient requires mean and scale to have equal ranks.";
      });
      var x4D = xAs4D($x);
      var inputs = {
        x: x4D,
        scale: $scale,
        offset: $offset,
        mean: $mean,
        variance: $variance
      };
      var attrs = { varianceEpsilon };
      var res = ENGINE.runKernel(FusedBatchNorm, inputs, attrs);
      return reshape(res, $x.shape);
    }
    var batchNorm = /* @__PURE__ */ op({ batchNorm_ });
    function batchNorm2d_(x, mean2, variance, offset, scale, varianceEpsilon) {
      var $x = convertToTensor(x, "x", "batchNorm");
      var $mean = convertToTensor(mean2, "mean", "batchNorm");
      var $variance = convertToTensor(variance, "variance", "batchNorm");
      var $scale;
      if (scale != null) {
        $scale = convertToTensor(scale, "scale", "batchNorm");
      }
      var $offset;
      if (offset != null) {
        $offset = convertToTensor(offset, "offset", "batchNorm");
      }
      assert($x.rank === 2, function() {
        return "Error in batchNorm2D: x must be rank 2 but got rank " + "".concat($x.rank, ".");
      });
      assert($mean.rank === 2 || $mean.rank === 1, function() {
        return "Error in batchNorm2D: mean must be rank 2 or rank 1 but " + "got rank ".concat($mean.rank, ".");
      });
      assert($variance.rank === 2 || $variance.rank === 1, function() {
        return "Error in batchNorm2D: variance must be rank 2 or rank 1 " + "but got rank ".concat($variance.rank, ".");
      });
      if ($scale != null) {
        assert($scale.rank === 2 || $scale.rank === 1, function() {
          return "Error in batchNorm2D: scale must be rank 2 or rank 1 " + "but got rank ".concat($scale.rank, ".");
        });
      }
      if ($offset != null) {
        assert($offset.rank === 2 || $offset.rank === 1, function() {
          return "Error in batchNorm2D: offset must be rank 2 or rank 1 " + "but got rank ".concat($offset.rank, ".");
        });
      }
      return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);
    }
    var batchNorm2d = /* @__PURE__ */ op({ batchNorm2d_ });
    function batchNorm3d_(x, mean2, variance, offset, scale, varianceEpsilon) {
      var $x = convertToTensor(x, "x", "batchNorm");
      var $mean = convertToTensor(mean2, "mean", "batchNorm");
      var $variance = convertToTensor(variance, "variance", "batchNorm");
      var $scale;
      if (scale != null) {
        $scale = convertToTensor(scale, "scale", "batchNorm");
      }
      var $offset;
      if (offset != null) {
        $offset = convertToTensor(offset, "offset", "batchNorm");
      }
      assert($x.rank === 3, function() {
        return "Error in batchNorm3D: x must be rank 3 but got rank " + "".concat($x.rank, ".");
      });
      assert($mean.rank === 3 || $mean.rank === 1, function() {
        return "Error in batchNorm3D: mean must be rank 3 or rank 1 but " + "got rank ".concat($mean.rank, ".");
      });
      assert($variance.rank === 3 || $variance.rank === 1, function() {
        return "Error in batchNorm3D: variance must be rank 3 or rank 1 " + "but got rank ".concat($variance.rank, ".");
      });
      if ($scale != null) {
        assert($scale.rank === 3 || $scale.rank === 1, function() {
          return "Error in batchNorm3D: scale must be rank 3 or rank 1 " + "but got rank ".concat($scale.rank, ".");
        });
      }
      if ($offset != null) {
        assert($offset.rank === 3 || $offset.rank === 1, function() {
          return "Error in batchNorm3D: offset must be rank 3 or rank 1 " + "but got rank ".concat($offset.rank, ".");
        });
      }
      return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);
    }
    var batchNorm3d = /* @__PURE__ */ op({ batchNorm3d_ });
    function batchNorm4d_(x, mean2, variance, offset, scale, varianceEpsilon) {
      var $x = convertToTensor(x, "x", "batchNorm");
      var $mean = convertToTensor(mean2, "mean", "batchNorm");
      var $variance = convertToTensor(variance, "variance", "batchNorm");
      var $scale;
      if (scale != null) {
        $scale = convertToTensor(scale, "scale", "batchNorm");
      }
      var $offset;
      if (offset != null) {
        $offset = convertToTensor(offset, "offset", "batchNorm");
      }
      assert($x.rank === 4, function() {
        return "Error in batchNorm4D: x must be rank 4 but got rank " + "".concat($x.rank, ".");
      });
      assert($mean.rank === 4 || $mean.rank === 1, function() {
        return "Error in batchNorm4D: mean must be rank 4 or rank 1 but " + "got rank ".concat($mean.rank, ".");
      });
      assert($variance.rank === 4 || $variance.rank === 1, function() {
        return "Error in batchNorm4D: variance must be rank 4 or rank 1 " + "but got rank ".concat($variance.rank, ".");
      });
      if ($scale != null) {
        assert($scale.rank === 4 || $scale.rank === 1, function() {
          return "Error in batchNorm4D: scale must be rank 4 or rank 1 " + "but got rank ".concat($scale.rank, ".");
        });
      }
      if ($offset != null) {
        assert($offset.rank === 4 || $offset.rank === 1, function() {
          return "Error in batchNorm4D: offset must be rank 4 or rank 1 " + "but got rank ".concat($offset.rank, ".");
        });
      }
      return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);
    }
    var batchNorm4d = /* @__PURE__ */ op({ batchNorm4d_ });
    function bincount_(x, weights, size) {
      var $x = convertToTensor(x, "x", "bincount");
      var $weights = convertToTensor(weights, "weights", "bincount");
      assert($x.dtype === "int32", function() {
        return "Error in bincount: input " + "dtype must be int32, but got ".concat($x.dtype);
      });
      assert(size >= 0, function() {
        return "size must be non-negative, but got ".concat(size, ".");
      });
      assert($weights.size === $x.size || $weights.size === 0, function() {
        return "Error in bincount: weights must have the same size as input or" + "0-length, but got input shape: ".concat($x.shape, ", weights shape: ") + "".concat($weights.shape, ".");
      });
      var inputs = { x: $x, weights: $weights };
      var attrs = { size };
      return ENGINE.runKernel(Bincount, inputs, attrs);
    }
    var bincount = /* @__PURE__ */ op({ bincount_ });
    function bitwiseAnd_(x, y) {
      var $x = convertToTensor(x, "x", "bitwiseAnd");
      var $y = convertToTensor(y, "y", "bitwiseAnd");
      if (!arraysEqual($x.shape, $y.shape)) {
        throw new Error("BitwiseAnd: Tensors must have the same shape. x: ".concat($x.shape, ", y: ").concat($y.shape));
      }
      if ($x.dtype !== "int32" || $y.dtype !== "int32") {
        throw new Error("BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ".concat($x.dtype, " and type of y: ").concat($y.dtype));
      }
      var inputs = { a: $x, b: $y };
      return ENGINE.runKernel(BitwiseAnd, inputs);
    }
    var bitwiseAnd = /* @__PURE__ */ op({ bitwiseAnd_ });
    function broadcastArgs_(s0, s1) {
      var shape1Input = convertToTensor(s0, "s0", "broadcastArgs", "int32");
      var shape2Input = convertToTensor(s1, "s1", "broadcastArgs", "int32");
      if (shape1Input.rank !== 1) {
        throw new Error("broadcastArgs(): first input must be a vector (rank=1). " + "Has rank ".concat(shape1Input.rank));
      }
      if (shape2Input.rank !== 1) {
        throw new Error("broadcastArgs(): second input must be a vector (rank=1). " + "Has rank ".concat(shape2Input.rank));
      }
      var inputs = { s0: shape1Input, s1: shape2Input };
      return ENGINE.runKernel(BroadcastArgs, inputs);
    }
    var broadcastArgs = /* @__PURE__ */ op({ broadcastArgs_ });
    function broadcastTo_(x, shape) {
      var input = convertToTensor(x, "broadcastTo", "x");
      var xShape = input.shape;
      assertNonNegativeIntegerDimensions(shape);
      if (shape.length < input.rank) {
        throw new Error("broadcastTo(): shape.length=".concat(shape.length, " < input.rank=").concat(input.rank, "."));
      }
      if (shape.length > input.rank) {
        var newShape = input.shape.slice();
        while (newShape.length < shape.length) {
          newShape.unshift(1);
        }
        input = reshape(input, newShape);
      }
      var inputShape = input.shape;
      var reps = Array.from(shape);
      for (var i = shape.length - 1; i >= 0; i--) {
        if (inputShape[i] === shape[i]) {
          reps[i] = 1;
        } else if (input.shape[i] !== 1) {
          throw new Error("broadcastTo(): [".concat(xShape, "] cannot be broadcast to [").concat(shape, "]."));
        }
      }
      var axes = reps.map(function(n, i2) {
        return n > 1 ? i2 : -1;
      }).filter(function(i2) {
        return i2 >= 0;
      });
      if (axes.length === 0) {
        return clone(input);
      }
      var inputs = { x: input };
      var attrs = { reps };
      return ENGINE.runKernel(Tile, inputs, attrs);
    }
    var broadcastTo = /* @__PURE__ */ op({ broadcastTo_ });
    function ceil_(x) {
      var $x = convertToTensor(x, "x", "ceil", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Ceil, inputs);
    }
    var ceil = /* @__PURE__ */ op({ ceil_ });
    function fill(shape, value, dtype) {
      assertNonNegativeIntegerDimensions(shape);
      dtype = dtype || inferDtype(value);
      var attrs = { shape, value, dtype };
      return ENGINE.runKernel(Fill, {}, attrs);
    }
    function clipByValue_(x, clipValueMin, clipValueMax) {
      var $x = convertToTensor(x, "x", "clipByValue");
      assert(clipValueMin <= clipValueMax, function() {
        return "Error in clip: min (".concat(clipValueMin, ") must be ") + "less than or equal to max (".concat(clipValueMax, ").");
      });
      if (clipValueMin === clipValueMax) {
        return fill($x.shape, clipValueMin, $x.dtype);
      }
      var inputs = { x: $x };
      var attrs = { clipValueMin, clipValueMax };
      return ENGINE.runKernel(ClipByValue, inputs, attrs);
    }
    var clipByValue = /* @__PURE__ */ op({ clipByValue_ });
    function concat1d_(tensors) {
      return concat(
        tensors,
        0
        /* axis */
      );
    }
    var concat1d = /* @__PURE__ */ op({ concat1d_ });
    function concat2d_(tensors, axis) {
      return concat(tensors, axis);
    }
    var concat2d = /* @__PURE__ */ op({ concat2d_ });
    function concat3d_(tensors, axis) {
      return concat(tensors, axis);
    }
    var concat3d = /* @__PURE__ */ op({ concat3d_ });
    function concat4d_(tensors, axis) {
      return concat(tensors, axis);
    }
    var concat4d = /* @__PURE__ */ op({ concat4d_ });
    function conv2d_(x, filter, strides, pad2, dataFormat, dilations, dimRoundingMode) {
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      if (dilations === void 0) {
        dilations = [1, 1];
      }
      var $x = convertToTensor(x, "x", "conv2d", "float32");
      var $filter = convertToTensor(filter, "filter", "conv2d", "float32");
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, function() {
        return "Error in conv2d: input must be rank 4, but got rank ".concat(x4D.rank, ".");
      });
      assert($filter.rank === 4, function() {
        return "Error in conv2d: filter must be rank 4, but got rank " + "".concat($filter.rank, ".");
      });
      checkPadOnDimRoundingMode("conv2d", pad2, dimRoundingMode);
      var inDepth = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
      assert(inDepth === $filter.shape[2], function() {
        return "Error in conv2d: depth of input (".concat(inDepth, ") must match ") + "input depth for filter ".concat($filter.shape[2], ".");
      });
      assert(eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in conv2D: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      assert(stridesOrDilationsArePositive(dilations), function() {
        return "Error in conv2D: Dilated rates should be larger than 0.";
      });
      assert(stridesOrDilationsArePositive(strides), function() {
        return "Error in conv2D: Strides should be larger than 0.";
      });
      var inputs = { x: x4D, filter: $filter };
      var attrs = { strides, pad: pad2, dataFormat, dilations, dimRoundingMode };
      var res = ENGINE.runKernel(Conv2D, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var conv2d$1 = /* @__PURE__ */ op({ conv2d_ });
    function conv1d_(x, filter, stride, pad2, dataFormat, dilation, dimRoundingMode) {
      if (dataFormat === void 0) {
        dataFormat = "NWC";
      }
      if (dilation === void 0) {
        dilation = 1;
      }
      var $x = convertToTensor(x, "x", "conv1d");
      var $filter = convertToTensor(filter, "filter", "conv1d");
      var x3D = $x;
      var reshapedTo3D = false;
      if ($x.rank === 2) {
        reshapedTo3D = true;
        x3D = reshape($x, [1, $x.shape[0], $x.shape[1]]);
      }
      assert(x3D.rank === 3, function() {
        return "Error in conv1d: input must be rank 3, but got rank ".concat(x3D.rank, ".");
      });
      assert($filter.rank === 3, function() {
        return "Error in conv1d: filter must be rank 3, but got rank " + "".concat($filter.rank, ".");
      });
      checkPadOnDimRoundingMode("conv1d", pad2, dimRoundingMode);
      assert(x3D.shape[2] === $filter.shape[1], function() {
        return "Error in conv1d: depth of input (".concat(x3D.shape[2], ") must match ") + "input depth for filter ".concat($filter.shape[1], ".");
      });
      assert(eitherStridesOrDilationsAreOne(stride, dilation), function() {
        return "Error in conv1D: Either stride or dilation must be 1. " + "Got stride ".concat(stride, " and dilation '").concat(dilation, "'");
      });
      assert(stridesOrDilationsArePositive(dilation), function() {
        return "Error in conv1D: Dilated rates should be larger than 0.";
      });
      assert(stridesOrDilationsArePositive(stride), function() {
        return "Error in conv1D: Stride should be larger than 0.";
      });
      assert(dataFormat === "NWC", function() {
        return "Error in conv1d: got dataFormat of ".concat(dataFormat, " but only NWC is currently supported.");
      });
      var filter4D = reshape($filter, [1, $filter.shape[0], $filter.shape[1], $filter.shape[2]]);
      var input4D = reshape(x3D, [x3D.shape[0], 1, x3D.shape[1], x3D.shape[2]]);
      var strides = [1, stride];
      var dilations = [1, dilation];
      var conv2dDataFormat = "NHWC";
      var res = conv2d$1(input4D, filter4D, strides, pad2, conv2dDataFormat, dilations, dimRoundingMode);
      if (reshapedTo3D) {
        return reshape(res, [res.shape[2], res.shape[3]]);
      }
      return reshape(res, [res.shape[0], res.shape[2], res.shape[3]]);
    }
    var conv1d = /* @__PURE__ */ op({ conv1d_ });
    function conv2DBackpropInput_(xShape, dy, filter, strides, pad2, dataFormat, dimRoundingMode) {
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      assert(xShape.length === dy.rank, function() {
        return "Length of inShape " + "(".concat(xShape.length, ") and rank of dy (").concat(dy.rank, ") must match");
      });
      var xShape4D = xShape;
      var dy4D = dy;
      var reshapedTo4D = false;
      if (dy.rank === 3) {
        reshapedTo4D = true;
        dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
        xShape4D = [1, xShape[0], xShape[1], xShape[2]];
      }
      assert(xShape4D.length === 4, function() {
        return "Error in conv2dDerInput: inShape must be length 4, but got length " + "".concat(xShape4D.length, ".");
      });
      assert(dy4D.rank === 4, function() {
        return "Error in conv2dDerInput: dy must be rank 4, but got " + "rank ".concat(dy4D.rank);
      });
      assert(filter.rank === 4, function() {
        return "Error in conv2dDerInput: filter must be rank 4, but got " + "rank ".concat(filter.rank);
      });
      var inDepth = dataFormat === "NHWC" ? xShape4D[3] : xShape4D[1];
      var outDepth = dataFormat === "NHWC" ? dy4D.shape[3] : dy4D.shape[1];
      assert(inDepth === filter.shape[2], function() {
        return "Error in conv2dDerInput: depth of input (".concat(inDepth, ") must ") + "match input depth for filter ".concat(filter.shape[2], ".");
      });
      assert(outDepth === filter.shape[3], function() {
        return "Error in conv2dDerInput: depth of output (".concat(outDepth, ") must ") + "match output depth for filter ".concat(filter.shape[3], ".");
      });
      checkPadOnDimRoundingMode("conv2dDerInput", pad2, dimRoundingMode);
      var inputs = { dy: dy4D, filter };
      var attrs = { strides, pad: pad2, dataFormat, dimRoundingMode, inputShape: xShape4D };
      var res = ENGINE.runKernel(Conv2DBackpropInput, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var conv2DBackpropInput = /* @__PURE__ */ op({ conv2DBackpropInput_ });
    function conv2dTranspose_(x, filter, outputShape, strides, pad2, dimRoundingMode) {
      var $x = convertToTensor(x, "x", "conv2dTranspose");
      var $filter = convertToTensor(filter, "filter", "conv2dTranspose");
      return conv2DBackpropInput(outputShape, $x, $filter, strides, pad2, "NHWC", dimRoundingMode);
    }
    var conv2dTranspose = /* @__PURE__ */ op({ conv2dTranspose_ });
    function conv3d_(x, filter, strides, pad2, dataFormat, dilations) {
      if (dataFormat === void 0) {
        dataFormat = "NDHWC";
      }
      if (dilations === void 0) {
        dilations = [1, 1, 1];
      }
      var $x = convertToTensor(x, "x", "conv3d");
      var $filter = convertToTensor(filter, "filter", "conv3d");
      var x5D = $x;
      var reshapedTo5D = false;
      if ($x.rank === 4) {
        reshapedTo5D = true;
        x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
      }
      assert(x5D.rank === 5, function() {
        return "Error in conv3d: input must be rank 5, but got rank ".concat(x5D.rank, ".");
      });
      assert($filter.rank === 5, function() {
        return "Error in conv3d: filter must be rank 5, but got rank " + "".concat($filter.rank, ".");
      });
      assert(x5D.shape[4] === $filter.shape[3], function() {
        return "Error in conv3d: depth of input (".concat(x5D.shape[4], ") must match ") + "input depth for filter ".concat($filter.shape[3], ".");
      });
      assert(eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in conv3D: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      assert(dataFormat === "NDHWC", function() {
        return "Error in conv3d: got dataFormat of ".concat(dataFormat, " but only NDHWC is currently supported.");
      });
      assert(stridesOrDilationsArePositive(dilations), function() {
        return "Error in conv3D: Dilated rates should be larger than 0.";
      });
      assert(stridesOrDilationsArePositive(strides), function() {
        return "Error in conv3D: Strides should be larger than 0.";
      });
      var inputs = { x: x5D, filter: $filter };
      var attrs = { strides, pad: pad2, dataFormat, dilations };
      var res = ENGINE.runKernel(Conv3D, inputs, attrs);
      if (reshapedTo5D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
      }
      return res;
    }
    var conv3d = /* @__PURE__ */ op({ conv3d_ });
    function conv3DBackpropInput_(xShape, dy, filter, strides, pad2) {
      assert(xShape.length === dy.rank, function() {
        return "Length of inShape " + "(".concat(xShape.length, ") and rank of dy (").concat(dy.rank, ") must match");
      });
      var xShape5D = xShape;
      var dy5D = dy;
      var reshapedTo5D = false;
      if (dy.rank === 4) {
        reshapedTo5D = true;
        dy5D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);
        xShape5D = [1, xShape[0], xShape[1], xShape[2], xShape[3]];
      }
      var inDepth = xShape5D[4];
      var outDepth = dy5D.shape[4];
      assert(xShape5D.length === 5, function() {
        return "Error in conv3dDerInput: inShape must be length 5, but got length " + "".concat(xShape5D.length, ".");
      });
      assert(dy5D.rank === 5, function() {
        return "Error in conv3dDerInput: dy must be rank 5, but got " + "rank ".concat(dy5D.rank);
      });
      assert(filter.rank === 5, function() {
        return "Error in conv3dDerInput: filter must be rank 5, but got " + "rank ".concat(filter.rank);
      });
      assert(inDepth === filter.shape[3], function() {
        return "Error in conv3dDerInput: depth of input (".concat(inDepth, ") must ") + "match input depth for filter ".concat(filter.shape[3], ".");
      });
      assert(outDepth === filter.shape[4], function() {
        return "Error in conv3dDerInput: depth of output (".concat(outDepth, ") must ") + "match output depth for filter ".concat(filter.shape[4], ".");
      });
      var inputs = { dy: dy5D, filter };
      var attrs = { pad: pad2, strides, inputShape: xShape5D };
      var res = ENGINE.runKernel(Conv3DBackpropInputV2, inputs, attrs);
      if (reshapedTo5D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
      }
      return res;
    }
    var conv3DBackpropInput = /* @__PURE__ */ op({ conv3DBackpropInput_ });
    function conv3dTranspose_(x, filter, outputShape, strides, pad2) {
      var $x = convertToTensor(x, "x", "conv3dTranspose");
      var $filter = convertToTensor(filter, "filter", "conv3dTranspose");
      return conv3DBackpropInput(outputShape, $x, $filter, strides, pad2);
    }
    var conv3dTranspose = /* @__PURE__ */ op({ conv3dTranspose_ });
    function cos_(x) {
      var $x = convertToTensor(x, "x", "cos", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Cos, inputs);
    }
    var cos = /* @__PURE__ */ op({ cos_ });
    function cosh_(x) {
      var $x = convertToTensor(x, "x", "cosh", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Cosh, inputs);
    }
    var cosh = /* @__PURE__ */ op({ cosh_ });
    function cumprod_(x, axis, exclusive, reverse2) {
      if (axis === void 0) {
        axis = 0;
      }
      if (exclusive === void 0) {
        exclusive = false;
      }
      if (reverse2 === void 0) {
        reverse2 = false;
      }
      var $x = convertToTensor(x, "x", "cumprod");
      var inputs = { x: $x };
      var attrs = { axis, exclusive, reverse: reverse2 };
      return ENGINE.runKernel(Cumprod, inputs, attrs);
    }
    var cumprod = /* @__PURE__ */ op({ cumprod_ });
    function cumsum_(x, axis, exclusive, reverse2) {
      if (axis === void 0) {
        axis = 0;
      }
      if (exclusive === void 0) {
        exclusive = false;
      }
      if (reverse2 === void 0) {
        reverse2 = false;
      }
      var $x = convertToTensor(x, "x", "cumsum");
      var inputs = { x: $x };
      var attrs = { axis, exclusive, reverse: reverse2 };
      return ENGINE.runKernel(Cumsum, inputs, attrs);
    }
    var cumsum = /* @__PURE__ */ op({ cumsum_ });
    function denseBincount_(x, weights, size, binaryOutput) {
      if (binaryOutput === void 0) {
        binaryOutput = false;
      }
      var $x = convertToTensor(x, "x", "denseBincount");
      var $weights = convertToTensor(weights, "weights", "denseBincount");
      assert($x.dtype === "int32", function() {
        return "Error in denseBincount: input " + "dtype must be int32, but got ".concat($x.dtype);
      });
      assert($x.rank <= 2, function() {
        return "Error in denseBincount: input must be at most rank 2, but got " + "rank ".concat($x.rank, ".");
      });
      assert(size >= 0, function() {
        return "size must be non-negative, but got ".concat(size, ".");
      });
      assert($weights.size === $x.size || $weights.size === 0, function() {
        return "Error in denseBincount: weights must have the same shape as x or " + "0-length, but got x shape: ".concat($x.shape, ", weights shape: ") + "".concat($weights.shape, ".");
      });
      var inputs = { x: $x, weights: $weights };
      var attrs = { size, binaryOutput };
      return ENGINE.runKernel(DenseBincount, inputs, attrs);
    }
    var denseBincount = /* @__PURE__ */ op({ denseBincount_ });
    function depthToSpace_(x, blockSize, dataFormat) {
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      var $x = convertToTensor(x, "x", "depthToSpace", "float32");
      var inputHeight = dataFormat === "NHWC" ? $x.shape[1] : $x.shape[2];
      var inputWidth = dataFormat === "NHWC" ? $x.shape[2] : $x.shape[3];
      var inputDepth = dataFormat === "NHWC" ? $x.shape[3] : $x.shape[1];
      assert(blockSize > 1, function() {
        return "blockSize should be > 1 for depthToSpace, but was: ".concat(blockSize);
      });
      assert(inputHeight * blockSize >= 0, function() {
        return "Negative dimension size caused by overflow when multiplying\n    ".concat(inputHeight, " and ").concat(blockSize, "  for depthToSpace with input shape\n    ").concat($x.shape);
      });
      assert(inputWidth * blockSize >= 0, function() {
        return "Negative dimension size caused by overflow when multiplying\n    ".concat(inputWidth, " and ").concat(blockSize, " for depthToSpace with input shape\n        ").concat($x.shape);
      });
      assert(inputDepth % (blockSize * blockSize) === 0, function() {
        return "Dimension size must be evenly divisible by ".concat(blockSize * blockSize, " but is ").concat(inputDepth, " for depthToSpace with input shape ").concat($x.shape);
      });
      var inputs = { x: $x };
      var attrs = { blockSize, dataFormat };
      return ENGINE.runKernel(DepthToSpace, inputs, attrs);
    }
    var depthToSpace = /* @__PURE__ */ op({ depthToSpace_ });
    function depthwiseConv2d_(x, filter, strides, pad2, dataFormat, dilations, dimRoundingMode) {
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      if (dilations === void 0) {
        dilations = [1, 1];
      }
      var $x = convertToTensor(x, "x", "depthwiseConv2d", "float32");
      var $filter = convertToTensor(filter, "filter", "depthwiseConv2d", "float32");
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, function() {
        return "Error in depthwiseConv2d: input must be rank 4, but got " + "rank ".concat(x4D.rank, ".");
      });
      assert($filter.rank === 4, function() {
        return "Error in depthwiseConv2d: filter must be rank 4, but got rank " + "".concat($filter.rank, ".");
      });
      var inChannels = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
      assert(inChannels === $filter.shape[2], function() {
        return "Error in depthwiseConv2d: number of input channels " + "(".concat(inChannels, ") must match the inChannels dimension in ") + "filter ".concat($filter.shape[2], ".");
      });
      checkPadOnDimRoundingMode("depthwiseConv2d", pad2, dimRoundingMode);
      var inputs = { x: x4D, filter: $filter };
      var attrs = { strides, pad: pad2, dataFormat, dilations, dimRoundingMode };
      var res = ENGINE.runKernel(DepthwiseConv2dNative, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var depthwiseConv2d$1 = /* @__PURE__ */ op({ depthwiseConv2d_ });
    function diag_(x) {
      var $x = convertToTensor(x, "x", "diag");
      var inputs = { x: $x };
      return ENGINE.runKernel(Diag, inputs);
    }
    var diag = /* @__PURE__ */ op({ diag_ });
    function dilation2d_(x, filter, strides, pad2, dilations, dataFormat) {
      if (dilations === void 0) {
        dilations = [1, 1];
      }
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      var $x = convertToTensor(x, "x", "dilation2d");
      var $filter = convertToTensor(filter, "filter", "dilation2d");
      assert($x.rank === 3 || $x.rank === 4, function() {
        return "Error in dilation2d: input must be rank 3 or 4, but got rank " + "".concat($x.rank, ".");
      });
      assert($filter.rank === 3, function() {
        return "Error in dilation2d: filter must be rank 3, but got rank " + "".concat($filter.rank, ".");
      });
      assert(dataFormat === "NHWC", function() {
        return "Error in dilation2d: Only NHWC is currently supported, " + "but got dataFormat of ".concat(dataFormat);
      });
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
        reshapedTo4D = true;
      }
      assert(x4D.shape[3] === $filter.shape[2], function() {
        return "Error in dilation2d:  input and filter must have the same depth: ".concat(x4D.shape[3], " vs ").concat($filter.shape[2]);
      });
      var inputs = { x: x4D, filter: $filter };
      var attrs = { strides, pad: pad2, dilations };
      var res = ENGINE.runKernel(Dilation2D, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var dilation2d = /* @__PURE__ */ op({ dilation2d_ });
    function getBroadcastDims(inShape, outShape) {
      var inRank = inShape.length;
      var dims = [];
      for (var i = 0; i < inRank; i++) {
        var dim = inRank - 1 - i;
        var a = inShape[dim] || 1;
        var b = outShape[outShape.length - 1 - i] || 1;
        if (b > 1 && a === 1) {
          dims.unshift(dim);
        }
      }
      return dims;
    }
    function getReductionAxes(inShape, outShape) {
      var result = [];
      for (var i = 0; i < outShape.length; i++) {
        var inDim = inShape[inShape.length - i - 1];
        var outAxis = outShape.length - i - 1;
        var outDim = outShape[outAxis];
        if (inDim == null || inDim === 1 && outDim > 1) {
          result.unshift(outAxis);
        }
      }
      return result;
    }
    function assertAndGetBroadcastShape(shapeA, shapeB) {
      var l = Math.max(shapeA.length, shapeB.length);
      var result = new Array(l);
      for (var i = 0; i < l; i++) {
        var a = shapeA[shapeA.length - i - 1];
        if (a == null) {
          a = 1;
        }
        var b = shapeB[shapeB.length - i - 1];
        if (b == null) {
          b = 1;
        }
        if (a === 1) {
          result[l - i - 1] = b;
        } else if (b === 1) {
          result[l - i - 1] = a;
        } else if (a !== b) {
          var errMsg = "Operands could not be broadcast together with shapes " + "".concat(shapeA, " and ").concat(shapeB, ".");
          throw Error(errMsg);
        } else {
          result[l - i - 1] = a;
        }
      }
      return result;
    }
    var broadcast_util = {
      __proto__: null,
      assertAndGetBroadcastShape,
      getBroadcastDims,
      getReductionAxes
    };
    function equal_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "equal", "string_or_numeric");
      var $b = convertToTensor(b, "b", "equal", "string_or_numeric");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Equal, inputs);
    }
    var equal = /* @__PURE__ */ op({ equal_ });
    function where_(condition, a, b) {
      var $a = convertToTensor(a, "a", "where");
      var $b = convertToTensor(b, "b", "where");
      var $condition = convertToTensor(condition, "condition", "where", "bool");
      var broadcastShape = assertAndGetBroadcastShape(assertAndGetBroadcastShape($condition.shape, $a.shape), $b.shape);
      var $broadcastedCondition = broadcastTo($condition, broadcastShape);
      var $broadcastedA = broadcastTo($a, broadcastShape);
      var $broadcastedB = broadcastTo($b, broadcastShape);
      var inputs = {
        condition: $broadcastedCondition,
        t: $broadcastedA,
        e: $broadcastedB
      };
      return ENGINE.runKernel(Select, inputs);
    }
    var where = /* @__PURE__ */ op({ where_ });
    function zerosLike_(x) {
      var $x = convertToTensor(x, "x", "zerosLike");
      var inputs = { x: $x };
      return ENGINE.runKernel(ZerosLike, inputs);
    }
    var zerosLike = /* @__PURE__ */ op({ zerosLike_ });
    function divNoNan_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "div");
      var $b = convertToTensor(b, "b", "div");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      var divResult = div($a, $b);
      var zeros2 = zerosLike(divResult);
      var bEqualsZero = equal($b, zeros2);
      return where(bEqualsZero, zeros2, divResult);
    }
    var divNoNan = /* @__PURE__ */ op({ divNoNan_ });
    function dot_(t1, t2) {
      var $t1 = convertToTensor(t1, "t1", "dot");
      var $t2 = convertToTensor(t2, "t2", "dot");
      assert(($t1.rank === 1 || $t1.rank === 2) && ($t2.rank === 1 || $t2.rank === 2), function() {
        return "Error in dot: inputs must all be rank 1 or 2, but got ranks " + "".concat($t1.rank, " and ").concat($t2.rank, ".");
      });
      var t1Inner = $t1.rank === 1 ? $t1.size : $t1.shape[1];
      var t2Inner = $t2.rank === 1 ? $t2.size : $t2.shape[0];
      assert(t1Inner === t2Inner, function() {
        return "Error in dot: inner dimensions of inputs must match, but got " + "".concat(t1Inner, " and ").concat(t2Inner, ".");
      });
      if ($t1.rank === 1 && $t2.rank === 1) {
        var t12D = reshape($t1, [1, -1]);
        var t22D = reshape($t2, [-1, 1]);
        var t1t2 = matMul$1(t12D, t22D);
        return reshape(t1t2, []);
      } else if ($t1.rank === 1 && $t2.rank === 2) {
        var t12D = reshape($t1, [1, -1]);
        var t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);
        var t1t2 = matMul$1(t12D, t22D);
        return reshape(t1t2, [t1t2.size]);
      } else if ($t1.rank === 2 && $t2.rank === 1) {
        var t22D = reshape($t2, [-1, 1]);
        var t1t2 = matMul$1($t1, t22D);
        return reshape(t1t2, [t1t2.size]);
      } else {
        var t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);
        var t1t2 = matMul$1($t1, t22D);
        return t1t2;
      }
    }
    var dot = /* @__PURE__ */ op({ dot_ });
    function einsum_(equation) {
      var tensors = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        tensors[_i - 1] = arguments[_i];
      }
      var $tensors = tensors.map(function(t, i) {
        return convertToTensor(t, "tensors".concat(i), "einsum");
      });
      var attrs = { equation };
      return ENGINE.runKernel(Einsum, $tensors, attrs);
    }
    var einsum = /* @__PURE__ */ op({ einsum_ });
    function elu_(x) {
      var $x = convertToTensor(x, "x", "elu", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Elu, inputs);
    }
    var elu = /* @__PURE__ */ op({ elu_ });
    function ensureShape_(x, shape) {
      var $x = convertToTensor(x, "x", "ensureShape", "string_or_numeric");
      if (!arraysEqualWithNull($x.shape, shape)) {
        throw new Error("EnsureShape: Shape of tensor ".concat($x.shape, " is not compatible with expected shape ").concat(shape));
      }
      return x;
    }
    var ensureShape = /* @__PURE__ */ op({ ensureShape_ });
    function erf_(x) {
      var $x = convertToTensor(x, "x", "erf");
      assert($x.dtype === "int32" || $x.dtype === "float32", function() {
        return "Input dtype must be `int32` or `float32`.";
      });
      if ($x.dtype === "int32") {
        $x = cast($x, "float32");
      }
      var inputs = { x: $x };
      return ENGINE.runKernel(Erf, inputs);
    }
    var erf = /* @__PURE__ */ op({ erf_ });
    function axesAreInnerMostDims(axes, rank) {
      for (var i = 0; i < axes.length; ++i) {
        if (axes[axes.length - i - 1] !== rank - 1 - i) {
          return false;
        }
      }
      return true;
    }
    function combineLocations(outputLoc, reduceLoc, axes) {
      var rank = outputLoc.length + reduceLoc.length;
      var loc = [];
      var outIdx = 0;
      var reduceIdx = 0;
      for (var dim = 0; dim < rank; dim++) {
        if (axes.indexOf(dim) === -1) {
          loc.push(outputLoc[outIdx++]);
        } else {
          loc.push(reduceLoc[reduceIdx++]);
        }
      }
      return loc;
    }
    function computeOutAndReduceShapes(aShape, axes) {
      var outShape = [];
      var rank = aShape.length;
      for (var dim = 0; dim < rank; dim++) {
        if (axes.indexOf(dim) === -1) {
          outShape.push(aShape[dim]);
        }
      }
      var reduceShape = axes.map(function(dim2) {
        return aShape[dim2];
      });
      return [outShape, reduceShape];
    }
    function expandShapeToKeepDim(shape, axes) {
      var reduceSubShape = axes.map(function(x) {
        return 1;
      });
      return combineLocations(shape, reduceSubShape, axes);
    }
    function assertAxesAreInnerMostDims(msg, axes, rank) {
      assert(axesAreInnerMostDims(axes, rank), function() {
        return "".concat(msg, " supports only inner-most axes for now. ") + "Got axes ".concat(axes, " and rank-").concat(rank, " input.");
      });
    }
    function getAxesPermutation(axes, rank) {
      if (axesAreInnerMostDims(axes, rank)) {
        return null;
      }
      var result = [];
      for (var i = 0; i < rank; ++i) {
        if (axes.indexOf(i) === -1) {
          result.push(i);
        }
      }
      axes.forEach(function(axis) {
        return result.push(axis);
      });
      return result;
    }
    function getUndoAxesPermutation(axes) {
      return axes.map(function(axis, i) {
        return [i, axis];
      }).sort(function(a, b) {
        return a[1] - b[1];
      }).map(function(x) {
        return x[0];
      });
    }
    function getInnerMostAxes(numAxes, rank) {
      var res = [];
      for (var i = rank - numAxes; i < rank; ++i) {
        res.push(i);
      }
      return res;
    }
    function max_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "max");
      var inputs = { x: $x };
      var attrs = { reductionIndices: axis, keepDims };
      return ENGINE.runKernel(Max, inputs, attrs);
    }
    var max = /* @__PURE__ */ op({ max_ });
    function min_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "min");
      var inputs = { x: $x };
      var attrs = { axis, keepDims };
      return ENGINE.runKernel(Min, inputs, attrs);
    }
    var min = /* @__PURE__ */ op({ min_ });
    function pow_(base, exp2) {
      var _a;
      var $base = convertToTensor(base, "base", "pow");
      var $exp = convertToTensor(exp2, "exp", "pow");
      _a = __read(makeTypesMatch($base, $exp), 2), $base = _a[0], $exp = _a[1];
      var inputs = { a: $base, b: $exp };
      return ENGINE.runKernel(Pow, inputs);
    }
    var pow = /* @__PURE__ */ op({ pow_ });
    function scalar(value, dtype) {
      if ((isTypedArray(value) && dtype !== "string" || Array.isArray(value)) && dtype !== "complex64") {
        throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");
      }
      if (dtype === "string" && isTypedArray(value) && !(value instanceof Uint8Array)) {
        throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");
      }
      var shape = [];
      var inferredShape = [];
      return makeTensor(value, shape, inferredShape, dtype);
    }
    function sqrt_(x) {
      var $x = convertToTensor(x, "x", "sqrt", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Sqrt, inputs);
    }
    var sqrt = /* @__PURE__ */ op({ sqrt_ });
    function square_(x) {
      var $x = convertToTensor(x, "x", "square");
      var attrs = {};
      return ENGINE.runKernel("Square", { x: $x }, attrs);
    }
    var square = /* @__PURE__ */ op({ square_ });
    function sum_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "sum");
      if ($x.dtype === "bool") {
        $x = cast($x, "int32");
      }
      var inputs = { x: $x };
      var attrs = { axis, keepDims };
      return ENGINE.runKernel(Sum, inputs, attrs);
    }
    var sum = /* @__PURE__ */ op({ sum_ });
    function norm_(x, ord, axis, keepDims) {
      if (ord === void 0) {
        ord = "euclidean";
      }
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      x = convertToTensor(x, "x", "norm");
      var norm2 = normImpl(x, ord, axis);
      var keepDimsShape = norm2.shape;
      if (keepDims) {
        var axes = parseAxisParam(axis, x.shape);
        keepDimsShape = expandShapeToKeepDim(norm2.shape, axes);
      }
      return reshape(norm2, keepDimsShape);
    }
    function normImpl(x, p, axis) {
      if (axis === void 0) {
        axis = null;
      }
      if (x.rank === 0) {
        return abs(x);
      }
      if (x.rank !== 1 && axis === null) {
        return normImpl(reshape(x, [-1]), p, axis);
      }
      if (x.rank === 1 || typeof axis === "number" || Array.isArray(axis) && axis.length === 1) {
        if (p === 1) {
          return sum(abs(x), axis);
        }
        if (p === Infinity) {
          return max(abs(x), axis);
        }
        if (p === -Infinity) {
          return min(abs(x), axis);
        }
        if (p === "euclidean" || p === 2) {
          return sqrt(sum(pow(abs(x), scalar(2, "int32")), axis));
        }
        throw new Error("Error in norm: invalid ord value: ".concat(p));
      }
      if (Array.isArray(axis) && axis.length === 2) {
        if (p === 1) {
          return max(sum(abs(x), axis[0]), axis[1] - 1);
        }
        if (p === Infinity) {
          return max(sum(abs(x), axis[1]), axis[0]);
        }
        if (p === -Infinity) {
          return min(sum(abs(x), axis[1]), axis[0]);
        }
        if (p === "fro" || p === "euclidean") {
          return sqrt(sum(square(x), axis));
        }
        throw new Error("Error in norm: invalid ord value: ".concat(p));
      }
      throw new Error("Error in norm: invalid axis: ".concat(axis));
    }
    var norm = /* @__PURE__ */ op({ norm_ });
    function euclideanNorm_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      return norm(x, "euclidean", axis, keepDims);
    }
    var euclideanNorm = /* @__PURE__ */ op({ euclideanNorm_ });
    function exp_(x) {
      var $x = convertToTensor(x, "x", "exp");
      var inputs = { x: $x };
      return ENGINE.runKernel(Exp, inputs);
    }
    var exp = /* @__PURE__ */ op({ exp_ });
    function expandDims_(x, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $x = convertToTensor(x, "x", "expandDims", "string_or_numeric");
      assert(axis <= $x.rank, function() {
        return "Axis must be <= rank of the tensor";
      });
      var inputs = { input: $x };
      var attrs = { dim: axis };
      return ENGINE.runKernel(ExpandDims, inputs, attrs);
    }
    var expandDims = /* @__PURE__ */ op({ expandDims_ });
    function expm1_(x) {
      var $x = convertToTensor(x, "x", "expm1");
      var inputs = { x: $x };
      return ENGINE.runKernel(Expm1, inputs);
    }
    var expm1 = /* @__PURE__ */ op({ expm1_ });
    function tile_(x, reps) {
      var $x = convertToTensor(x, "x", "tile", "string_or_numeric");
      assert($x.rank === reps.length, function() {
        return "Error in transpose: rank of input ".concat($x.rank, " ") + "must match length of reps ".concat(reps, ".");
      });
      var inputs = { x: $x };
      var attrs = { reps };
      return ENGINE.runKernel(Tile, inputs, attrs);
    }
    var tile = /* @__PURE__ */ op({ tile_ });
    function eye_(numRows, numColumns, batchShape, dtype) {
      if (dtype === void 0) {
        dtype = "float32";
      }
      if (numColumns == null) {
        numColumns = numRows;
      }
      var buff = buffer([numRows, numColumns], dtype);
      var n = numRows <= numColumns ? numRows : numColumns;
      for (var i = 0; i < n; ++i) {
        buff.set(1, i, i);
      }
      var out = reshape(buff.toTensor(), [numRows, numColumns]);
      if (batchShape == null) {
        return out;
      } else {
        if (batchShape.length === 1) {
          return tile(expandDims(out, 0), [batchShape[0], 1, 1]);
        } else if (batchShape.length === 2) {
          return tile(expandDims(expandDims(out, 0), 0), [batchShape[0], batchShape[1], 1, 1]);
        } else if (batchShape.length === 3) {
          return tile(expandDims(expandDims(expandDims(out, 0), 0), 0), [
            batchShape[0],
            batchShape[1],
            batchShape[2],
            1,
            1
          ]);
        } else {
          throw new Error("eye() currently supports only 1D and 2D " + // tslint:disable-next-line:no-any
          "batchShapes, but received ".concat(batchShape.length, "D."));
        }
      }
    }
    var eye = /* @__PURE__ */ op({ eye_ });
    function floor_(x) {
      var $x = convertToTensor(x, "x", "floor", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Floor, inputs);
    }
    var floor = /* @__PURE__ */ op({ floor_ });
    function gather_(x, indices, axis, batchDims) {
      if (axis === void 0) {
        axis = 0;
      }
      if (batchDims === void 0) {
        batchDims = 0;
      }
      var $x = convertToTensor(x, "x", "gather");
      var $indices = convertToTensor(indices, "indices", "gather", "int32");
      var inputs = { x: $x, indices: $indices };
      var attrs = { axis, batchDims };
      return ENGINE.runKernel(GatherV2, inputs, attrs);
    }
    var gather = /* @__PURE__ */ op({ gather_ });
    function greater_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "greater", "string_or_numeric");
      var $b = convertToTensor(b, "b", "greater", "string_or_numeric");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Greater, inputs);
    }
    var greater = /* @__PURE__ */ op({ greater_ });
    function greaterEqual_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "greaterEqual", "string_or_numeric");
      var $b = convertToTensor(b, "b", "greaterEqual", "string_or_numeric");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(GreaterEqual, inputs);
    }
    var greaterEqual = /* @__PURE__ */ op({ greaterEqual_ });
    function imag_(input) {
      var $input = convertToTensor(input, "input", "imag");
      var inputs = { input: $input };
      return ENGINE.runKernel(Imag, inputs);
    }
    var imag = /* @__PURE__ */ op({ imag_ });
    function isFinite_(x) {
      var $x = convertToTensor(x, "x", "isFinite");
      var inputs = { x: $x };
      return ENGINE.runKernel(IsFinite, inputs);
    }
    var isFinite$1 = /* @__PURE__ */ op({ isFinite_ });
    function isInf_(x) {
      var $x = convertToTensor(x, "x", "isInf");
      var inputs = { x: $x };
      return ENGINE.runKernel(IsInf, inputs);
    }
    var isInf = /* @__PURE__ */ op({ isInf_ });
    function isNaN_(x) {
      var $x = convertToTensor(x, "x", "isNaN");
      var inputs = { x: $x };
      return ENGINE.runKernel(IsNan, inputs);
    }
    var isNaN$1 = /* @__PURE__ */ op({ isNaN_ });
    function leakyRelu_(x, alpha) {
      if (alpha === void 0) {
        alpha = 0.2;
      }
      var $x = convertToTensor(x, "x", "leakyRelu");
      var inputs = { x: $x };
      var attrs = { alpha };
      return ENGINE.runKernel(LeakyRelu, inputs, attrs);
    }
    var leakyRelu = /* @__PURE__ */ op({ leakyRelu_ });
    function less_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "less", "string_or_numeric");
      var $b = convertToTensor(b, "b", "less", "string_or_numeric");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Less, inputs);
    }
    var less = /* @__PURE__ */ op({ less_ });
    function lessEqual_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "lessEqual", "string_or_numeric");
      var $b = convertToTensor(b, "b", "lessEqual", "string_or_numeric");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(LessEqual, inputs);
    }
    var lessEqual = /* @__PURE__ */ op({ lessEqual_ });
    function linspace(start, stop, num) {
      if (num <= 0) {
        throw new Error("The number of values should be positive.");
      }
      var attrs = { start, stop, num };
      return ENGINE.runKernel(LinSpace, {}, attrs);
    }
    function localResponseNormalization_(x, depthRadius, bias, alpha, beta) {
      if (depthRadius === void 0) {
        depthRadius = 5;
      }
      if (bias === void 0) {
        bias = 1;
      }
      if (alpha === void 0) {
        alpha = 1;
      }
      if (beta === void 0) {
        beta = 0.5;
      }
      var $x = convertToTensor(x, "x", "localResponseNormalization");
      assert($x.rank === 4 || $x.rank === 3, function() {
        return "Error in localResponseNormalization: x must be rank 3 or 4 but got\n               rank ".concat($x.rank, ".");
      });
      assert(isInt(depthRadius), function() {
        return "Error in localResponseNormalization: depthRadius must be an " + "integer but got depthRadius ".concat(depthRadius, ".");
      });
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      var inputs = { x: x4D };
      var attrs = { depthRadius, bias, alpha, beta };
      var res = ENGINE.runKernel(LRN, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      } else {
        return res;
      }
    }
    var localResponseNormalization = /* @__PURE__ */ op({ localResponseNormalization_ });
    function log_(x) {
      var $x = convertToTensor(x, "x", "log", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Log, inputs);
    }
    var log = /* @__PURE__ */ op({ log_ });
    function log1p_(x) {
      var $x = convertToTensor(x, "x", "log1p");
      var inputs = { x: $x };
      return ENGINE.runKernel(Log1p, inputs);
    }
    var log1p = /* @__PURE__ */ op({ log1p_ });
    function grad(f) {
      assert(isFunction(f), function() {
        return "The f passed in grad(f) must be a function";
      });
      return function(x, dy) {
        var $x = convertToTensor(x, "x", "tf.grad", "string_or_numeric");
        var $dy = dy != null ? convertToTensor(dy, "dy", "tf.grad") : null;
        return ENGINE.tidy(function() {
          var _a = ENGINE.gradients(function() {
            return f($x);
          }, [$x], $dy), value = _a.value, grads2 = _a.grads;
          if ($dy != null) {
            assertShapesMatch(value.shape, $dy.shape, "The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)");
          }
          checkGrads(grads2);
          return grads2[0];
        });
      };
    }
    function grads(f) {
      assert(isFunction(f), function() {
        return "The f passed in grads(f) must be a function";
      });
      return function(args, dy) {
        assert(Array.isArray(args), function() {
          return "The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s";
        });
        var $args = convertToTensorArray(args, "args", "tf.grads", "string_or_numeric");
        var $dy = dy != null ? convertToTensor(dy, "dy", "tf.grads") : null;
        return ENGINE.tidy(function() {
          var _a = ENGINE.gradients(function() {
            return f.apply(void 0, __spreadArray([], __read($args), false));
          }, $args, $dy), value = _a.value, grads2 = _a.grads;
          if ($dy != null) {
            assertShapesMatch(value.shape, $dy.shape, "The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])");
          }
          checkGrads(grads2);
          return grads2;
        });
      };
    }
    function valueAndGrad(f) {
      assert(isFunction(f), function() {
        return "The f passed in valueAndGrad(f) must be a function";
      });
      return function(x, dy) {
        assert(x instanceof Tensor, function() {
          return "The x passed in valueAndGrad(f)(x) must be a tensor";
        });
        assert(dy == null || dy instanceof Tensor, function() {
          return "The dy passed in valueAndGrad(f)(x, dy) must be a tensor";
        });
        var _a = ENGINE.gradients(function() {
          return f(x);
        }, [x], dy), grads2 = _a.grads, value = _a.value;
        checkGrads(grads2);
        return { grad: grads2[0], value };
      };
    }
    function valueAndGrads(f) {
      assert(isFunction(f), function() {
        return "The f passed in valueAndGrads(f) must be a function";
      });
      return function(args, dy) {
        assert(Array.isArray(args) && args.every(function(arg) {
          return arg instanceof Tensor;
        }), function() {
          return "The args passed in valueAndGrads(f)(args) must be array of tensors";
        });
        assert(dy == null || dy instanceof Tensor, function() {
          return "The dy passed in valueAndGrads(f)(args, dy) must be a tensor";
        });
        var res = ENGINE.gradients(function() {
          return f.apply(void 0, __spreadArray([], __read(args), false));
        }, args, dy);
        if (dy != null) {
          assertShapesMatch(res.value.shape, dy.shape, "The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])");
        }
        checkGrads(res.grads);
        return res;
      };
    }
    function variableGrads(f, varList) {
      assert(isFunction(f), function() {
        return "The f passed in variableGrads(f) must be a function";
      });
      assert(varList == null || Array.isArray(varList) && varList.every(function(v) {
        return v instanceof Variable;
      }), function() {
        return "The varList passed in variableGrads(f, varList) must be an array of variables";
      });
      var specifiedVarList = varList != null;
      if (!specifiedVarList) {
        varList = [];
        for (var varName in ENGINE.registeredVariables) {
          varList.push(ENGINE.registeredVariables[varName]);
        }
      }
      var specifiedNonTrainable = specifiedVarList ? varList.filter(function(variable2) {
        return !variable2.trainable;
      }) : null;
      var originalVarCount = varList.length;
      varList = varList.filter(function(variable2) {
        return variable2.trainable;
      });
      assert(varList.length > 0, function() {
        return "variableGrads() expects at least one of the input variables to " + "be trainable, but none of the ".concat(originalVarCount, " variables is ") + "trainable.";
      });
      var allowNoGradients = true;
      var _a = ENGINE.gradients(f, varList, null, allowNoGradients), value = _a.value, grads2 = _a.grads;
      assert(grads2.some(function(g) {
        return g != null;
      }), function() {
        return "Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize().";
      });
      assert(value.rank === 0, function() {
        return "The f passed in variableGrads(f) must return a scalar, but it " + "returned a rank-".concat(value.rank, " tensor");
      });
      var namedGrads = {};
      varList.forEach(function(v, i) {
        if (grads2[i] != null) {
          namedGrads[v.name] = grads2[i];
        }
      });
      if (specifiedNonTrainable != null) {
        specifiedNonTrainable.forEach(function(v) {
          return namedGrads[v.name] = null;
        });
      }
      return { value, grads: namedGrads };
    }
    function customGrad(f) {
      return ENGINE.customGrad(f);
    }
    function checkGrads(grads2) {
      var numNullGradients = grads2.filter(function(g) {
        return g == null;
      }).length;
      if (numNullGradients > 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 neg_(x) {
      var $x = convertToTensor(x, "x", "neg");
      var inputs = { x: $x };
      return ENGINE.runKernel(Neg, inputs);
    }
    var neg = /* @__PURE__ */ op({ neg_ });
    function softplus_(x) {
      var $x = convertToTensor(x, "x", "softplus");
      var inputs = { x: $x };
      return ENGINE.runKernel(Softplus, inputs);
    }
    var softplus = /* @__PURE__ */ op({ softplus_ });
    function logSigmoid_(x) {
      var $x = convertToTensor(x, "x", "logSigmoid");
      var customOp = customGrad(function(x2) {
        var value = neg(softplus(neg(x2)));
        var gradFunc = function(dy) {
          var derX = mul(dy, sigmoid(neg(x2)));
          return derX;
        };
        return { value, gradFunc };
      });
      return customOp($x);
    }
    var logSigmoid = /* @__PURE__ */ op({ logSigmoid_ });
    function sub_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "sub");
      var $b = convertToTensor(b, "b", "sub");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Sub, inputs);
    }
    var sub = /* @__PURE__ */ op({ sub_ });
    function logSoftmax_(logits, axis) {
      if (axis === void 0) {
        axis = -1;
      }
      var $logits = convertToTensor(logits, "logits", "logSoftmax");
      if (axis === -1) {
        axis = $logits.rank - 1;
      }
      if (axis !== $logits.rank - 1) {
        throw Error("Log Softmax along a non-last dimension is not yet supported. " + "Logits was rank ".concat($logits.rank, " and axis was ").concat(axis));
      }
      var customOp = customGrad(function(logits2, save) {
        var keepDims = true;
        var xMax = max(logits2, axis, true);
        var shifted = sub(logits2, xMax);
        var value = sub(cast(shifted, "float32"), log(sum(exp(shifted), axis, keepDims)));
        save([value]);
        var gradFunc = function(dy, saved) {
          var _a = __read(saved, 1), value2 = _a[0];
          var keepDims2 = true;
          var softmax2 = exp(value2);
          return sub(dy, mul(sum(dy, axis, keepDims2), softmax2));
        };
        return { value, gradFunc };
      });
      return customOp($logits);
    }
    var logSoftmax = /* @__PURE__ */ op({ logSoftmax_ });
    function logSumExp_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "logSumExp");
      var axes = parseAxisParam(axis, $x.shape);
      var xMax = max(
        $x,
        axes,
        true
        /* keepDims */
      );
      var a = sub($x, xMax);
      var b = exp(a);
      var c = sum(b, axes);
      var d = log(c);
      var res = add(reshape(xMax, d.shape), d);
      if (keepDims) {
        var newShape = expandShapeToKeepDim(res.shape, axes);
        return reshape(res, newShape);
      }
      return res;
    }
    var logSumExp = /* @__PURE__ */ op({ logSumExp_ });
    function logicalAnd_(a, b) {
      var $a = convertToTensor(a, "a", "logicalAnd", "bool");
      var $b = convertToTensor(b, "b", "logicalAnd", "bool");
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(LogicalAnd, inputs);
    }
    var logicalAnd = /* @__PURE__ */ op({ logicalAnd_ });
    function logicalNot_(x) {
      var $x = convertToTensor(x, "x", "logicalNot", "bool");
      var inputs = { x: $x };
      return ENGINE.runKernel(LogicalNot, inputs);
    }
    var logicalNot = /* @__PURE__ */ op({ logicalNot_ });
    function logicalOr_(a, b) {
      var $a = convertToTensor(a, "a", "logicalOr", "bool");
      var $b = convertToTensor(b, "b", "logicalOr", "bool");
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(LogicalOr, inputs);
    }
    var logicalOr = /* @__PURE__ */ op({ logicalOr_ });
    function logicalXor_(a, b) {
      var $a = convertToTensor(a, "a", "logicalXor", "bool");
      var $b = convertToTensor(b, "b", "logicalXor", "bool");
      assertAndGetBroadcastShape($a.shape, $b.shape);
      return logicalAnd(logicalOr(a, b), logicalNot(logicalAnd(a, b)));
    }
    var logicalXor = /* @__PURE__ */ op({ logicalXor_ });
    var INT32_MAX = 2147483648;
    function searchSorted_(sortedSequence, values, side) {
      if (side === void 0) {
        side = "left";
      }
      var $sortedSequence = convertToTensor(sortedSequence, "sortedSequence", "searchSorted");
      var $values = convertToTensor(values, "values", "searchSorted");
      var sequenceSize = $sortedSequence.shape[$sortedSequence.shape.length - 1];
      var valuesSize = $values.shape[$values.shape.length - 1];
      var $sortedSequence2D = reshape($sortedSequence, [-1, sequenceSize]);
      var $values2D = reshape($values, [-1, valuesSize]);
      if ($sortedSequence2D.rank < 2) {
        throw new Error("Sorted input argument must be at least 2-dimensional");
      }
      if ($sortedSequence2D.shape[0] !== $values2D.shape[0]) {
        throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");
      }
      if (sizeFromShape($values2D.shape) >= INT32_MAX) {
        throw new Error("values tensor size must less than ".concat(INT32_MAX));
      }
      if ($sortedSequence2D.shape[1] >= INT32_MAX) {
        throw new Error("trailing dim_size must less than ".concat(INT32_MAX, " for int32 output type, was ").concat($sortedSequence2D.shape[1]));
      }
      var inputs = {
        sortedSequence: $sortedSequence2D,
        values: $values2D
      };
      var attrs = { side };
      return ENGINE.runKernel(SearchSorted, inputs, attrs);
    }
    var searchSorted = /* @__PURE__ */ op({ searchSorted_ });
    function lowerBound(sortedSequence, values) {
      return searchSorted(sortedSequence, values, "left");
    }
    function maxPool_(x, filterSize, strides, pad2, dimRoundingMode) {
      var $x = convertToTensor(x, "x", "maxPool");
      var dilations = 1;
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, function() {
        return "Error in maxPool: input must be rank 4 but got rank ".concat(x4D.rank, ".");
      });
      assert(eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in maxPool: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      checkPadOnDimRoundingMode("maxPool", pad2, dimRoundingMode);
      var inputs = { x: x4D };
      var attrs = { filterSize, strides, pad: pad2, dimRoundingMode };
      var res = ENGINE.runKernel(MaxPool, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var maxPool = /* @__PURE__ */ op({ maxPool_ });
    function maxPool3d_(x, filterSize, strides, pad2, dimRoundingMode, dataFormat) {
      if (filterSize === void 0) {
        filterSize = [1, 1, 1];
      }
      if (dataFormat === void 0) {
        dataFormat = "NDHWC";
      }
      var $x = convertToTensor(x, "x", "maxPool3d");
      var x5D = $x;
      var reshapedTo5D = false;
      if ($x.rank === 4) {
        reshapedTo5D = true;
        x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
      }
      assert(x5D.rank === 5, function() {
        return "Error in maxPool3d: x must be rank 5 but got rank ".concat(x5D.rank, ".");
      });
      assert(dataFormat === "NDHWC", function() {
        return "Error in maxPool3d: Only NDHWC is currently supported, " + "but got dataFormat of ".concat(dataFormat);
      });
      checkPadOnDimRoundingMode("maxPool3d", pad2, dimRoundingMode);
      var inputs = { x: x5D };
      var attrs = { filterSize, strides, pad: pad2, dimRoundingMode, dataFormat };
      var res = ENGINE.runKernel(MaxPool3D, inputs, attrs);
      if (reshapedTo5D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
      }
      return res;
    }
    var maxPool3d = /* @__PURE__ */ op({ maxPool3d_ });
    function maxPoolWithArgmax_(x, filterSize, strides, pad2, includeBatchInIndex) {
      if (includeBatchInIndex === void 0) {
        includeBatchInIndex = false;
      }
      var $x = convertToTensor(x, "x", "maxPoolWithArgmax");
      var inputs = { x: $x };
      var attrs = { filterSize, strides, pad: pad2, includeBatchInIndex };
      var result = ENGINE.runKernel(MaxPoolWithArgmax, inputs, attrs);
      return { result: result[0], indexes: result[1] };
    }
    var maxPoolWithArgmax = /* @__PURE__ */ op({ maxPoolWithArgmax_ });
    function maximum_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "maximum");
      var $b = convertToTensor(b, "b", "maximum");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      if ($a.dtype === "bool") {
        $a = cast($a, "int32");
        $b = cast($b, "int32");
      }
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Maximum, inputs);
    }
    var maximum = /* @__PURE__ */ op({ maximum_ });
    function mean_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "mean");
      var inputs = { x: $x };
      var attrs = { axis, keepDims };
      return ENGINE.runKernel(Mean, inputs, attrs);
    }
    var mean = /* @__PURE__ */ op({ mean_ });
    function zeros(shape, dtype) {
      if (dtype === void 0) {
        dtype = "float32";
      }
      assertNonNegativeIntegerDimensions(shape);
      if (dtype === "complex64") {
        var real2 = zeros(shape, "float32");
        var imag2 = zeros(shape, "float32");
        return complex(real2, imag2);
      }
      var values = makeZerosTypedArray(sizeFromShape(shape), dtype);
      return ENGINE.makeTensor(values, shape, dtype);
    }
    function ones(shape, dtype) {
      if (dtype === void 0) {
        dtype = "float32";
      }
      assertNonNegativeIntegerDimensions(shape);
      if (dtype === "complex64") {
        var real2 = ones(shape, "float32");
        var imag2 = zeros(shape, "float32");
        return complex(real2, imag2);
      }
      var values = makeOnesTypedArray(sizeFromShape(shape), dtype);
      return ENGINE.makeTensor(values, shape, dtype);
    }
    function meshgrid(x, y, _a) {
      var _b = _a === void 0 ? {} : _a, _c = _b.indexing, indexing = _c === void 0 ? "xy" : _c;
      if (indexing !== "xy" && indexing !== "ij") {
        throw new TypeError("".concat(indexing, " is not a valid third argument to meshgrid"));
      }
      if (x === void 0) {
        return [];
      }
      var $x = convertToTensor(x, "x", "meshgrid", x instanceof Tensor ? x.dtype : "float32");
      if (y === void 0) {
        return [$x];
      }
      var $y = convertToTensor(y, "y", "meshgrid", y instanceof Tensor ? y.dtype : "float32");
      var w = sizeFromShape($x.shape);
      var h = sizeFromShape($y.shape);
      if (indexing === "xy") {
        $x = reshape($x, [1, -1]);
        $y = reshape($y, [-1, 1]);
        return [
          matMul$1(ones([h, 1], $x.dtype), $x),
          matMul$1($y, ones([1, w], $y.dtype))
        ];
      }
      $x = reshape($x, [-1, 1]);
      $y = reshape($y, [1, -1]);
      return [
        matMul$1($x, ones([1, h], $x.dtype)),
        matMul$1(ones([w, 1], $y.dtype), $y)
      ];
    }
    function minimum_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "minimum");
      var $b = convertToTensor(b, "b", "minimum");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      if ($a.dtype === "bool") {
        $a = cast($a, "int32");
        $b = cast($b, "int32");
      }
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Minimum, inputs);
    }
    var minimum = /* @__PURE__ */ op({ minimum_ });
    function mirrorPad_(x, paddings, mode) {
      assert(mode === "reflect" || mode === "symmetric", function() {
        return "Invalid mode. Mode must be either reflect or symmetric. " + "Got ".concat(mode, ".");
      });
      var $x = convertToTensor(x, "x", "mirrorPad");
      if ($x.rank === 0) {
        throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");
      }
      assert(paddings.length === $x.rank, function() {
        return "Padding doesn't match input. Must be ".concat($x.rank, ". ") + "Got ".concat(paddings.length, ".");
      });
      var shapeOffset = mode === "reflect" ? 1 : 0;
      var _loop_1 = function(i2) {
        assert(paddings[i2].length === 2, function() {
          return "Invalid number of paddings. Must be length of 2 each.";
        });
        assert(paddings[i2][0] >= 0 && paddings[i2][0] <= $x.shape[i2] - shapeOffset && paddings[i2][1] >= 0 && paddings[i2][1] <= $x.shape[i2] - shapeOffset, function() {
          return "Padding in dimension ".concat(i2, " cannot be greater than or equal ") + "to ".concat($x.shape[i2] - shapeOffset, " or less than 0 for input of ") + "shape ".concat($x.shape);
        });
      };
      for (var i = 0; i < $x.rank; i++) {
        _loop_1(i);
      }
      var attrs = { paddings, mode };
      var inputs = { x: $x };
      return ENGINE.runKernel(MirrorPad, inputs, attrs);
    }
    var mirrorPad = /* @__PURE__ */ op({ mirrorPad_ });
    function mod_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "mod");
      var $b = convertToTensor(b, "b", "mod");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Mod, inputs);
    }
    var mod = /* @__PURE__ */ op({ mod_ });
    function moments_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      x = convertToTensor(x, "x", "moments");
      var axes = parseAxisParam(axis, x.shape);
      var xMean = mean(x, axes, keepDims);
      var keepDimsShape = xMean.shape;
      if (!keepDims) {
        keepDimsShape = expandShapeToKeepDim(xMean.shape, axes);
      }
      var devSquared = square(sub(cast(x, "float32"), reshape(xMean, keepDimsShape)));
      var variance = mean(devSquared, axes, keepDims);
      return { mean: xMean, variance };
    }
    var moments = /* @__PURE__ */ op({ moments_ });
    function multiRNNCell_(lstmCells, data, c, h) {
      var $data = convertToTensor(data, "data", "multiRNNCell");
      var $c = convertToTensorArray(c, "c", "multiRNNCell");
      var $h = convertToTensorArray(h, "h", "multiRNNCell");
      var input = $data;
      var newStates = [];
      for (var i = 0; i < lstmCells.length; i++) {
        var output = lstmCells[i](input, $c[i], $h[i]);
        newStates.push(output[0]);
        newStates.push(output[1]);
        input = output[1];
      }
      var newC = [];
      var newH = [];
      for (var i = 0; i < newStates.length; i += 2) {
        newC.push(newStates[i]);
        newH.push(newStates[i + 1]);
      }
      return [newC, newH];
    }
    var multiRNNCell = /* @__PURE__ */ op({ multiRNNCell_ });
    function multinomial_(logits, numSamples, seed, normalized) {
      if (normalized === void 0) {
        normalized = false;
      }
      var $logits = convertToTensor(logits, "logits", "multinomial");
      var numOutcomes = $logits.size;
      var origRank = $logits.rank;
      if (numOutcomes < 2) {
        throw new Error("Error in multinomial: you need at least 2 outcomes, but got " + "".concat(numOutcomes, "."));
      }
      if (origRank > 2) {
        throw new Error("Rank of probabilities must be 1 or 2, but is ".concat(origRank));
      }
      seed = seed || Math.random();
      var logits2D = origRank === 1 ? reshape($logits, [1, -1]) : $logits;
      var inputs = { logits: logits2D };
      var attrs = { numSamples, seed, normalized };
      var res = ENGINE.runKernel(Multinomial, inputs, attrs);
      return origRank === 1 ? reshape(res, [res.size]) : res;
    }
    var multinomial = /* @__PURE__ */ op({ multinomial_ });
    function notEqual_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "notEqual", "string_or_numeric");
      var $b = convertToTensor(b, "b", "notEqual", "string_or_numeric");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(NotEqual, inputs);
    }
    var notEqual = /* @__PURE__ */ op({ notEqual_ });
    function oneHot_(indices, depth, onValue, offValue, dtype) {
      if (onValue === void 0) {
        onValue = 1;
      }
      if (offValue === void 0) {
        offValue = 0;
      }
      if (dtype === void 0) {
        dtype = "int32";
      }
      if (depth < 2) {
        throw new Error("Error in oneHot: depth must be >=2, but it is ".concat(depth));
      }
      var $indices = convertToTensor(indices, "indices", "oneHot", "int32");
      var inputs = { indices: $indices };
      var attrs = { dtype, depth, onValue, offValue };
      return ENGINE.runKernel(OneHot, inputs, attrs);
    }
    var oneHot = /* @__PURE__ */ op({ oneHot_ });
    function onesLike_(x) {
      var $x = convertToTensor(x, "x", "onesLike");
      var inputs = { x: $x };
      return ENGINE.runKernel(OnesLike, inputs);
    }
    var onesLike = /* @__PURE__ */ op({ onesLike_ });
    function outerProduct_(v1, v2) {
      var $v1 = convertToTensor(v1, "v1", "outerProduct");
      var $v2 = convertToTensor(v2, "v2", "outerProduct");
      assert($v1.rank === 1 && $v2.rank === 1, function() {
        return "Error in outerProduct: inputs must be rank 1, but got ranks " + "".concat($v1.rank, " and ").concat($v2.rank, ".");
      });
      var v12D = reshape($v1, [-1, 1]);
      var v22D = reshape($v2, [1, -1]);
      return matMul$1(v12D, v22D);
    }
    var outerProduct = /* @__PURE__ */ op({ outerProduct_ });
    function pad_(x, paddings, constantValue) {
      if (constantValue === void 0) {
        constantValue = 0;
      }
      var $x = convertToTensor(x, "x", "pad");
      if ($x.rank === 0) {
        throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");
      }
      var attrs = { paddings, constantValue };
      var inputs = { x: $x };
      return ENGINE.runKernel(PadV2, inputs, attrs);
    }
    var pad = /* @__PURE__ */ op({ pad_ });
    function pad1d_(x, paddings, constantValue) {
      if (constantValue === void 0) {
        constantValue = 0;
      }
      assert(paddings.length === 2, function() {
        return "Invalid number of paddings. Must be length of 2.";
      });
      return pad(x, [paddings], constantValue);
    }
    var pad1d = /* @__PURE__ */ op({ pad1d_ });
    function pad2d_(x, paddings, constantValue) {
      if (constantValue === void 0) {
        constantValue = 0;
      }
      assert(paddings.length === 2 && paddings[0].length === 2 && paddings[1].length === 2, function() {
        return "Invalid number of paddings. Must be length of 2 each.";
      });
      return pad(x, paddings, constantValue);
    }
    var pad2d = /* @__PURE__ */ op({ pad2d_ });
    function pad3d_(x, paddings, constantValue) {
      if (constantValue === void 0) {
        constantValue = 0;
      }
      assert(paddings.length === 3 && paddings[0].length === 2 && paddings[1].length === 2 && paddings[2].length === 2, function() {
        return "Invalid number of paddings. Must be length of 2 each.";
      });
      return pad(x, paddings, constantValue);
    }
    var pad3d = /* @__PURE__ */ op({ pad3d_ });
    function pad4d_(x, paddings, constantValue) {
      if (constantValue === void 0) {
        constantValue = 0;
      }
      assert(paddings.length === 4 && paddings[0].length === 2 && paddings[1].length === 2 && paddings[2].length === 2 && paddings[3].length === 2, function() {
        return "Invalid number of paddings. Must be length of 2 each.";
      });
      return pad(x, paddings, constantValue);
    }
    var pad4d = /* @__PURE__ */ op({ pad4d_ });
    function spaceToBatchND_(x, blockShape, paddings) {
      var $x = convertToTensor(x, "x", "spaceToBatchND");
      assert($x.rank >= 1 + blockShape.length, function() {
        return "input rank ".concat($x.rank, " should be > than [blockShape] ").concat(blockShape.length);
      });
      assert(paddings.length === blockShape.length, function() {
        return "paddings.shape[0] ".concat(paddings.length, " must be equal to [blockShape] ").concat(blockShape.length);
      });
      assert($x.shape.reduce(function(a, b, i) {
        if (i > 0 && i <= blockShape.length) {
          return a && (b + paddings[i - 1][0] + paddings[i - 1][1]) % blockShape[i - 1] === 0;
        }
        return a;
      }, true), function() {
        return "input spatial dimensions ".concat($x.shape.slice(1), " with paddings ").concat(paddings.toString(), " must be divisible by blockShapes ").concat(blockShape.toString());
      });
      var inputs = { x: $x };
      var attrs = { blockShape, paddings };
      return ENGINE.runKernel(SpaceToBatchND, inputs, attrs);
    }
    var spaceToBatchND = /* @__PURE__ */ op({ spaceToBatchND_ });
    function pool_(input, windowShape, poolingType, pad2, dilations, strides, dimRoundingMode) {
      if (dilations == null) {
        dilations = [1, 1];
      }
      if (strides == null) {
        strides = 1;
      }
      if (pad2 === 0) {
        pad2 = "valid";
      }
      var $x = convertToTensor(input, "x", "maxPool");
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in pool: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      var convInfo = computePool2DInfo(x4D.shape, windowShape, strides, dilations, pad2);
      var dilation = [convInfo.dilationHeight, convInfo.dilationWidth];
      var basePadding;
      if (pad2 === "same") {
        basePadding = withSpaceToBatchBasePaddings([convInfo.filterHeight, convInfo.filterWidth], dilation);
      } else {
        basePadding = [[0, 0], [0, 0]];
      }
      var isDilationOne = dilation[0] === 1 && dilation[1] === 1;
      var _a = __read(requiredSpaceToBatchPaddings([convInfo.inHeight, convInfo.inWidth], dilation, basePadding), 2), adjustedPadding = _a[0], adjustedCrops = _a[1];
      var convertedPad = isDilationOne ? pad2 : "valid";
      var convertedX = isDilationOne ? x4D : spaceToBatchND(x4D, dilation, adjustedPadding);
      var forwardOp = poolingType === "avg" ? function() {
        return avgPool(convertedX, windowShape, strides, convertedPad, dimRoundingMode);
      } : function() {
        return maxPool(convertedX, windowShape, strides, convertedPad, dimRoundingMode);
      };
      var y = forwardOp();
      var res = isDilationOne ? y : batchToSpaceND(y, dilation, adjustedCrops);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    function requiredSpaceToBatchPaddings(inputShape, blockShape, basePadding) {
      var padStart = basePadding.map(function(b) {
        return b[0];
      });
      var origPadEnd = basePadding.map(function(b) {
        return b[1];
      });
      var fullInputShape = inputShape.concat(padStart, origPadEnd);
      var padEndExtra = blockShape.map(function(b, i) {
        return (b - fullInputShape[i] % b) % b;
      });
      var padEnd = origPadEnd.map(function(s, i) {
        return s + padEndExtra[i];
      });
      var paddings = blockShape.map(function(_, i) {
        return [padStart[i], padEnd[i]];
      });
      var crops = blockShape.map(function(_, i) {
        return [0, padEndExtra[i]];
      });
      return [paddings, crops];
    }
    function withSpaceToBatchBasePaddings(filterShape, dilation) {
      var dilatedFilterShape = filterShape.map(function(s, i) {
        return s + (s - 1) * (dilation[i] - 1);
      });
      var padExtraShape = dilatedFilterShape.map(function(s) {
        return s - 1;
      });
      var padExtraStart = padExtraShape.map(function(s) {
        return Math.floor(s / 2);
      });
      var padExtraEnd = padExtraShape.map(function(s, i) {
        return s - padExtraStart[i];
      });
      return padExtraShape.map(function(_, i) {
        return [padExtraStart[i], padExtraEnd[i]];
      });
    }
    var pool = /* @__PURE__ */ op({ pool_ });
    function prelu_(x, alpha) {
      var $x = convertToTensor(x, "x", "prelu");
      var $alpha = convertToTensor(alpha, "alpha", "prelu");
      var inputs = { x: $x, alpha: $alpha };
      return ENGINE.runKernel(Prelu, inputs);
    }
    var prelu = /* @__PURE__ */ op({ prelu_ });
    function prod_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "prod");
      if ($x.dtype === "bool") {
        $x = cast($x, "int32");
      }
      var inputs = { x: $x };
      var attrs = { axis, keepDims };
      return ENGINE.runKernel(Prod, inputs, attrs);
    }
    var prod = /* @__PURE__ */ op({ prod_ });
    function raggedGather_(paramsNestedSplits, paramsDenseValues, indices, outputRaggedRank) {
      var $paramsNestedSplits = paramsNestedSplits.map(function(t, i) {
        return convertToTensor(t, "tensors".concat(i), "raggedGather", "int32");
      });
      var $paramsDenseValues = convertToTensor(paramsDenseValues, "paramsDenseValues", "raggedGather");
      var $indices = convertToTensor(indices, "indices", "raggedGather", "int32");
      var inputs = {
        paramsNestedSplits: $paramsNestedSplits,
        paramsDenseValues: $paramsDenseValues,
        indices: $indices
      };
      var attrs = { outputRaggedRank };
      var result = ENGINE.runKernel(RaggedGather, inputs, attrs);
      return {
        outputNestedSplits: result.slice(0, result.length - 1),
        outputDenseValues: result[result.length - 1]
      };
    }
    var raggedGather = /* @__PURE__ */ op({ raggedGather_ });
    function raggedRange_(starts, limits, deltas) {
      var $starts = convertToTensor(starts, "starts", "raggedRange");
      var $limits = convertToTensor(limits, "limits", "raggedRange", $starts.dtype);
      var $deltas = convertToTensor(deltas, "deltas", "raggedRange", $starts.dtype);
      var inputs = {
        starts: $starts,
        limits: $limits,
        deltas: $deltas
      };
      var result = ENGINE.runKernel(RaggedRange, inputs);
      return {
        rtNestedSplits: result[0],
        rtDenseValues: result[1]
      };
    }
    var raggedRange = /* @__PURE__ */ op({ raggedRange_ });
    function raggedTensorToTensor_(shape, values, defaultValue, rowPartitionTensors, rowPartitionTypes) {
      var $shape = convertToTensor(shape, "shape", "raggedTensorToTensor", "int32");
      var $values = convertToTensor(values, "values", "raggedTensorToTensor");
      var $defaultValue = convertToTensor(defaultValue, "defaultValue", "raggedTensorToTensor", $values.dtype);
      var $rowPartitionTensors = rowPartitionTensors.map(function(t, i) {
        return convertToTensor(t, "tensors".concat(i), "raggedTensorToTensor", "int32");
      });
      var inputs = {
        shape: $shape,
        values: $values,
        defaultValue: $defaultValue,
        rowPartitionTensors: $rowPartitionTensors
      };
      var attrs = { rowPartitionTypes };
      return ENGINE.runKernel(RaggedTensorToTensor, inputs, attrs);
    }
    var raggedTensorToTensor = /* @__PURE__ */ op({ raggedTensorToTensor_ });
    function rand_(shape, randFunction, dtype) {
      assertNonNegativeIntegerDimensions(shape);
      var size = sizeFromShape(shape);
      var values = null;
      if (dtype == null || dtype === "float32") {
        values = new Float32Array(size);
      } else if (dtype === "int32") {
        values = new Int32Array(size);
      } else if (dtype === "bool") {
        values = new Uint8Array(size);
      } else {
        throw new Error("Unknown data type ".concat(dtype));
      }
      for (var i = 0; i < size; i++) {
        values[i] = randFunction();
      }
      return ENGINE.makeTensor(values, shape, dtype);
    }
    var rand = /* @__PURE__ */ op({ rand_ });
    var alea$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function Alea(seed) {
          var me = this, mash = Mash();
          me.next = function() {
            var t = 2091639 * me.s0 + me.c * 23283064365386963e-26;
            me.s0 = me.s1;
            me.s1 = me.s2;
            return me.s2 = t - (me.c = t | 0);
          };
          me.c = 1;
          me.s0 = mash(" ");
          me.s1 = mash(" ");
          me.s2 = mash(" ");
          me.s0 -= mash(seed);
          if (me.s0 < 0) {
            me.s0 += 1;
          }
          me.s1 -= mash(seed);
          if (me.s1 < 0) {
            me.s1 += 1;
          }
          me.s2 -= mash(seed);
          if (me.s2 < 0) {
            me.s2 += 1;
          }
          mash = null;
        }
        function copy(f, t) {
          t.c = f.c;
          t.s0 = f.s0;
          t.s1 = f.s1;
          t.s2 = f.s2;
          return t;
        }
        function impl(seed, opts) {
          var xg = new Alea(seed), state = opts && opts.state, prng = xg.next;
          prng.int32 = function() {
            return xg.next() * 4294967296 | 0;
          };
          prng.double = function() {
            return prng() + (prng() * 2097152 | 0) * 11102230246251565e-32;
          };
          prng.quick = prng;
          if (state) {
            if (typeof state == "object")
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        function Mash() {
          var n = 4022871197;
          var mash = function(data) {
            data = String(data);
            for (var i = 0; i < data.length; i++) {
              n += data.charCodeAt(i);
              var h = 0.02519603282416938 * n;
              n = h >>> 0;
              h -= n;
              h *= n;
              n = h >>> 0;
              h -= n;
              n += h * 4294967296;
            }
            return (n >>> 0) * 23283064365386963e-26;
          };
          return mash;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.alea = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(alea$1);
    var aleaExports = alea$1.exports;
    var xor128$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this, strseed = "";
          me.x = 0;
          me.y = 0;
          me.z = 0;
          me.w = 0;
          me.next = function() {
            var t = me.x ^ me.x << 11;
            me.x = me.y;
            me.y = me.z;
            me.z = me.w;
            return me.w ^= me.w >>> 19 ^ t ^ t >>> 8;
          };
          if (seed === (seed | 0)) {
            me.x = seed;
          } else {
            strseed += seed;
          }
          for (var k = 0; k < strseed.length + 64; k++) {
            me.x ^= strseed.charCodeAt(k) | 0;
            me.next();
          }
        }
        function copy(f, t) {
          t.x = f.x;
          t.y = f.y;
          t.z = f.z;
          t.w = f.w;
          return t;
        }
        function impl(seed, opts) {
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (typeof state == "object")
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xor128 = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xor128$1);
    var xor128Exports = xor128$1.exports;
    var xorwow$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this, strseed = "";
          me.next = function() {
            var t = me.x ^ me.x >>> 2;
            me.x = me.y;
            me.y = me.z;
            me.z = me.w;
            me.w = me.v;
            return (me.d = me.d + 362437 | 0) + (me.v = me.v ^ me.v << 4 ^ (t ^ t << 1)) | 0;
          };
          me.x = 0;
          me.y = 0;
          me.z = 0;
          me.w = 0;
          me.v = 0;
          if (seed === (seed | 0)) {
            me.x = seed;
          } else {
            strseed += seed;
          }
          for (var k = 0; k < strseed.length + 64; k++) {
            me.x ^= strseed.charCodeAt(k) | 0;
            if (k == strseed.length) {
              me.d = me.x << 10 ^ me.x >>> 4;
            }
            me.next();
          }
        }
        function copy(f, t) {
          t.x = f.x;
          t.y = f.y;
          t.z = f.z;
          t.w = f.w;
          t.v = f.v;
          t.d = f.d;
          return t;
        }
        function impl(seed, opts) {
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (typeof state == "object")
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xorwow = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xorwow$1);
    var xorwowExports = xorwow$1.exports;
    var xorshift7$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this;
          me.next = function() {
            var X = me.x, i = me.i, t, v;
            t = X[i];
            t ^= t >>> 7;
            v = t ^ t << 24;
            t = X[i + 1 & 7];
            v ^= t ^ t >>> 10;
            t = X[i + 3 & 7];
            v ^= t ^ t >>> 3;
            t = X[i + 4 & 7];
            v ^= t ^ t << 7;
            t = X[i + 7 & 7];
            t = t ^ t << 13;
            v ^= t ^ t << 9;
            X[i] = v;
            me.i = i + 1 & 7;
            return v;
          };
          function init(me2, seed2) {
            var j, X = [];
            if (seed2 === (seed2 | 0)) {
              X[0] = seed2;
            } else {
              seed2 = "" + seed2;
              for (j = 0; j < seed2.length; ++j) {
                X[j & 7] = X[j & 7] << 15 ^ seed2.charCodeAt(j) + X[j + 1 & 7] << 13;
              }
            }
            while (X.length < 8)
              X.push(0);
            for (j = 0; j < 8 && X[j] === 0; ++j)
              ;
            if (j == 8)
              X[7] = -1;
            else
              X[j];
            me2.x = X;
            me2.i = 0;
            for (j = 256; j > 0; --j) {
              me2.next();
            }
          }
          init(me, seed);
        }
        function copy(f, t) {
          t.x = f.x.slice();
          t.i = f.i;
          return t;
        }
        function impl(seed, opts) {
          if (seed == null)
            seed = +/* @__PURE__ */ new Date();
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (state.x)
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xorshift7 = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xorshift7$1);
    var xorshift7Exports = xorshift7$1.exports;
    var xor4096$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this;
          me.next = function() {
            var w = me.w, X = me.X, i = me.i, t, v;
            me.w = w = w + 1640531527 | 0;
            v = X[i + 34 & 127];
            t = X[i = i + 1 & 127];
            v ^= v << 13;
            t ^= t << 17;
            v ^= v >>> 15;
            t ^= t >>> 12;
            v = X[i] = v ^ t;
            me.i = i;
            return v + (w ^ w >>> 16) | 0;
          };
          function init(me2, seed2) {
            var t, v, i, j, w, X = [], limit = 128;
            if (seed2 === (seed2 | 0)) {
              v = seed2;
              seed2 = null;
            } else {
              seed2 = seed2 + "\0";
              v = 0;
              limit = Math.max(limit, seed2.length);
            }
            for (i = 0, j = -32; j < limit; ++j) {
              if (seed2)
                v ^= seed2.charCodeAt((j + 32) % seed2.length);
              if (j === 0)
                w = v;
              v ^= v << 10;
              v ^= v >>> 15;
              v ^= v << 4;
              v ^= v >>> 13;
              if (j >= 0) {
                w = w + 1640531527 | 0;
                t = X[j & 127] ^= v + w;
                i = 0 == t ? i + 1 : 0;
              }
            }
            if (i >= 128) {
              X[(seed2 && seed2.length || 0) & 127] = -1;
            }
            i = 127;
            for (j = 4 * 128; j > 0; --j) {
              v = X[i + 34 & 127];
              t = X[i = i + 1 & 127];
              v ^= v << 13;
              t ^= t << 17;
              v ^= v >>> 15;
              t ^= t >>> 12;
              X[i] = v ^ t;
            }
            me2.w = w;
            me2.X = X;
            me2.i = i;
          }
          init(me, seed);
        }
        function copy(f, t) {
          t.i = f.i;
          t.w = f.w;
          t.X = f.X.slice();
          return t;
        }
        function impl(seed, opts) {
          if (seed == null)
            seed = +/* @__PURE__ */ new Date();
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (state.X)
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xor4096 = impl;
        }
      })(
        commonjsGlobal,
        // window object or global
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xor4096$1);
    var xor4096Exports = xor4096$1.exports;
    var tychei$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this, strseed = "";
          me.next = function() {
            var b = me.b, c = me.c, d = me.d, a = me.a;
            b = b << 25 ^ b >>> 7 ^ c;
            c = c - d | 0;
            d = d << 24 ^ d >>> 8 ^ a;
            a = a - b | 0;
            me.b = b = b << 20 ^ b >>> 12 ^ c;
            me.c = c = c - d | 0;
            me.d = d << 16 ^ c >>> 16 ^ a;
            return me.a = a - b | 0;
          };
          me.a = 0;
          me.b = 0;
          me.c = 2654435769 | 0;
          me.d = 1367130551;
          if (seed === Math.floor(seed)) {
            me.a = seed / 4294967296 | 0;
            me.b = seed | 0;
          } else {
            strseed += seed;
          }
          for (var k = 0; k < strseed.length + 20; k++) {
            me.b ^= strseed.charCodeAt(k) | 0;
            me.next();
          }
        }
        function copy(f, t) {
          t.a = f.a;
          t.b = f.b;
          t.c = f.c;
          t.d = f.d;
          return t;
        }
        function impl(seed, opts) {
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (typeof state == "object")
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.tychei = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(tychei$1);
    var tycheiExports = tychei$1.exports;
    var seedrandom$1 = { exports: {} };
    (function(module3) {
      (function(global2, pool2, math2) {
        var width = 256, chunks = 6, digits = 52, rngname = "random", startdenom = math2.pow(width, chunks), significance = math2.pow(2, digits), overflow = significance * 2, mask = width - 1, nodecrypto;
        function seedrandom2(seed, options, callback) {
          var key = [];
          options = options == true ? { entropy: true } : options || {};
          var shortseed = mixkey(flatten2(options.entropy ? [seed, tostring(pool2)] : seed == null ? autoseed() : seed, 3), key);
          var arc4 = new ARC4(key);
          var prng = function() {
            var n = arc4.g(chunks), d = startdenom, x = 0;
            while (n < significance) {
              n = (n + x) * width;
              d *= width;
              x = arc4.g(1);
            }
            while (n >= overflow) {
              n /= 2;
              d /= 2;
              x >>>= 1;
            }
            return (n + x) / d;
          };
          prng.int32 = function() {
            return arc4.g(4) | 0;
          };
          prng.quick = function() {
            return arc4.g(4) / 4294967296;
          };
          prng.double = prng;
          mixkey(tostring(arc4.S), pool2);
          return (options.pass || callback || function(prng2, seed2, is_math_call, state) {
            if (state) {
              if (state.S) {
                copy(state, arc4);
              }
              prng2.state = function() {
                return copy(arc4, {});
              };
            }
            if (is_math_call) {
              math2[rngname] = prng2;
              return seed2;
            } else
              return prng2;
          })(prng, shortseed, "global" in options ? options.global : this == math2, options.state);
        }
        function ARC4(key) {
          var t, keylen = key.length, me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
          if (!keylen) {
            key = [keylen++];
          }
          while (i < width) {
            s[i] = i++;
          }
          for (i = 0; i < width; i++) {
            s[i] = s[j = mask & j + key[i % keylen] + (t = s[i])];
            s[j] = t;
          }
          (me.g = function(count) {
            var t2, r = 0, i2 = me.i, j2 = me.j, s2 = me.S;
            while (count--) {
              t2 = s2[i2 = mask & i2 + 1];
              r = r * width + s2[mask & (s2[i2] = s2[j2 = mask & j2 + t2]) + (s2[j2] = t2)];
            }
            me.i = i2;
            me.j = j2;
            return r;
          })(width);
        }
        function copy(f, t) {
          t.i = f.i;
          t.j = f.j;
          t.S = f.S.slice();
          return t;
        }
        function flatten2(obj, depth) {
          var result = [], typ = typeof obj, prop;
          if (depth && typ == "object") {
            for (prop in obj) {
              try {
                result.push(flatten2(obj[prop], depth - 1));
              } catch (e) {
              }
            }
          }
          return result.length ? result : typ == "string" ? obj : obj + "\0";
        }
        function mixkey(seed, key) {
          var stringseed = seed + "", smear, j = 0;
          while (j < stringseed.length) {
            key[mask & j] = mask & (smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++);
          }
          return tostring(key);
        }
        function autoseed() {
          try {
            var out;
            if (nodecrypto && (out = nodecrypto.randomBytes)) {
              out = out(width);
            } else {
              out = new Uint8Array(width);
              (global2.crypto || global2.msCrypto).getRandomValues(out);
            }
            return tostring(out);
          } catch (e) {
            var browser2 = global2.navigator, plugins = browser2 && browser2.plugins;
            return [+/* @__PURE__ */ new Date(), global2, plugins, global2.screen, tostring(pool2)];
          }
        }
        function tostring(a) {
          return String.fromCharCode.apply(0, a);
        }
        mixkey(math2.random(), pool2);
        if (module3.exports) {
          module3.exports = seedrandom2;
          try {
            nodecrypto = require("crypto");
          } catch (ex) {
          }
        } else {
          math2["seed" + rngname] = seedrandom2;
        }
      })(
        // global: `self` in browsers (including strict mode and web workers),
        // otherwise `this` in Node and other environments
        typeof self !== "undefined" ? self : commonjsGlobal,
        [],
        // pool: entropy pool starts empty
        Math
        // math: package containing random, pow, and seedrandom
      );
    })(seedrandom$1);
    var seedrandomExports = seedrandom$1.exports;
    var alea = aleaExports;
    var xor128 = xor128Exports;
    var xorwow = xorwowExports;
    var xorshift7 = xorshift7Exports;
    var xor4096 = xor4096Exports;
    var tychei = tycheiExports;
    var sr = seedrandomExports;
    sr.alea = alea;
    sr.xor128 = xor128;
    sr.xorwow = xorwow;
    sr.xorshift7 = xorshift7;
    sr.xor4096 = xor4096;
    sr.tychei = tychei;
    var seedrandom = sr;
    var TEST_EPSILON_FLOAT32 = 1e-3;
    var TEST_EPSILON_FLOAT16 = 0.1;
    function expectArraysClose(actual, expected, epsilon) {
      if (epsilon == null) {
        epsilon = testEpsilon();
      }
      return expectArraysPredicate(actual, expected, function(a, b) {
        return areClose(a, b, epsilon);
      });
    }
    function testEpsilon() {
      return ENGINE.backend.floatPrecision() === 32 ? TEST_EPSILON_FLOAT32 : TEST_EPSILON_FLOAT16;
    }
    function expectArraysPredicate(actual, expected, predicate) {
      var checkClassType = true;
      if (isTypedArray(actual) || isTypedArray(expected)) {
        checkClassType = false;
      }
      if (isTypedArray(actual) && isTypedArray(expected)) {
        checkClassType = true;
      }
      if (checkClassType) {
        var aType = actual.constructor.name;
        var bType = expected.constructor.name;
        if (aType !== bType) {
          throw new Error("Arrays are of different type. Actual: ".concat(aType, ". ") + "Expected: ".concat(bType));
        }
      }
      if (Array.isArray(actual) && Array.isArray(expected)) {
        var actualShape = inferShape(actual);
        var expectedShape = inferShape(expected);
        if (!arraysEqual(actualShape, expectedShape)) {
          throw new Error("Arrays have different shapes. " + "Actual: [".concat(actualShape, "]. Expected: [").concat(expectedShape, "]"));
        }
      }
      var actualFlat = isTypedArray(actual) ? actual : flatten(actual);
      var expectedFlat = isTypedArray(expected) ? expected : flatten(expected);
      if (actualFlat.length !== expectedFlat.length) {
        throw new Error("Arrays have different lengths actual: ".concat(actualFlat.length, " vs ") + "expected: ".concat(expectedFlat.length, ".\n") + "Actual:   ".concat(actualFlat, ".\n") + "Expected: ".concat(expectedFlat, "."));
      }
      for (var i = 0; i < expectedFlat.length; ++i) {
        var a = actualFlat[i];
        var e = expectedFlat[i];
        if (!predicate(a, e)) {
          throw new Error("Arrays differ: actual[".concat(i, "] = ").concat(a, ", expected[").concat(i, "] = ").concat(e, ".\n") + "Actual:   ".concat(actualFlat, ".\n") + "Expected: ".concat(expectedFlat, "."));
        }
      }
      if (typeof expect !== "undefined") {
        expect().nothing();
      }
    }
    function expectPromiseToFail(fn, done) {
      fn().then(function() {
        return done.fail();
      }, function() {
        return done();
      });
      if (typeof expect !== "undefined") {
        expect().nothing();
      }
    }
    function expectArraysEqual(actual, expected) {
      var exp2 = typeof expected === "string" || typeof expected === "number" || typeof expected === "boolean" ? [expected] : expected;
      if (isString(actual) || isString(actual[0]) || isString(expected) || isString(expected[0])) {
        return expectArraysPredicate(actual, exp2, function(a, b) {
          return a == b;
        });
      }
      return expectArraysPredicate(actual, expected, function(a, b) {
        return areClose(a, b, 0);
      });
    }
    function expectNumbersClose(a, e, epsilon) {
      if (epsilon == null) {
        epsilon = testEpsilon();
      }
      if (!areClose(a, e, epsilon)) {
        throw new Error("Numbers differ: actual === ".concat(a, ", expected === ").concat(e));
      }
      if (typeof expect !== "undefined") {
        expect().nothing();
      }
    }
    function areClose(a, e, epsilon) {
      if (!isFinite(a) && !isFinite(e)) {
        return true;
      }
      if (isNaN(a) || isNaN(e) || Math.abs(a - e) > epsilon) {
        return false;
      }
      return true;
    }
    function expectValuesInRange(actual, low, high) {
      for (var i = 0; i < actual.length; i++) {
        if (actual[i] < low || actual[i] > high) {
          throw new Error("Value out of range:".concat(actual[i], " low: ").concat(low, ", high: ").concat(high));
        }
      }
    }
    function expectArrayBuffersEqual(actual, expected) {
      var actualArray = new Float32Array(actual);
      var expectedArray = new Float32Array(expected);
      if (actualArray.length !== expectedArray.length) {
        throw new Error("Expected ArrayBuffer to be of length " + "".concat(expectedArray.length, ", but it was ").concat(actualArray.length));
      }
      for (var i = 0; i < expectedArray.length; i++) {
        if (actualArray[i] !== expectedArray[i]) {
          throw new Error("Expected ArrayBuffer value at ".concat(i, " to be ") + "".concat(expectedArray[i], " but got ").concat(actualArray[i], " instead"));
        }
      }
    }
    function encodeStrings(a) {
      for (var i = 0; i < a.length; i++) {
        var val = a[i];
        if (Array.isArray(val)) {
          encodeStrings(val);
        } else {
          a[i] = encodeString(val);
        }
      }
      return a;
    }
    function createVideoElement(source) {
      var video = document.createElement("video");
      if ("playsInline" in video) {
        video.playsInline = true;
      }
      video.muted = true;
      video.loop = true;
      video.style.position = "fixed";
      video.style.left = "0px";
      video.style.top = "0px";
      video.preload = "auto";
      video.appendChild(source);
      return new Promise(function(resolve) {
        video.addEventListener("loadeddata", function(_) {
          return resolve(video);
        });
        video.load();
      });
    }
    function play(video) {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              return [4, video.play()];
            case 1:
              _a.sent();
              if (!("requestVideoFrameCallback" in video)) return [3, 3];
              return [4, new Promise(function(resolve) {
                video.requestVideoFrameCallback(resolve);
              })];
            case 2:
              _a.sent();
              _a.label = 3;
            case 3:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    }
    var test_util = {
      __proto__: null,
      TEST_EPSILON_FLOAT16,
      createVideoElement,
      encodeStrings,
      expectArrayBuffersEqual,
      expectArraysClose,
      expectArraysEqual,
      expectNumbersClose,
      expectPromiseToFail,
      expectValuesInRange,
      play,
      testEpsilon
    };
    var MPRandGauss = (
      /** @class */
      function() {
        function MPRandGauss2(mean2, stdDeviation, dtype, truncated, seed) {
          this.mean = mean2;
          this.stdDev = stdDeviation;
          this.dtype = dtype;
          this.nextVal = NaN;
          this.truncated = truncated;
          if (this.truncated) {
            this.upper = this.mean + this.stdDev * 2;
            this.lower = this.mean - this.stdDev * 2;
          }
          var seedValue = seed ? seed : Math.random();
          this.random = seedrandom.alea(seedValue.toString());
        }
        MPRandGauss2.prototype.nextValue = function() {
          if (!isNaN(this.nextVal)) {
            var value = this.nextVal;
            this.nextVal = NaN;
            return value;
          }
          var resultX, resultY;
          var isValid = false;
          while (!isValid) {
            var v1 = void 0, v2 = void 0, s = void 0;
            do {
              v1 = 2 * this.random() - 1;
              v2 = 2 * this.random() - 1;
              s = v1 * v1 + v2 * v2;
            } while (s >= 1 || s === 0);
            var mul2 = Math.sqrt(-2 * Math.log(s) / s);
            resultX = this.mean + this.stdDev * v1 * mul2;
            resultY = this.mean + this.stdDev * v2 * mul2;
            if (!this.truncated || this.isValidTruncated(resultX)) {
              isValid = true;
            }
          }
          if (!this.truncated || this.isValidTruncated(resultY)) {
            this.nextVal = this.convertValue(resultY);
          }
          return this.convertValue(resultX);
        };
        MPRandGauss2.prototype.convertValue = function(value) {
          if (this.dtype == null || this.dtype === "float32") {
            return value;
          }
          return Math.round(value);
        };
        MPRandGauss2.prototype.isValidTruncated = function(value) {
          return value <= this.upper && value >= this.lower;
        };
        return MPRandGauss2;
      }()
    );
    var RandGamma = (
      /** @class */
      function() {
        function RandGamma2(alpha, beta, dtype, seed) {
          this.alpha = alpha;
          this.beta = 1 / beta;
          this.dtype = dtype;
          var seedValue = seed ? seed : Math.random();
          this.randu = seedrandom.alea(seedValue.toString());
          this.randn = new MPRandGauss(0, 1, dtype, false, this.randu());
          if (alpha < 1) {
            this.d = alpha + 2 / 3;
          } else {
            this.d = alpha - 1 / 3;
          }
          this.c = 1 / Math.sqrt(9 * this.d);
        }
        RandGamma2.prototype.nextValue = function() {
          var x2, v0, v1, x, u, v;
          while (true) {
            do {
              x = this.randn.nextValue();
              v = 1 + this.c * x;
            } while (v <= 0);
            v *= v * v;
            x2 = x * x;
            v0 = 1 - 0.331 * x2 * x2;
            v1 = 0.5 * x2 + this.d * (1 - v + Math.log(v));
            u = this.randu();
            if (u < v0 || Math.log(u) < v1) {
              break;
            }
          }
          v = 1 / this.beta * this.d * v;
          if (this.alpha < 1) {
            v *= Math.pow(this.randu(), 1 / this.alpha);
          }
          return this.convertValue(v);
        };
        RandGamma2.prototype.convertValue = function(value) {
          if (this.dtype === "float32") {
            return value;
          }
          return Math.round(value);
        };
        return RandGamma2;
      }()
    );
    var UniformRandom = (
      /** @class */
      function() {
        function UniformRandom2(min2, max2, dtype, seed) {
          if (min2 === void 0) {
            min2 = 0;
          }
          if (max2 === void 0) {
            max2 = 1;
          }
          var _this = this;
          this.canReturnFloat = function() {
            return _this.dtype == null || _this.dtype === "float32";
          };
          this.min = min2;
          this.range = max2 - min2;
          this.dtype = dtype;
          if (seed == null) {
            seed = Math.random();
          }
          if (typeof seed === "number") {
            seed = seed.toString();
          }
          if (!this.canReturnFloat() && this.range <= 1) {
            throw new Error("The difference between ".concat(min2, " - ").concat(max2, " <= 1 and dtype is not float"));
          }
          this.random = seedrandom.alea(seed);
        }
        UniformRandom2.prototype.convertValue = function(value) {
          if (this.canReturnFloat()) {
            return value;
          }
          return Math.round(value);
        };
        UniformRandom2.prototype.nextValue = function() {
          return this.convertValue(this.min + this.range * this.random());
        };
        return UniformRandom2;
      }()
    );
    function randomGamma_(shape, alpha, beta, dtype, seed) {
      if (beta === void 0) {
        beta = 1;
      }
      if (dtype === void 0) {
        dtype = "float32";
      }
      assertNonNegativeIntegerDimensions(shape);
      if (beta == null) {
        beta = 1;
      }
      if (dtype == null) {
        dtype = "float32";
      }
      if (dtype !== "float32" && dtype !== "int32") {
        throw new Error("Unsupported data type ".concat(dtype));
      }
      var rgamma = new RandGamma(alpha, beta, dtype, seed);
      var res = buffer(shape, dtype);
      for (var i = 0; i < res.values.length; i++) {
        res.values[i] = rgamma.nextValue();
      }
      return res.toTensor();
    }
    var randomGamma = /* @__PURE__ */ op({ randomGamma_ });
    function randomNormal_(shape, mean2, stdDev, dtype, seed) {
      if (mean2 === void 0) {
        mean2 = 0;
      }
      if (stdDev === void 0) {
        stdDev = 1;
      }
      assertNonNegativeIntegerDimensions(shape);
      if (dtype != null && dtype === "bool") {
        throw new Error("Unsupported data type ".concat(dtype));
      }
      var randGauss = new MPRandGauss(mean2, stdDev, dtype, false, seed);
      var res = buffer(shape, dtype);
      for (var i = 0; i < res.values.length; i++) {
        res.values[i] = randGauss.nextValue();
      }
      return res.toTensor();
    }
    var randomNormal = /* @__PURE__ */ op({ randomNormal_ });
    function randomStandardNormal_(shape, dtype, seed) {
      if (dtype != null && dtype === "bool") {
        throw new Error("Unsupported data type ".concat(dtype));
      }
      return randomNormal(shape, 0, 1, dtype, seed);
    }
    var randomStandardNormal = /* @__PURE__ */ op({ randomStandardNormal_ });
    function randomUniform_(shape, minval, maxval, dtype, seed) {
      if (minval === void 0) {
        minval = 0;
      }
      if (maxval === void 0) {
        maxval = 1;
      }
      if (dtype === void 0) {
        dtype = "float32";
      }
      assertNonNegativeIntegerDimensions(shape);
      var res = buffer(shape, dtype);
      var random = new UniformRandom(minval, maxval, null, seed);
      for (var i = 0; i < res.values.length; i++) {
        res.values[i] = random.nextValue();
      }
      return res.toTensor();
    }
    var randomUniform = /* @__PURE__ */ op({ randomUniform_ });
    function randomUniformInt_(shape, minval, maxval, seed) {
      return randomUniform(shape, minval, maxval, "int32", seed);
    }
    var randomUniformInt = /* @__PURE__ */ op({ randomUniformInt_ });
    function range(start, stop, step2, dtype) {
      if (step2 === void 0) {
        step2 = 1;
      }
      if (dtype === void 0) {
        dtype = "float32";
      }
      if (step2 === 0) {
        throw new Error("Cannot have a step of zero");
      }
      var attrs = { start, stop, step: step2, dtype };
      return ENGINE.runKernel(Range, {}, attrs);
    }
    function real_(input) {
      var $input = convertToTensor(input, "input", "real");
      var inputs = { input: $input };
      return ENGINE.runKernel(Real, inputs);
    }
    var real = /* @__PURE__ */ op({ real_ });
    function reciprocal_(x) {
      var $x = convertToTensor(x, "x", "reciprocal");
      var inputs = { x: $x };
      return ENGINE.runKernel(Reciprocal, inputs);
    }
    var reciprocal = /* @__PURE__ */ op({ reciprocal_ });
    function relu_(x) {
      var $x = convertToTensor(x, "x", "relu");
      var inputs = { x: $x };
      return ENGINE.runKernel(Relu, inputs);
    }
    var relu = /* @__PURE__ */ op({ relu_ });
    function relu6_(x) {
      var $x = convertToTensor(x, "x", "relu6");
      var inputs = { x: $x };
      return ENGINE.runKernel(Relu6, inputs);
    }
    var relu6 = /* @__PURE__ */ op({ relu6_ });
    function reverse_(x, axis) {
      var $x = convertToTensor(x, "x", "reverse");
      var inputs = { x: $x };
      var attrs = { dims: axis };
      return ENGINE.runKernel(Reverse, inputs, attrs);
    }
    var reverse = /* @__PURE__ */ op({ reverse_ });
    function reverse1d_(x) {
      var $x = convertToTensor(x, "x", "reverse");
      assert($x.rank === 1, function() {
        return "Error in reverse1D: x must be rank 1 but got rank ".concat($x.rank, ".");
      });
      return reverse($x, 0);
    }
    var reverse1d = /* @__PURE__ */ op({ reverse1d_ });
    function reverse2d_(x, axis) {
      var $x = convertToTensor(x, "x", "reverse");
      assert($x.rank === 2, function() {
        return "Error in reverse2D: x must be rank 2 but got rank ".concat($x.rank, ".");
      });
      return reverse($x, axis);
    }
    var reverse2d = /* @__PURE__ */ op({ reverse2d_ });
    function reverse3d_(x, axis) {
      var $x = convertToTensor(x, "x", "reverse");
      assert($x.rank === 3, function() {
        return "Error in reverse3D: x must be rank 3 but got rank ".concat($x.rank, ".");
      });
      return reverse($x, axis);
    }
    var reverse3d = /* @__PURE__ */ op({ reverse3d_ });
    function reverse4d_(x, axis) {
      var $x = convertToTensor(x, "x", "reverse");
      assert($x.rank === 4, function() {
        return "Error in reverse4D: x must be rank 4 but got rank ".concat($x.rank, ".");
      });
      return reverse($x, axis);
    }
    var reverse4d = /* @__PURE__ */ op({ reverse4d_ });
    function round_(x) {
      var $x = convertToTensor(x, "x", "round");
      var inputs = { x: $x };
      return ENGINE.runKernel(Round, inputs);
    }
    var round = /* @__PURE__ */ op({ round_ });
    function rsqrt_(x) {
      var $x = convertToTensor(x, "x", "rsqrt", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Rsqrt, inputs);
    }
    var rsqrt = /* @__PURE__ */ op({ rsqrt_ });
    function selu_(x) {
      var $x = convertToTensor(x, "x", "selu");
      var inputs = { x: $x };
      return ENGINE.runKernel(Selu, inputs);
    }
    var selu = /* @__PURE__ */ op({ selu_ });
    function separableConv2d_(x, depthwiseFilter, pointwiseFilter, strides, pad2, dilation, dataFormat) {
      if (dilation === void 0) {
        dilation = [1, 1];
      }
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      var $x = convertToTensor(x, "x", "separableConv2d");
      var $depthwiseFilter = convertToTensor(depthwiseFilter, "depthwiseFilter", "separableConv2d");
      var $pointwiseFilter = convertToTensor(pointwiseFilter, "pointwiseFilter", "separableConv2d");
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      if (dataFormat === "NCHW") {
        throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");
      }
      assert(x4D.rank === 4, function() {
        return "Error in separableConv2d: input must be rank 4, but got " + "rank ".concat(x4D.rank, ".");
      });
      assert($depthwiseFilter.rank === 4, function() {
        return "Error in separableConv2d: depthwise filter must be rank 4, but " + "got rank ".concat($depthwiseFilter.rank, ".");
      });
      assert($pointwiseFilter.rank === 4, function() {
        return "Error in separableConv2d: pointwise filter must be rank 4, but " + "got rank ".concat($depthwiseFilter.rank, ".");
      });
      assert($pointwiseFilter.shape[0] === 1, function() {
        return "Error in separableConv2d: the first dimension of pointwise filter " + " must be 1, but got ".concat($pointwiseFilter.shape[0], ".");
      });
      assert($pointwiseFilter.shape[1] === 1, function() {
        return "Error in separableConv2d: the second dimension of pointwise " + "filter must be 1, but got ".concat($pointwiseFilter.shape[1], ".");
      });
      var inChannels = $depthwiseFilter.shape[2];
      var channelMultiplier = $depthwiseFilter.shape[3];
      assert($pointwiseFilter.shape[2] === inChannels * channelMultiplier, function() {
        return "Error in separableConv2d: the third dimension of pointwise filter " + "must be ".concat(inChannels * channelMultiplier, ", ") + "but got ".concat($pointwiseFilter.shape[2], ".");
      });
      var depthwise = depthwiseConv2d$1(x4D, $depthwiseFilter, strides, pad2, dataFormat, dilation);
      var pointwiseStride = 1;
      var res = conv2d$1(depthwise, $pointwiseFilter, pointwiseStride, "valid", dataFormat);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var separableConv2d = /* @__PURE__ */ op({ separableConv2d_ });
    function setdiff1dAsync_(x, y) {
      return __awaiter(this, void 0, void 0, function() {
        var $x, $y, xVals, yVals, ySet, outputSize, i, buffer2, indices, i, p;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              $x = convertToTensor(x, "x", "setdiff1d");
              $y = convertToTensor(y, "y", "setdiff1d");
              assert($x.dtype === $y.dtype, function() {
                return "x and y should have the same dtype, but got x (".concat($x.dtype, ") and y (").concat($y.dtype, ").");
              });
              assert($x.rank === 1, function() {
                return "x should be 1D tensor, but got x (".concat($x.shape, ").");
              });
              assert($y.rank === 1, function() {
                return "y should be 1D tensor, but got y (".concat($y.shape, ").");
              });
              return [4, $x.data()];
            case 1:
              xVals = _a.sent();
              return [4, $y.data()];
            case 2:
              yVals = _a.sent();
              ySet = new Set(yVals);
              outputSize = 0;
              for (i = 0; i < xVals.length; i++) {
                if (!ySet.has(xVals[i])) {
                  outputSize++;
                }
              }
              buffer2 = new TensorBuffer([outputSize], $x.dtype);
              indices = new TensorBuffer([outputSize], "int32");
              for (i = 0, p = 0; i < xVals.length; i++) {
                if (!ySet.has(xVals[i])) {
                  buffer2.values[p] = xVals[i];
                  indices.values[p] = i;
                  p++;
                }
              }
              return [2, [buffer2.toTensor(), indices.toTensor()]];
          }
        });
      });
    }
    var setdiff1dAsync = setdiff1dAsync_;
    function sign_(x) {
      var $x = convertToTensor(x, "x", "sign");
      var inputs = { x: $x };
      return ENGINE.runKernel(Sign, inputs);
    }
    var sign = /* @__PURE__ */ op({ sign_ });
    function sin_(x) {
      var $x = convertToTensor(x, "x", "sin", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Sin, inputs);
    }
    var sin = /* @__PURE__ */ op({ sin_ });
    function sinh_(x) {
      var $x = convertToTensor(x, "x", "sinh");
      var inputs = { x: $x };
      return ENGINE.runKernel(Sinh, inputs);
    }
    var sinh = /* @__PURE__ */ op({ sinh_ });
    function slice1d_(x, begin, size) {
      var $x = convertToTensor(x, "x", "slice1d");
      assert($x.rank === 1, function() {
        return "slice1d expects a rank-1 tensor, but got a rank-".concat($x.rank, " tensor");
      });
      return slice($x, [begin], [size]);
    }
    var slice1d = /* @__PURE__ */ op({ slice1d_ });
    function slice2d_(x, begin, size) {
      var $x = convertToTensor(x, "x", "slice2d");
      assert($x.rank === 2, function() {
        return "slice2d expects a rank-2 tensor, but got a rank-".concat($x.rank, " tensor");
      });
      return slice($x, begin, size);
    }
    var slice2d = /* @__PURE__ */ op({ slice2d_ });
    function slice3d_(x, begin, size) {
      var $x = convertToTensor(x, "x", "slice3d");
      assert($x.rank === 3, function() {
        return "slice3d expects a rank-3 tensor, but got a rank-".concat($x.rank, " tensor");
      });
      return slice($x, begin, size);
    }
    var slice3d = /* @__PURE__ */ op({ slice3d_ });
    function slice4d_(x, begin, size) {
      var $x = convertToTensor(x, "x", "slice4d");
      assert($x.rank === 4, function() {
        return "slice4d expects a rank-4 tensor, but got a rank-".concat($x.rank, " tensor");
      });
      return slice($x, begin, size);
    }
    var slice4d = /* @__PURE__ */ op({ slice4d_ });
    function softmax_(logits, dim) {
      if (dim === void 0) {
        dim = -1;
      }
      var $logits = convertToTensor(logits, "logits", "softmax", "float32");
      if (dim === -1) {
        dim = $logits.rank - 1;
      }
      if (dim !== $logits.rank - 1) {
        throw Error("Softmax along a non-last dimension is not yet supported. " + "Logits was rank ".concat($logits.rank, " and dim was ").concat(dim));
      }
      var inputs = { logits: $logits };
      var attrs = { dim };
      return ENGINE.runKernel(Softmax, inputs, attrs);
    }
    var softmax = /* @__PURE__ */ op({ softmax_ });
    function fft_(input) {
      assert(input.dtype === "complex64", function() {
        return "The dtype for tf.spectral.fft() must be complex64 " + "but got ".concat(input.dtype, ".");
      });
      var inputs = { input };
      return ENGINE.runKernel(FFT, inputs);
    }
    var fft = /* @__PURE__ */ op({ fft_ });
    function ifft_(input) {
      assert(input.dtype === "complex64", function() {
        return "The dtype for tf.spectral.ifft() must be complex64 " + "but got ".concat(input.dtype, ".");
      });
      var inputs = { input };
      return ENGINE.runKernel(IFFT, inputs);
    }
    var ifft = /* @__PURE__ */ op({ ifft_ });
    function irfft_(input) {
      var innerDimensionSize = input.shape[input.shape.length - 1];
      var batch = input.size / innerDimensionSize;
      var ret;
      if (innerDimensionSize <= 2) {
        var complexInput = reshape(input, [batch, innerDimensionSize]);
        ret = ifft(complexInput);
      } else {
        var outputShape = [batch, 2 * (innerDimensionSize - 1)];
        var realInput = reshape(real(input), [batch, innerDimensionSize]);
        var imagInput = reshape(imag(input), [batch, innerDimensionSize]);
        var realConjugate = reverse(slice(realInput, [0, 1], [batch, innerDimensionSize - 2]), 1);
        var imagConjugate = mul(reverse(slice(imagInput, [0, 1], [batch, innerDimensionSize - 2]), 1), scalar(-1));
        var r = concat([realInput, realConjugate], 1);
        var i = concat([imagInput, imagConjugate], 1);
        var complexInput = reshape(complex(r, i), [outputShape[0], outputShape[1]]);
        ret = ifft(complexInput);
      }
      ret = real(ret);
      if (input.rank === 3 && input.shape[0] !== 0) {
        var temp = ret;
        var batch_1 = input.shape[0];
        ret = reshape(ret, [batch_1, ret.shape[0] / batch_1, ret.shape[1]]);
        temp.dispose();
      }
      return ret;
    }
    var irfft = /* @__PURE__ */ op({ irfft_ });
    function split_(x, numOrSizeSplits, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $x = convertToTensor(x, "x", "split");
      var inputs = { x: $x };
      var attr = { numOrSizeSplits, axis };
      return ENGINE.runKernel(SplitV, inputs, attr);
    }
    var split = /* @__PURE__ */ op({ split_ });
    function rfft_(input, fftLength) {
      assert(input.dtype === "float32", function() {
        return "The dtype for rfft() must be real value but got ".concat(input.dtype);
      });
      var innerDimensionSize = input.shape[input.shape.length - 1];
      var batch = input.size / innerDimensionSize;
      var adjustedInput;
      if (fftLength != null && fftLength < innerDimensionSize) {
        var begin = input.shape.map(function(v) {
          return 0;
        });
        var size = input.shape.map(function(v) {
          return v;
        });
        size[input.shape.length - 1] = fftLength;
        adjustedInput = slice(input, begin, size);
        innerDimensionSize = fftLength;
      } else if (fftLength != null && fftLength > innerDimensionSize) {
        var zerosShape = input.shape.map(function(v) {
          return v;
        });
        zerosShape[input.shape.length - 1] = fftLength - innerDimensionSize;
        adjustedInput = concat([input, zeros(zerosShape)], input.shape.length - 1);
        innerDimensionSize = fftLength;
      } else {
        adjustedInput = input;
      }
      var zerosInput = zerosLike(adjustedInput);
      var complexInput = reshape(complex(adjustedInput, zerosInput), [batch, innerDimensionSize]);
      var ret = fft(complexInput);
      var half = Math.floor(innerDimensionSize / 2) + 1;
      var realValues = real(ret);
      var imagValues = imag(ret);
      var realComplexConjugate = split(realValues, [half, innerDimensionSize - half], realValues.shape.length - 1);
      var imagComplexConjugate = split(imagValues, [half, innerDimensionSize - half], imagValues.shape.length - 1);
      var outputShape = adjustedInput.shape.slice();
      outputShape[adjustedInput.shape.length - 1] = half;
      return reshape(complex(realComplexConjugate[0], imagComplexConjugate[0]), outputShape);
    }
    var rfft = /* @__PURE__ */ op({ rfft_ });
    function squaredDifference_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "squaredDifference");
      var $b = convertToTensor(b, "b", "squaredDifference");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      var attrs = {};
      return ENGINE.runKernel(SquaredDifference, inputs, attrs);
    }
    var squaredDifference = /* @__PURE__ */ op({ squaredDifference_ });
    function squeeze_(x, axis) {
      var $x = convertToTensor(x, "x", "squeeze", "string_or_numeric");
      return reshape($x, squeezeShape($x.shape, axis).newShape);
    }
    var squeeze = /* @__PURE__ */ op({ squeeze_ });
    function stack_(tensors, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $tensors = convertToTensorArray(tensors, "tensors", "stack", "string_or_numeric");
      assert($tensors.length >= 1, function() {
        return "Pass at least one tensor to tf.stack";
      });
      if ($tensors.length > 0) {
        assert(axis <= $tensors[0].rank, function() {
          return "Axis must be <= rank of the tensor";
        });
      }
      var inputs = $tensors;
      var attrs = { axis };
      return ENGINE.runKernel(Pack, inputs, attrs);
    }
    var stack = /* @__PURE__ */ op({ stack_ });
    function step_(x, alpha) {
      if (alpha === void 0) {
        alpha = 0;
      }
      var $x = convertToTensor(x, "x", "step");
      var inputs = { x: $x };
      var attrs = { alpha };
      return ENGINE.runKernel(Step, inputs, attrs);
    }
    var step = /* @__PURE__ */ op({ step_ });
    function stridedSlice_(x, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask) {
      if (beginMask === void 0) {
        beginMask = 0;
      }
      if (endMask === void 0) {
        endMask = 0;
      }
      if (ellipsisMask === void 0) {
        ellipsisMask = 0;
      }
      if (newAxisMask === void 0) {
        newAxisMask = 0;
      }
      if (shrinkAxisMask === void 0) {
        shrinkAxisMask = 0;
      }
      var $x = convertToTensor(x, "x", "stridedSlice", "string_or_numeric");
      var inputs = { x: $x };
      var attrs = {
        begin,
        end,
        strides,
        beginMask,
        endMask,
        ellipsisMask,
        newAxisMask,
        shrinkAxisMask
      };
      return ENGINE.runKernel(StridedSlice, inputs, attrs);
    }
    var stridedSlice = /* @__PURE__ */ op({ stridedSlice_ });
    function tan_(x) {
      var $x = convertToTensor(x, "x", "tan", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Tan, inputs);
    }
    var tan = /* @__PURE__ */ op({ tan_ });
    function tensor1d(values, dtype) {
      assertNonNull(values);
      var inferredShape = inferShape(values, dtype);
      if (inferredShape.length !== 1) {
        throw new Error("tensor1d() requires values to be a flat/TypedArray");
      }
      var shape = null;
      return makeTensor(values, shape, inferredShape, dtype);
    }
    function tensor2d(values, shape, dtype) {
      assertNonNull(values);
      if (shape != null && shape.length !== 2) {
        throw new Error("tensor2d() requires shape to have two numbers");
      }
      var inferredShape = inferShape(values, dtype);
      if (inferredShape.length !== 2 && inferredShape.length !== 1) {
        throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");
      }
      if (inferredShape.length === 1 && shape == null) {
        throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");
      }
      return makeTensor(values, shape, inferredShape, dtype);
    }
    function tensor3d(values, shape, dtype) {
      assertNonNull(values);
      if (shape != null && shape.length !== 3) {
        throw new Error("tensor3d() requires shape to have three numbers");
      }
      var inferredShape = inferShape(values, dtype);
      if (inferredShape.length !== 3 && inferredShape.length !== 1) {
        throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");
      }
      if (inferredShape.length === 1 && shape == null) {
        throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");
      }
      return makeTensor(values, shape, inferredShape, dtype);
    }
    function tensor4d(values, shape, dtype) {
      assertNonNull(values);
      if (shape != null && shape.length !== 4) {
        throw new Error("tensor4d() requires shape to have four numbers");
      }
      var inferredShape = inferShape(values, dtype);
      if (inferredShape.length !== 4 && inferredShape.length !== 1) {
        throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");
      }
      if (inferredShape.length === 1 && shape == null) {
        throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");
      }
      return makeTensor(values, shape, inferredShape, dtype);
    }
    function tensor5d(values, shape, dtype) {
      assertNonNull(values);
      if (shape != null && shape.length !== 5) {
        throw new Error("tensor5d() requires shape to have five numbers");
      }
      var inferredShape = inferShape(values, dtype);
      if (inferredShape.length !== 5 && inferredShape.length !== 1) {
        throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");
      }
      if (inferredShape.length === 1 && shape == null) {
        throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");
      }
      return makeTensor(values, shape, inferredShape, dtype);
    }
    function tensor6d(values, shape, dtype) {
      assertNonNull(values);
      if (shape != null && shape.length !== 6) {
        throw new Error("tensor6d() requires shape to have six numbers");
      }
      var inferredShape = inferShape(values, dtype);
      if (inferredShape.length !== 6 && inferredShape.length !== 1) {
        throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");
      }
      if (inferredShape.length === 1 && shape == null) {
        throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");
      }
      shape = shape || inferredShape;
      return makeTensor(values, shape, inferredShape, dtype);
    }
    function validateUpdateShape(shape, indices, updates) {
      var sliceDim = indices.rank > 1 ? indices.shape[indices.rank - 1] : 1;
      var batchDim = indices.rank > 1 ? indices.rank - 1 : 1;
      var shapeError = "Must have updates.shape = indices.shape[:batchDim] + " + "shape[sliceDim:], got updates.shape: ".concat(updates.shape) + ", indices.shape: ".concat(indices.shape, ", shape: ").concat(shape) + ", sliceDim: ".concat(sliceDim, ", and batchDim: ").concat(batchDim, ".");
      if (updates.rank < batchDim) {
        throw new Error(shapeError + " update.rank < ".concat(batchDim, ". "));
      }
      if (shape.length < sliceDim + (updates.rank - batchDim)) {
        throw new Error(shapeError + " Output shape length < ".concat(sliceDim + (updates.rank - batchDim)));
      }
      if (updates.rank !== batchDim + shape.length - sliceDim) {
        throw new Error(shapeError + " update.rank != ".concat(batchDim + shape.length - sliceDim));
      }
      for (var d = 0; d < batchDim; ++d) {
        if (updates.shape[d] !== indices.shape[d]) {
          throw new Error(shapeError + " updates.shape[".concat(d, "] (").concat(updates.shape[d], ") != indices.shape[").concat(d, "] (").concat(indices.shape[d], ")."));
        }
      }
      for (var d = 0; d < updates.rank - batchDim; ++d) {
        if (updates.shape[d + batchDim] !== shape[d + sliceDim]) {
          throw new Error(shapeError + " updates.shape[".concat(d + batchDim, "] (").concat(updates.shape[d + batchDim], ") != shape[").concat(d + batchDim, "] (").concat(shape[d + batchDim], ")"));
        }
      }
    }
    function validateInput$1(updates, indices, shape) {
      if (indices.rank < 1) {
        throw new Error("tf.scatterND() expects the indices to be rank 1 or higher," + " but the rank was ".concat(indices.rank, "."));
      }
      if (updates.rank < 1) {
        throw new Error("tf.scatterND() expects the updates to be rank 1 or higher," + " but the rank was ".concat(updates.rank, "."));
      }
      if (indices.dtype !== "int32") {
        throw new Error("The dtype of 'indices' should be int32, but got dtype: ".concat(indices.dtype));
      }
      if (shape.length < 1) {
        throw new Error("Output rank must be greater or equal to 1, but got shape: ".concat(shape));
      }
      if (shape.length === 0) {
        if (indices.size === 0) {
          throw new Error("Indices specified for empty output. indices shape: ".concat(indices.shape));
        }
        if (updates.size === 0) {
          throw new Error("Updates specified for empty output. updates shape: ".concat(updates.shape));
        }
      }
      validateUpdateShape(shape, indices, updates);
    }
    function calculateShapes(updates, indices, shape) {
      var indicesRank = indices.shape.length;
      var sliceRank = indicesRank > 1 ? indices.shape[indicesRank - 1] : 1;
      var totalNd = shape.length;
      var sliceSize = 1;
      for (var i = sliceRank; i < totalNd; ++i) {
        sliceSize *= shape[i];
      }
      var safeSliceDim = sliceRank < 1 ? 1 : sliceRank;
      var numUpdates = sizeFromShape(indices.shape) / safeSliceDim;
      var strides = __spreadArray(__spreadArray([], __read(computeStrides(shape.slice(0, sliceRank))), false), [1], false);
      var outputSize = sizeFromShape(shape);
      return { sliceRank, numUpdates, sliceSize, strides, outputSize };
    }
    var scatter_nd_util = {
      __proto__: null,
      calculateShapes,
      validateInput: validateInput$1,
      validateUpdateShape
    };
    function tensorScatterUpdate_(tensor2, indices, updates) {
      var $tensor = convertToTensor(tensor2, "tensor", "tensorScatterupdate");
      var $indices = convertToTensor(indices, "indices", "tensorScatterupdate", "int32");
      var $updates = convertToTensor(updates, "updates", "tensorScatterupdate");
      validateInput$1($updates, $indices, $tensor.shape);
      if ($tensor.dtype !== $updates.dtype) {
        throw new Error("tensor and updates must have the same dtype, instead they are ".concat($tensor.dtype, " and ").concat($updates.dtype, "."));
      }
      var inputs = {
        tensor: $tensor,
        indices: $indices,
        updates: $updates
      };
      var attrs = {};
      return ENGINE.runKernel(TensorScatterUpdate, inputs, attrs);
    }
    var tensorScatterUpdate = op({ tensorScatterUpdate_ });
    function topk_(x, k, sorted) {
      if (k === void 0) {
        k = 1;
      }
      if (sorted === void 0) {
        sorted = true;
      }
      var $x = convertToTensor(x, "x", "topk");
      if ($x.rank === 0) {
        throw new Error("topk() expects the input to be of rank 1 or higher");
      }
      var lastDim = $x.shape[$x.shape.length - 1];
      if (k < 0) {
        throw new Error("'k' passed to topk() must be >= 0 but got ".concat(k));
      }
      if (k > lastDim) {
        throw new Error("'k' passed to topk() must be <= the last dimension (".concat(lastDim, ") ") + "but got ".concat(k));
      }
      var inputs = { x: $x };
      var attrs = { k, sorted };
      var _a = __read(ENGINE.runKernel(TopK, inputs, attrs), 2), values = _a[0], indices = _a[1];
      return { values, indices };
    }
    var topk = /* @__PURE__ */ op({ topk_ });
    function truncatedNormal_(shape, mean2, stdDev, dtype, seed) {
      if (mean2 === void 0) {
        mean2 = 0;
      }
      if (stdDev === void 0) {
        stdDev = 1;
      }
      assertNonNegativeIntegerDimensions(shape);
      if (dtype != null && dtype === "bool") {
        throw new Error("Unsupported data type $ { dtype }");
      }
      var randGauss = new MPRandGauss(mean2, stdDev, dtype, true, seed);
      var res = buffer(shape, dtype);
      for (var i = 0; i < res.values.length; i++) {
        res.values[i] = randGauss.nextValue();
      }
      return res.toTensor();
    }
    var truncatedNormal = /* @__PURE__ */ op({ truncatedNormal_ });
    function unique_(x, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $x = convertToTensor(x, "x", "unique", "string_or_numeric");
      assert($x.rank > 0, function() {
        return "The input tensor must be at least 1D";
      });
      var inputs = { x: $x };
      var attrs = { axis };
      var _a = __read(ENGINE.runKernel(Unique, inputs, attrs), 2), values = _a[0], indices = _a[1];
      return { values, indices };
    }
    var unique = /* @__PURE__ */ op({ unique_ });
    function unsortedSegmentSum_(x, segmentIds, numSegments) {
      var $x = convertToTensor(x, "x", "unsortedSegmentSum");
      var $segmentIds = convertToTensor(segmentIds, "segmentIds", "unsortedSegmentSum", "int32");
      assert(isInt(numSegments), function() {
        return "numSegments must be of dtype int";
      });
      var inputs = { x: $x, segmentIds: $segmentIds };
      var attrs = { numSegments };
      return ENGINE.runKernel(UnsortedSegmentSum, inputs, attrs);
    }
    var unsortedSegmentSum = /* @__PURE__ */ op({ unsortedSegmentSum_ });
    function unstack_(x, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $x = convertToTensor(x, "x", "unstack", "string_or_numeric");
      assert(axis >= -$x.shape.length && axis < $x.shape.length, function() {
        return "Axis = ".concat(axis, " is not in [-").concat($x.shape.length, ", ").concat($x.shape.length, ")");
      });
      var inputs = { value: $x };
      var attrs = { axis };
      return ENGINE.runKernel(Unpack, inputs, attrs);
    }
    var unstack = /* @__PURE__ */ op({ unstack_ });
    function upperBound(sortedSequence, values) {
      return searchSorted(sortedSequence, values, "right");
    }
    function variable(initialValue, trainable, name, dtype) {
      if (trainable === void 0) {
        trainable = true;
      }
      return ENGINE.makeVariable(initialValue, trainable, name, dtype);
    }
    function whereImpl(condShape, condVals) {
      var indices = [];
      for (var i = 0; i < condVals.length; i++) {
        if (condVals[i]) {
          indices.push(i);
        }
      }
      var inBuffer = buffer(condShape, "int32");
      var out = buffer([indices.length, condShape.length], "int32");
      for (var i = 0; i < indices.length; i++) {
        var loc = inBuffer.indexToLoc(indices[i]);
        var offset = i * condShape.length;
        out.values.set(loc, offset);
      }
      return out.toTensor();
    }
    function whereAsync_(condition) {
      return __awaiter(this, void 0, void 0, function() {
        var $condition, vals, res;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              $condition = convertToTensor(condition, "condition", "whereAsync", "bool");
              return [4, $condition.data()];
            case 1:
              vals = _a.sent();
              res = whereImpl($condition.shape, vals);
              if (condition !== $condition) {
                $condition.dispose();
              }
              return [2, res];
          }
        });
      });
    }
    var whereAsync = whereAsync_;
    function booleanMaskAsync_(tensor2, mask, axis) {
      return __awaiter(this, void 0, void 0, function() {
        var $tensor, $mask, axisFrom, maskDim, tensorShape, leadingSize, i, targetTensorShape, reshapedTensor, reshapedMask, positivePositions, indices, res;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              $tensor = convertToTensor(tensor2, "tensor", "boolMask");
              $mask = convertToTensor(mask, "mask", "boolMask", "bool");
              axisFrom = axis == null ? 0 : axis;
              maskDim = $mask.rank;
              tensorShape = $tensor.shape;
              assert(maskDim > 0, function() {
                return "mask cannot be scalar";
              });
              assertShapesMatch(tensorShape.slice(axisFrom, axisFrom + maskDim), $mask.shape, "mask's shape must match the first K dimensions of tensor's shape,");
              leadingSize = 1;
              for (i = axisFrom; i < axisFrom + maskDim; i++) {
                leadingSize *= tensorShape[i];
              }
              targetTensorShape = tensorShape.slice(0, axisFrom).concat([leadingSize], tensorShape.slice(axisFrom + maskDim));
              reshapedTensor = reshape($tensor, targetTensorShape);
              reshapedMask = reshape($mask, [-1]);
              return [4, whereAsync(reshapedMask)];
            case 1:
              positivePositions = _a.sent();
              indices = squeeze(positivePositions, [1]);
              res = gather(reshapedTensor, indices, axisFrom);
              if (tensor2 !== $tensor) {
                $tensor.dispose();
              }
              if (mask !== $mask) {
                $mask.dispose();
              }
              indices.dispose();
              reshapedTensor.dispose();
              reshapedMask.dispose();
              positivePositions.dispose();
              return [2, res];
          }
        });
      });
    }
    var booleanMaskAsync = booleanMaskAsync_;
    function transpose_(x, perm, conjugate) {
      var $x = convertToTensor(x, "x", "transpose");
      if (perm == null) {
        perm = $x.shape.map(function(s, i) {
          return i;
        }).reverse();
      }
      assert($x.rank === perm.length, function() {
        return "Error in transpose: rank of input ".concat($x.rank, " ") + "must match length of perm ".concat(perm, ".");
      });
      perm.forEach(function(axis) {
        assert(axis >= 0 && axis < $x.rank, function() {
          return "All entries in 'perm' must be between 0 and ".concat($x.rank - 1) + " but got ".concat(perm);
        });
      });
      if ($x.rank <= 1) {
        return $x.clone();
      }
      var inputs = { x: $x };
      var attrs = { perm };
      if ($x.dtype === "complex64") {
        return tidy(function() {
          var $real = real($x);
          var $imag = imag($x);
          $real = ENGINE.runKernel(Transpose, { x: $real }, attrs);
          $imag = ENGINE.runKernel(Transpose, { x: $imag }, attrs);
          if (conjugate) {
            $imag = neg($imag);
          }
          return complex($real, $imag);
        });
      }
      return ENGINE.runKernel(Transpose, inputs, attrs);
    }
    var transpose = /* @__PURE__ */ op({ transpose_ });
    function movingAverage_(v, x, decay, step2, zeroDebias) {
      if (zeroDebias === void 0) {
        zeroDebias = true;
      }
      var $v = convertToTensor(v, "v", "movingAverage");
      var $x = convertToTensor(x, "x", "movingAverage");
      var $decay = convertToTensor(decay, "decay", "movingAverage");
      assertTypesMatch($v, $x);
      assert(arraysEqual($v.shape, $x.shape), function() {
        return "Shape mismatch in v and x";
      });
      var one = scalar(1);
      var oneMinusDecay = sub(one, $decay);
      var update = mul(sub($x, $v), oneMinusDecay);
      if (zeroDebias) {
        assert(step2 != null, function() {
          return "When using zeroDebias: true, step is required.";
        });
        var $step = convertToTensor(step2, "step", "movingAverage");
        update = div(update, sub(one, pow($decay, $step)));
      }
      return add($v, update);
    }
    var movingAverage = /* @__PURE__ */ op({ movingAverage_ });
    function scatterND_(indices, updates, shape) {
      assertNonNegativeIntegerDimensions(shape);
      var $indices = convertToTensor(indices, "indices", "scatterND", "int32");
      var $updates = convertToTensor(updates, "updates", "scatterND");
      validateInput$1($updates, $indices, shape);
      var inputs = { indices: $indices, updates: $updates };
      var attrs = { shape };
      return ENGINE.runKernel(ScatterNd, inputs, attrs);
    }
    var scatterND = /* @__PURE__ */ op({ scatterND_ });
    function validateInput(sparseIndices, sparseValues, outputShape, defaultValues) {
      if (sparseIndices.dtype !== "int32") {
        throw new Error("tf.sparseToDense() expects the indices to be int32 type," + " but the dtype was ".concat(sparseIndices.dtype, "."));
      }
      if (sparseIndices.rank > 2) {
        throw new Error("sparseIndices should be a scalar, vector, or matrix," + " but got shape ".concat(sparseIndices.shape, "."));
      }
      var numElems = sparseIndices.rank > 0 ? sparseIndices.shape[0] : 1;
      var numDims = sparseIndices.rank > 1 ? sparseIndices.shape[1] : 1;
      if (outputShape.length !== numDims) {
        throw new Error("outputShape has incorrect number of elements:," + " ".concat(outputShape.length, ", should be: ").concat(numDims, "."));
      }
      var numValues = sparseValues.size;
      if (!(sparseValues.rank === 0 || sparseValues.rank === 1 && numValues === numElems)) {
        throw new Error("sparseValues has incorrect shape " + "".concat(sparseValues.shape, ", should be [] or [").concat(numElems, "]"));
      }
      if (sparseValues.dtype !== defaultValues.dtype) {
        throw new Error("sparseValues.dtype must match defaultValues.dtype");
      }
    }
    function sparseToDense_(sparseIndices, sparseValues, outputShape, defaultValue) {
      if (defaultValue === void 0) {
        defaultValue = 0;
      }
      assertNonNegativeIntegerDimensions(outputShape);
      var $sparseIndices = convertToTensor(sparseIndices, "sparseIndices", "sparseToDense", "int32");
      var $sparseValues = convertToTensor(sparseValues, "sparseValues", "sparseToDense", "string_or_numeric");
      var $defaultValue = convertToTensor(defaultValue, "defaultValue", "sparseToDense", $sparseValues.dtype);
      validateInput($sparseIndices, $sparseValues, outputShape, $defaultValue);
      var inputs = {
        sparseIndices: $sparseIndices,
        sparseValues: $sparseValues,
        defaultValue: $defaultValue
      };
      var attrs = { outputShape };
      return ENGINE.runKernel(SparseToDense, inputs, attrs);
    }
    var sparseToDense = /* @__PURE__ */ op({ sparseToDense_ });
    function gatherND_(x, indices) {
      var $indices = convertToTensor(indices, "indices", "gatherND", "int32");
      var $x = convertToTensor(x, "x", "gatherND", "string_or_numeric");
      var inputs = { params: $x, indices: $indices };
      return ENGINE.runKernel(GatherNd, inputs);
    }
    var gatherND = /* @__PURE__ */ op({ gatherND_ });
    function getNoiseShape(x, noiseShape) {
      if (noiseShape == null) {
        return x.shape.slice();
      }
      if (arraysEqual(x.shape, noiseShape)) {
        return noiseShape;
      }
      if (x.shape.length === noiseShape.length) {
        var newDimension = [];
        for (var i = 0; i < x.shape.length; i++) {
          if (noiseShape[i] == null && x.shape[i] != null) {
            newDimension.push(x.shape[i]);
          } else {
            newDimension.push(noiseShape[i]);
          }
        }
        return newDimension;
      }
      return noiseShape;
    }
    function dropout_(x, rate, noiseShape, seed) {
      var $x = convertToTensor(x, "x", "dropout");
      assert($x.dtype === "float32", function() {
        return "x has to be a floating point tensor since it's going to be " + "scaled, but got a ".concat($x.dtype, " tensor instead.");
      });
      assert(rate >= 0 && rate < 1, function() {
        return "rate must be a float in the range [0, 1), but got ".concat(rate, ".");
      });
      if (rate === 0) {
        return x instanceof Tensor ? $x.clone() : $x;
      }
      var $noiseShape = getNoiseShape($x, noiseShape);
      var keepProb = 1 - rate;
      var multiplier = div(floor(add(randomUniform($noiseShape, 0, 1, "float32", seed), keepProb)), keepProb);
      return mul($x, multiplier);
    }
    var dropout = /* @__PURE__ */ op({ dropout_ });
    function enclosingPowerOfTwo(value) {
      return Math.floor(Math.pow(2, Math.ceil(Math.log(value) / Math.log(2))));
    }
    function cosineWindow(windowLength, a, b) {
      var even = 1 - windowLength % 2;
      var newValues = new Float32Array(windowLength);
      for (var i = 0; i < windowLength; ++i) {
        var cosArg = 2 * Math.PI * i / (windowLength + even - 1);
        newValues[i] = a - b * Math.cos(cosArg);
      }
      return tensor1d(newValues, "float32");
    }
    function inTopKAsync_(predictions, targets, k) {
      if (k === void 0) {
        k = 1;
      }
      return __awaiter(this, void 0, void 0, function() {
        var $predictions, $targets, lastDim, predictionsVals, targetsVals, _a, batch, size, precision, b, offset, vals, valAndInd, i, i;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              $predictions = convertToTensor(predictions, "predictions", "inTopK");
              $targets = convertToTensor(targets, "targets", "inTopK");
              assert($predictions.rank > 1, function() {
                return "inTopK() expects the predictions to be of rank 2 or higher, " + "but got ".concat($predictions.rank);
              });
              assert($predictions.rank - 1 === $targets.rank, function() {
                return "predictions rank should be 1 larger than targets rank, but got predictions rank " + "".concat($predictions.rank, " and targets rank ").concat($targets.rank);
              });
              assertShapesMatch($predictions.shape.slice(0, $predictions.shape.length - 1), $targets.shape, "predictions's shape should be align with the targets' shape, except the last dimension.");
              lastDim = $predictions.shape[$predictions.shape.length - 1];
              assert(k > 0 && k <= lastDim, function() {
                return "'k' passed to inTopK() must be > 0 && <= the predictions last " + "dimension (".concat(lastDim, "), but got ").concat(k);
              });
              return [4, $predictions.data()];
            case 1:
              predictionsVals = _b.sent();
              return [4, $targets.data()];
            case 2:
              targetsVals = _b.sent();
              _a = __read([predictionsVals.length / lastDim, lastDim], 2), batch = _a[0], size = _a[1];
              precision = getTypedArrayFromDType("bool", batch);
              for (b = 0; b < batch; b++) {
                offset = b * size;
                vals = predictionsVals.subarray(offset, offset + size);
                valAndInd = [];
                for (i = 0; i < vals.length; i++) {
                  valAndInd.push({ value: vals[i], index: i });
                }
                valAndInd.sort(function(a, b2) {
                  return b2.value - a.value;
                });
                precision[b] = 0;
                for (i = 0; i < k; i++) {
                  if (valAndInd[i].index === targetsVals[b]) {
                    precision[b] = 1;
                    break;
                  }
                }
              }
              if (predictions !== $predictions) {
                $predictions.dispose();
              }
              if (targets !== $targets) {
                $targets.dispose();
              }
              return [2, tensor(precision, $targets.shape, "bool")];
          }
        });
      });
    }
    var inTopKAsync = inTopKAsync_;
    function conv2DBackpropFilter_(x, dy, filterShape, strides, pad2, dataFormat, dimRoundingMode) {
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      var x4D = x;
      if (x.rank === 3) {
        x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
      }
      var dy4D = dy;
      if (dy4D.rank === 3) {
        dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
      }
      assert(x4D.rank === 4, function() {
        return "Error in conv2dDerFilter: input must be rank 4, but got shape " + "".concat(x4D.shape, ".");
      });
      assert(dy4D.rank === 4, function() {
        return "Error in conv2dDerFilter: dy must be rank 4, but got shape " + "".concat(dy4D.shape, ".");
      });
      assert(filterShape.length === 4, function() {
        return "Error in conv2dDerFilter: filterShape must be length 4, but got " + "".concat(filterShape, ".");
      });
      var inDepth = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
      var outDepth = dataFormat === "NHWC" ? dy4D.shape[3] : dy4D.shape[1];
      assert(inDepth === filterShape[2], function() {
        return "Error in conv2dDerFilter: depth of input ".concat(inDepth, ") must ") + "match input depth in filter (".concat(filterShape[2], ".");
      });
      assert(outDepth === filterShape[3], function() {
        return "Error in conv2dDerFilter: depth of dy (".concat(outDepth, ") must ") + "match output depth for filter (".concat(filterShape[3], ").");
      });
      checkPadOnDimRoundingMode("conv2dDerFilter", pad2, dimRoundingMode);
      var inputs = { x: x4D, dy: dy4D };
      var attrs = { strides, pad: pad2, dataFormat, dimRoundingMode, filterShape };
      return ENGINE.runKernel(Conv2DBackpropFilter, inputs, attrs);
    }
    var conv2DBackpropFilter = /* @__PURE__ */ op({ conv2DBackpropFilter_ });
    function getFusedDyActivation(dy, y, activation) {
      if (activation == null || activation === "linear") {
        return dy;
      }
      if (activation === "relu") {
        return mul(dy, step(y));
      }
      throw new Error("Cannot compute gradient for fused activation ".concat(activation, "."));
    }
    function getFusedBiasGradient(bias, dyActivation) {
      var res = dyActivation;
      var reduceAxes = getReductionAxes(bias.shape, dyActivation.shape);
      if (reduceAxes.length > 0) {
        res = sum(res, reduceAxes);
      }
      return reshape(res, bias.shape);
    }
    function applyActivation(x, activation, preluActivationWeights, leakyreluAlpha) {
      if (activation === "linear") {
        return x;
      } else if (activation === "relu") {
        return relu(x);
      } else if (activation === "elu") {
        return elu(x);
      } else if (activation === "relu6") {
        return relu6(x);
      } else if (activation === "prelu") {
        return prelu(x, preluActivationWeights);
      } else if (activation === "leakyrelu") {
        return leakyRelu(x, leakyreluAlpha);
      } else if (activation === "sigmoid") {
        return sigmoid(x);
      }
      throw new Error("Unknown fused activation ".concat(activation, "."));
    }
    var shouldFuse = function(gradientDepth, activation) {
      var gradientMode = gradientDepth > 0;
      return !gradientMode || activation === "linear";
    };
    function fusedConv2d_(_a) {
      var _b;
      var x = _a.x, filter = _a.filter, strides = _a.strides, pad2 = _a.pad, _c = _a.dataFormat, dataFormat = _c === void 0 ? "NHWC" : _c, _d = _a.dilations, dilations = _d === void 0 ? [1, 1] : _d, dimRoundingMode = _a.dimRoundingMode, bias = _a.bias, _e = _a.activation, activation = _e === void 0 ? "linear" : _e, preluActivationWeights = _a.preluActivationWeights, leakyreluAlpha = _a.leakyreluAlpha;
      activation = activation || "linear";
      if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {
        assert(dataFormat === "NHWC", function() {
          return "Error in fused conv2d: got dataFormat of ".concat(dataFormat, " but ") + "only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.";
        });
        var result = conv2d$1(x, filter, strides, pad2, dataFormat, dilations, dimRoundingMode);
        if (bias != null) {
          result = add(result, bias);
        }
        return applyActivation(result, activation, preluActivationWeights, leakyreluAlpha);
      }
      var $x = convertToTensor(x, "x", "conv2d", "float32");
      var $filter = convertToTensor(filter, "filter", "conv2d", "float32");
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, function() {
        return "Error in fused conv2d: input must be rank 4, but got rank " + "".concat(x4D.rank, ".");
      });
      assert($filter.rank === 4, function() {
        return "Error in fused conv2d: filter must be rank 4, but got rank " + "".concat($filter.rank, ".");
      });
      checkPadOnDimRoundingMode("fused conv2d", pad2, dimRoundingMode);
      var inputChannels = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
      assert($filter.shape[2] === inputChannels, function() {
        return "Error in conv2d: depth of input (".concat(inputChannels, ") must match ") + "input depth for filter ".concat($filter.shape[2], ".");
      });
      assert(eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in conv2D: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      var convInfo = computeConv2DInfo(x4D.shape, $filter.shape, strides, dilations, pad2, dimRoundingMode);
      var $bias;
      if (bias != null) {
        $bias = convertToTensor(bias, "bias", "fused conv2d");
        _b = __read(makeTypesMatch($bias, $x), 1), $bias = _b[0];
        if (dataFormat === "NHWC") {
          assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);
        } else {
          assert($bias.shape.length <= 1, function() {
            return "Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of " + "rank-".concat($bias.shape.length, ".");
          });
          assert($bias.shape.length === 0 || $bias.shape[0] === convInfo.outChannels || $bias.shape[0] === 1, function() {
            return "Error in fused conv2d: bias shape (".concat($bias.shape, ") is not ") + "compatible with the number of output channels " + "(".concat(convInfo.outChannels, ")");
          });
        }
      }
      var $preluActivationWeights;
      if (preluActivationWeights != null) {
        var alphaShape_1 = preluActivationWeights.shape;
        assert(alphaShape_1.length <= 1 || alphaShape_1.length === 3, function() {
          return "Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of " + "rank-".concat(alphaShape_1.length, ".");
        });
        if (alphaShape_1.length === 1) {
          assert(alphaShape_1[0] === 1 || alphaShape_1[0] === convInfo.outChannels, function() {
            return "Error in fused conv2d: PReLU activation weights " + "(".concat(alphaShape_1, ") is not compatible with the number of output ") + "channels (".concat(convInfo.outChannels, ").");
          });
        } else if (alphaShape_1.length === 3) {
          try {
            assertAndGetBroadcastShape(alphaShape_1, convInfo.outShape);
          } catch (e) {
            var errMsg = "Error in fused conv2d: PReLU activation weights (".concat(alphaShape_1, ") ") + "is not compatible with the output shape of the conv2d " + "(".concat(convInfo.outShape, ").");
            throw Error(errMsg);
          }
        }
        $preluActivationWeights = convertToTensor(preluActivationWeights, "prelu weights", "fused conv2d");
      }
      var grad2 = function(dy, saved) {
        assert(dataFormat === "NHWC", function() {
          return "Error in gradient of fused conv2D: got dataFormat of ".concat(dataFormat, " but only NHWC is currently supported.");
        });
        var _a2 = __read(saved, 4), $filter2 = _a2[0], x4D2 = _a2[1], y = _a2[2], $bias2 = _a2[3];
        var dyActivation = getFusedDyActivation(dy, y, activation);
        assert(tupleValuesAreOne(dilations), function() {
          return "Error in gradient of fused conv2D: dilation rates greater than 1 " + "are not yet supported in gradients. Got dilations '".concat(dilations, "'");
        });
        var xDer = conv2DBackpropInput(x4D2.shape, dyActivation, $filter2, strides, pad2);
        var filterDer = conv2DBackpropFilter(x4D2, dyActivation, $filter2.shape, strides, pad2);
        var der = [xDer, filterDer];
        if ($bias2 != null) {
          var biasDer = getFusedBiasGradient($bias2, dyActivation);
          der.push(biasDer);
        }
        return der;
      };
      var inputs = {
        x: x4D,
        filter: $filter,
        bias: $bias,
        preluActivationWeights: $preluActivationWeights
      };
      var attrs = {
        strides,
        pad: pad2,
        dataFormat,
        dilations,
        dimRoundingMode,
        activation,
        leakyreluAlpha
      };
      if (bias == null) {
        var customOp = customGrad(function(x4D2, filter2, save) {
          var res = (
            // tslint:disable-next-line: no-unnecessary-type-assertion
            ENGINE.runKernel(FusedConv2D, inputs, attrs)
          );
          save([filter2, x4D2, res]);
          if (reshapedTo4D) {
            res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
          }
          return { value: res, gradFunc: grad2 };
        });
        return customOp(x4D, $filter);
      } else {
        var customOpWithBias = customGrad(function(x4D2, filter2, bias2, save) {
          var res = ENGINE.runKernel(FusedConv2D, inputs, attrs);
          save([filter2, x4D2, res, bias2]);
          if (reshapedTo4D) {
            res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
          }
          return { value: res, gradFunc: grad2 };
        });
        return customOpWithBias(x4D, $filter, $bias);
      }
    }
    var conv2d = /* @__PURE__ */ op({ fusedConv2d_ });
    function depthwiseConv2dNativeBackpropFilter_(x, dy, filterShape, strides, pad2, dilations, dimRoundingMode) {
      if (dilations === void 0) {
        dilations = [1, 1];
      }
      var x4D = x;
      if (x.rank === 3) {
        x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
      }
      var dy4D = dy;
      if (dy4D.rank === 3) {
        dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
      }
      var inputs = { x: x4D, dy: dy4D };
      var attrs = { strides, pad: pad2, dimRoundingMode, dilations, filterShape };
      return ENGINE.runKernel(DepthwiseConv2dNativeBackpropFilter, inputs, attrs);
    }
    var depthwiseConv2dNativeBackpropFilter = op({ depthwiseConv2dNativeBackpropFilter_ });
    function depthwiseConv2dNativeBackpropInput_(xShape, dy, filter, strides, pad2, dilations, dimRoundingMode) {
      if (dilations === void 0) {
        dilations = [1, 1];
      }
      var dy4D = dy;
      var reshapedTo4D = false;
      if (dy.rank === 3) {
        reshapedTo4D = true;
        dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
      }
      var inputs = { dy: dy4D, filter };
      var attrs = { strides, pad: pad2, dimRoundingMode, dilations, inputShape: xShape };
      var res = (
        // tslint:disable-next-line: no-unnecessary-type-assertion
        ENGINE.runKernel(DepthwiseConv2dNativeBackpropInput, inputs, attrs)
      );
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var depthwiseConv2dNativeBackpropInput = op({ depthwiseConv2dNativeBackpropInput_ });
    function fusedDepthwiseConv2d_(_a) {
      var _b;
      var x = _a.x, filter = _a.filter, strides = _a.strides, pad2 = _a.pad, _c = _a.dataFormat, dataFormat = _c === void 0 ? "NHWC" : _c, _d = _a.dilations, dilations = _d === void 0 ? [1, 1] : _d, dimRoundingMode = _a.dimRoundingMode, bias = _a.bias, _e = _a.activation, activation = _e === void 0 ? "linear" : _e, preluActivationWeights = _a.preluActivationWeights, leakyreluAlpha = _a.leakyreluAlpha;
      if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {
        var result = depthwiseConv2d$1(x, filter, strides, pad2, dataFormat, dilations, dimRoundingMode);
        if (bias != null) {
          result = add(result, bias);
        }
        return applyActivation(result, activation, preluActivationWeights, leakyreluAlpha);
      }
      var $x = convertToTensor(x, "x", "depthwiseConv2d", "float32");
      var $filter = convertToTensor(filter, "filter", "depthwiseConv2d", "float32");
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, function() {
        return "Error in fused depthwiseConv2d: input must be rank 4, but got " + "rank ".concat(x4D.rank, ".");
      });
      assert($filter.rank === 4, function() {
        return "Error in fused depthwiseConv2d: filter must be rank 4, " + "but got rank ".concat($filter.rank, ".");
      });
      assert(x4D.shape[3] === $filter.shape[2], function() {
        return "Error in fused depthwiseConv2d: number of input channels " + "(".concat(x4D.shape[3], ") must match the inChannels dimension in ") + "filter ".concat($filter.shape[2], ".");
      });
      if (dilations == null) {
        dilations = [1, 1];
      }
      assert(eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in fused depthwiseConv2d: Either strides or dilations must " + "be 1. Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      checkPadOnDimRoundingMode("fused depthwiseConv2d", pad2, dimRoundingMode);
      var convInfo = computeConv2DInfo(
        x4D.shape,
        $filter.shape,
        strides,
        dilations,
        pad2,
        dimRoundingMode,
        true
        /* depthwise */
      );
      var $bias;
      if (bias != null) {
        $bias = convertToTensor(bias, "bias", "fused conv2d");
        _b = __read(makeTypesMatch($bias, $x), 1), $bias = _b[0];
        assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);
      }
      var $preluActivationWeights;
      if (preluActivationWeights != null) {
        $preluActivationWeights = convertToTensor(preluActivationWeights, "prelu weights", "fused depthwiseConv2d");
      }
      var grad2 = function(dy, saved) {
        assert(tupleValuesAreOne(dilations), function() {
          return "Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations " + "'".concat(dilations, "'");
        });
        var _a2 = __read(saved, 4), $filter2 = _a2[0], x4D2 = _a2[1], y = _a2[2], bias2 = _a2[3];
        var dyActivation = getFusedDyActivation(dy, y, activation);
        var xDer = depthwiseConv2dNativeBackpropInput(x4D2.shape, dyActivation, $filter2, strides, pad2, dilations, dimRoundingMode);
        var filterDer = depthwiseConv2dNativeBackpropFilter(x4D2, dyActivation, $filter2.shape, strides, pad2, dilations, dimRoundingMode);
        if (bias2 != null) {
          var biasDer = getFusedBiasGradient($bias, dyActivation);
          return [xDer, filterDer, biasDer];
        }
        return [xDer, filterDer];
      };
      var inputs = {
        x: x4D,
        filter: $filter,
        bias: $bias,
        preluActivationWeights: $preluActivationWeights
      };
      var attrs = {
        strides,
        pad: pad2,
        dataFormat,
        dilations,
        dimRoundingMode,
        activation,
        leakyreluAlpha
      };
      if (bias == null) {
        var customOp = customGrad(function(x4D2, filter2, save) {
          var res = ENGINE.runKernel(FusedDepthwiseConv2D, inputs, attrs);
          save([filter2, x4D2, res]);
          if (reshapedTo4D) {
            res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
          }
          return { value: res, gradFunc: grad2 };
        });
        return customOp(x4D, $filter);
      } else {
        var customOpWithBias = customGrad(function(x4D2, filter2, bias2, save) {
          var res = ENGINE.runKernel(FusedDepthwiseConv2D, inputs, attrs);
          save([filter2, x4D2, res, bias2]);
          if (reshapedTo4D) {
            res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
          }
          return { value: res, gradFunc: grad2 };
        });
        return customOpWithBias(x4D, $filter, $bias);
      }
    }
    var depthwiseConv2d = /* @__PURE__ */ op({ fusedDepthwiseConv2d_ });
    function fusedMatMul_(_a) {
      var _b, _c;
      var a = _a.a, b = _a.b, _d = _a.transposeA, transposeA = _d === void 0 ? false : _d, _e = _a.transposeB, transposeB = _e === void 0 ? false : _e, bias = _a.bias, _f = _a.activation, activation = _f === void 0 ? "linear" : _f, preluActivationWeights = _a.preluActivationWeights, _g = _a.leakyreluAlpha, leakyreluAlpha = _g === void 0 ? 0.2 : _g;
      if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {
        var result = matMul$1(a, b, transposeA, transposeB);
        if (bias != null) {
          result = add(result, bias);
        }
        return applyActivation(result, activation, preluActivationWeights, leakyreluAlpha);
      }
      var $a = convertToTensor(a, "a", "fused matMul");
      var $b = convertToTensor(b, "b", "fused matMul");
      _b = __read(makeTypesMatch($a, $b), 2), $a = _b[0], $b = _b[1];
      var innerShapeA = transposeA ? $a.shape[$a.rank - 2] : $a.shape[$a.rank - 1];
      var innerShapeB = transposeB ? $b.shape[$b.rank - 1] : $b.shape[$b.rank - 2];
      var outerShapeA = transposeA ? $a.shape[$a.rank - 1] : $a.shape[$a.rank - 2];
      var outerShapeB = transposeB ? $b.shape[$b.rank - 2] : $b.shape[$b.rank - 1];
      var outerDimsA = $a.shape.slice(0, -2);
      var outerDimsB = $b.shape.slice(0, -2);
      var batchDimA = sizeFromShape(outerDimsA);
      var batchDimB = sizeFromShape(outerDimsB);
      assert(innerShapeA === innerShapeB, function() {
        return "Error in fused matMul: inner shapes (".concat(innerShapeA, ") and (") + "".concat(innerShapeB, ") of Tensors with shapes ").concat($a.shape, " and ") + "".concat($b.shape, " and transposeA=").concat(transposeA) + " and transposeB=".concat(transposeB, " must match.");
      });
      var outShapeOuterDims = assertAndGetBroadcastShape($a.shape.slice(0, -2), $b.shape.slice(0, -2));
      var outShape = outShapeOuterDims.concat([outerShapeA, outerShapeB]);
      var a3D = transposeA ? reshape($a, [batchDimA, innerShapeA, outerShapeA]) : reshape($a, [batchDimA, outerShapeA, innerShapeA]);
      var b3D = transposeB ? reshape($b, [batchDimB, outerShapeB, innerShapeB]) : reshape($b, [batchDimB, innerShapeB, outerShapeB]);
      var $bias;
      if (bias != null) {
        $bias = convertToTensor(bias, "bias", "fused matMul");
        _c = __read(makeTypesMatch($bias, $a), 1), $bias = _c[0];
        assertAndGetBroadcastShape(outShape, $bias.shape);
      }
      var $preluActivationWeights;
      if (preluActivationWeights != null) {
        $preluActivationWeights = convertToTensor(preluActivationWeights, "prelu weights", "fused matMul");
      }
      var grad2 = function(dy, saved) {
        var _a2 = __read(saved, 4), a3D2 = _a2[0], b3D2 = _a2[1], y = _a2[2], $bias2 = _a2[3];
        var dyActivation = getFusedDyActivation(reshape(dy, y.shape), y, activation);
        var aDer;
        var bDer;
        if (!transposeA && !transposeB) {
          aDer = matMul$1(dyActivation, b3D2, false, true);
          bDer = matMul$1(a3D2, dyActivation, true, false);
        } else if (!transposeA && transposeB) {
          aDer = matMul$1(dyActivation, b3D2, false, false);
          bDer = matMul$1(dyActivation, a3D2, true, false);
        } else if (transposeA && !transposeB) {
          aDer = matMul$1(b3D2, dyActivation, false, true);
          bDer = matMul$1(a3D2, dyActivation, false, false);
        } else {
          aDer = matMul$1(b3D2, dyActivation, true, true);
          bDer = matMul$1(dyActivation, a3D2, true, true);
        }
        if (bias != null) {
          var biasDer = getFusedBiasGradient($bias2, dyActivation);
          return [aDer, bDer, biasDer];
        } else {
          return [aDer, bDer];
        }
      };
      var inputs = {
        a: a3D,
        b: b3D,
        bias: $bias,
        preluActivationWeights: $preluActivationWeights
      };
      var attrs = { transposeA, transposeB, activation, leakyreluAlpha };
      if (bias == null) {
        var customOp = customGrad(function(a3D2, b3D2, save) {
          var res = (
            // tslint:disable-next-line: no-unnecessary-type-assertion
            ENGINE.runKernel(_FusedMatMul, inputs, attrs)
          );
          save([a3D2, b3D2, res]);
          return { value: reshape(res, outShape), gradFunc: grad2 };
        });
        return customOp(a3D, b3D);
      } else {
        var customOpWithBias = customGrad(function(a3D2, b3D2, $bias2, save) {
          var res = (
            // tslint:disable-next-line: no-unnecessary-type-assertion
            ENGINE.runKernel(_FusedMatMul, inputs, attrs)
          );
          save([a3D2, b3D2, res, $bias2]);
          return { value: reshape(res, outShape), gradFunc: grad2 };
        });
        return customOpWithBias(a3D, b3D, $bias);
      }
    }
    var matMul = /* @__PURE__ */ op({ fusedMatMul_ });
    var fused_ops = {
      __proto__: null,
      conv2d,
      depthwiseConv2d,
      matMul
    };
    function hammingWindow_(windowLength) {
      return cosineWindow(windowLength, 0.54, 0.46);
    }
    var hammingWindow = /* @__PURE__ */ op({ hammingWindow_ });
    function hannWindow_(windowLength) {
      return cosineWindow(windowLength, 0.5, 0.5);
    }
    var hannWindow = /* @__PURE__ */ op({ hannWindow_ });
    function frame_(signal2, frameLength, frameStep, padEnd, padValue) {
      if (padEnd === void 0) {
        padEnd = false;
      }
      if (padValue === void 0) {
        padValue = 0;
      }
      var start = 0;
      var output = [];
      while (start + frameLength <= signal2.size) {
        output.push(slice(signal2, start, frameLength));
        start += frameStep;
      }
      if (padEnd) {
        while (start < signal2.size) {
          var padLen = start + frameLength - signal2.size;
          var pad2 = concat([
            slice(signal2, start, frameLength - padLen),
            fill([padLen], padValue)
          ]);
          output.push(pad2);
          start += frameStep;
        }
      }
      if (output.length === 0) {
        return tensor2d([], [0, frameLength]);
      }
      return reshape(concat(output), [output.length, frameLength]);
    }
    var frame = /* @__PURE__ */ op({ frame_ });
    function stft_(signal2, frameLength, frameStep, fftLength, windowFn) {
      if (windowFn === void 0) {
        windowFn = hannWindow;
      }
      if (fftLength == null) {
        fftLength = enclosingPowerOfTwo(frameLength);
      }
      var framedSignal = frame(signal2, frameLength, frameStep);
      var windowedSignal = mul(framedSignal, windowFn(frameLength));
      return rfft(windowedSignal, fftLength);
    }
    var stft = /* @__PURE__ */ op({ stft_ });
    function cropAndResize_(image2, boxes, boxInd, cropSize, method, extrapolationValue) {
      if (method === void 0) {
        method = "bilinear";
      }
      if (extrapolationValue === void 0) {
        extrapolationValue = 0;
      }
      var $image = convertToTensor(image2, "image", "cropAndResize");
      var $boxes = convertToTensor(boxes, "boxes", "cropAndResize", "float32");
      var $boxInd = convertToTensor(boxInd, "boxInd", "cropAndResize", "int32");
      var numBoxes = $boxes.shape[0];
      assert($image.rank === 4, function() {
        return "Error in cropAndResize: image must be rank 4," + "but got rank ".concat($image.rank, ".");
      });
      assert($boxes.rank === 2 && $boxes.shape[1] === 4, function() {
        return "Error in cropAndResize: boxes must be have size [".concat(numBoxes, ",4] ") + "but had shape ".concat($boxes.shape, ".");
      });
      assert($boxInd.rank === 1 && $boxInd.shape[0] === numBoxes, function() {
        return "Error in cropAndResize: boxInd must be have size [".concat(numBoxes, "] ") + "but had shape ".concat($boxes.shape, ".");
      });
      assert(cropSize.length === 2, function() {
        return "Error in cropAndResize: cropSize must be of length 2, but got " + "length ".concat(cropSize.length, ".");
      });
      assert(cropSize[0] >= 1 && cropSize[1] >= 1, function() {
        return "cropSize must be atleast [1,1], but was ".concat(cropSize);
      });
      assert(method === "bilinear" || method === "nearest", function() {
        return "method must be bilinear or nearest, but was ".concat(method);
      });
      var inputs = { image: $image, boxes: $boxes, boxInd: $boxInd };
      var attrs = { method, extrapolationValue, cropSize };
      var res = ENGINE.runKernel(CropAndResize, inputs, attrs);
      return res;
    }
    var cropAndResize = /* @__PURE__ */ op({ cropAndResize_ });
    function flipLeftRight_(image2) {
      var $image = convertToTensor(image2, "image", "flipLeftRight", "float32");
      assert($image.rank === 4, function() {
        return "Error in flipLeftRight: image must be rank 4," + "but got rank ".concat($image.rank, ".");
      });
      var inputs = { image: $image };
      var res = ENGINE.runKernel(FlipLeftRight, inputs, {});
      return res;
    }
    var flipLeftRight = /* @__PURE__ */ op({ flipLeftRight_ });
    function grayscaleToRGB_(image2) {
      var $image = convertToTensor(image2, "image", "grayscaleToRGB");
      var lastDimsIdx = $image.rank - 1;
      var lastDims = $image.shape[lastDimsIdx];
      assert($image.rank >= 2, function() {
        return "Error in grayscaleToRGB: images must be at least rank 2, " + "but got rank ".concat($image.rank, ".");
      });
      assert(lastDims === 1, function() {
        return "Error in grayscaleToRGB: last dimension of a grayscale image " + "should be size 1, but got size ".concat(lastDims, ".");
      });
      var reps = new Array($image.rank);
      reps.fill(1, 0, lastDimsIdx);
      reps[lastDimsIdx] = 3;
      return tile($image, reps);
    }
    var grayscaleToRGB = /* @__PURE__ */ op({ grayscaleToRGB_ });
    function rgbToGrayscale_(image2) {
      var $image = convertToTensor(image2, "image", "RGBToGrayscale");
      var lastDimsIdx = $image.rank - 1;
      var lastDims = $image.shape[lastDimsIdx];
      assert($image.rank >= 2, function() {
        return "Error in RGBToGrayscale: images must be at least rank 2, " + "but got rank ".concat($image.rank, ".");
      });
      assert(lastDims === 3, function() {
        return "Error in RGBToGrayscale: last dimension of an RGB image " + "should be size 3, but got size ".concat(lastDims, ".");
      });
      var origDtype = $image.dtype;
      var fltImage = cast($image, "float32");
      var rgbWeights = tensor1d([0.2989, 0.587, 0.114]);
      var grayFloat;
      switch ($image.rank) {
        case 2:
          grayFloat = einsum("ij,j->i", fltImage, rgbWeights);
          break;
        case 3:
          grayFloat = einsum("ijk,k->ij", fltImage, rgbWeights);
          break;
        case 4:
          grayFloat = einsum("ijkl,l->ijk", fltImage, rgbWeights);
          break;
        case 5:
          grayFloat = einsum("ijklm,m->ijkl", fltImage, rgbWeights);
          break;
        case 6:
          grayFloat = einsum("ijklmn,n->ijklm", fltImage, rgbWeights);
          break;
        default:
          throw new Error("Not a valid tensor rank.");
      }
      grayFloat = expandDims(grayFloat, -1);
      return cast(grayFloat, origDtype);
    }
    var rgbToGrayscale = /* @__PURE__ */ op({ rgbToGrayscale_ });
    function rotateWithOffset_(image2, radians, fillValue, center) {
      if (fillValue === void 0) {
        fillValue = 0;
      }
      if (center === void 0) {
        center = 0.5;
      }
      var $image = convertToTensor(image2, "image", "rotateWithOffset", "float32");
      assert($image.rank === 4, function() {
        return "Error in rotateWithOffset: image must be rank 4," + "but got rank ".concat($image.rank, ".");
      });
      var inputs = { image: $image };
      var attrs = { radians, fillValue, center };
      var res = ENGINE.runKernel(RotateWithOffset, inputs, attrs);
      return res;
    }
    var rotateWithOffset = /* @__PURE__ */ op({ rotateWithOffset_ });
    function nonMaxSuppSanityCheck(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
      if (iouThreshold == null) {
        iouThreshold = 0.5;
      }
      if (scoreThreshold == null) {
        scoreThreshold = Number.NEGATIVE_INFINITY;
      }
      if (softNmsSigma == null) {
        softNmsSigma = 0;
      }
      var numBoxes = boxes.shape[0];
      maxOutputSize = Math.min(maxOutputSize, numBoxes);
      assert(0 <= iouThreshold && iouThreshold <= 1, function() {
        return "iouThreshold must be in [0, 1], but was '".concat(iouThreshold, "'");
      });
      assert(boxes.rank === 2, function() {
        return "boxes must be a 2D tensor, but was of rank '".concat(boxes.rank, "'");
      });
      assert(boxes.shape[1] === 4, function() {
        return "boxes must have 4 columns, but 2nd dimension was ".concat(boxes.shape[1]);
      });
      assert(scores.rank === 1, function() {
        return "scores must be a 1D tensor";
      });
      assert(scores.shape[0] === numBoxes, function() {
        return "scores has incompatible shape with boxes. Expected ".concat(numBoxes, ", ") + "but was ".concat(scores.shape[0]);
      });
      assert(0 <= softNmsSigma && softNmsSigma <= 1, function() {
        return "softNmsSigma must be in [0, 1], but was '".concat(softNmsSigma, "'");
      });
      return { maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma };
    }
    function nonMaxSuppression_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) {
      if (iouThreshold === void 0) {
        iouThreshold = 0.5;
      }
      if (scoreThreshold === void 0) {
        scoreThreshold = Number.NEGATIVE_INFINITY;
      }
      var $boxes = convertToTensor(boxes, "boxes", "nonMaxSuppression", "float32");
      var $scores = convertToTensor(scores, "scores", "nonMaxSuppression", "float32");
      var inputs = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);
      maxOutputSize = inputs.maxOutputSize;
      iouThreshold = inputs.iouThreshold;
      scoreThreshold = inputs.scoreThreshold;
      var attrs = { maxOutputSize, iouThreshold, scoreThreshold };
      return ENGINE.runKernel(NonMaxSuppressionV3, { boxes: $boxes, scores: $scores }, attrs);
    }
    var nonMaxSuppression = /* @__PURE__ */ op({ nonMaxSuppression_ });
    function binaryInsert(arr, element, comparator) {
      var index = binarySearch(arr, element, comparator);
      var insertionPoint = index < 0 ? -(index + 1) : index;
      arr.splice(insertionPoint, 0, element);
    }
    function binarySearch(arr, target, comparator) {
      return binarySearch_(arr, target, comparator || defaultComparator);
    }
    function defaultComparator(a, b) {
      return a > b ? 1 : a < b ? -1 : 0;
    }
    function binarySearch_(arr, target, comparator) {
      var left = 0;
      var right = arr.length;
      var middle = 0;
      var found = false;
      while (left < right) {
        middle = left + (right - left >>> 1);
        var compareResult = comparator(target, arr[middle]);
        if (compareResult > 0) {
          left = middle + 1;
        } else {
          right = middle;
          found = !compareResult;
        }
      }
      return found ? left : -left - 1;
    }
    function nonMaxSuppressionV3Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) {
      return nonMaxSuppressionImpl_(
        boxes,
        scores,
        maxOutputSize,
        iouThreshold,
        scoreThreshold,
        0
        /* softNmsSigma */
      );
    }
    function nonMaxSuppressionV4Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize) {
      return nonMaxSuppressionImpl_(
        boxes,
        scores,
        maxOutputSize,
        iouThreshold,
        scoreThreshold,
        0,
        false,
        padToMaxOutputSize,
        true
        /* returnValidOutputs */
      );
    }
    function nonMaxSuppressionV5Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
      return nonMaxSuppressionImpl_(
        boxes,
        scores,
        maxOutputSize,
        iouThreshold,
        scoreThreshold,
        softNmsSigma,
        true
        /* returnScoresTensor */
      );
    }
    function nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma, returnScoresTensor, padToMaxOutputSize, returnValidOutputs) {
      if (returnScoresTensor === void 0) {
        returnScoresTensor = false;
      }
      if (padToMaxOutputSize === void 0) {
        padToMaxOutputSize = false;
      }
      if (returnValidOutputs === void 0) {
        returnValidOutputs = false;
      }
      var candidates = [];
      for (var i = 0; i < scores.length; i++) {
        if (scores[i] > scoreThreshold) {
          candidates.push({ score: scores[i], boxIndex: i, suppressBeginIndex: 0 });
        }
      }
      candidates.sort(ascendingComparator);
      var scale = softNmsSigma > 0 ? -0.5 / softNmsSigma : 0;
      var selectedIndices = [];
      var selectedScores = [];
      while (selectedIndices.length < maxOutputSize && candidates.length > 0) {
        var candidate = candidates.pop();
        var originalScore = candidate.score, boxIndex = candidate.boxIndex, suppressBeginIndex = candidate.suppressBeginIndex;
        if (originalScore < scoreThreshold) {
          break;
        }
        var ignoreCandidate = false;
        for (var j = selectedIndices.length - 1; j >= suppressBeginIndex; --j) {
          var iou = intersectionOverUnion(boxes, boxIndex, selectedIndices[j]);
          if (iou >= iouThreshold) {
            ignoreCandidate = true;
            break;
          }
          candidate.score = candidate.score * suppressWeight(iouThreshold, scale, iou);
          if (candidate.score <= scoreThreshold) {
            break;
          }
        }
        candidate.suppressBeginIndex = selectedIndices.length;
        if (!ignoreCandidate) {
          if (candidate.score === originalScore) {
            selectedIndices.push(boxIndex);
            selectedScores.push(candidate.score);
          } else if (candidate.score > scoreThreshold) {
            binaryInsert(candidates, candidate, ascendingComparator);
          }
        }
      }
      var validOutputs = selectedIndices.length;
      var elemsToPad = maxOutputSize - validOutputs;
      if (padToMaxOutputSize && elemsToPad > 0) {
        selectedIndices.push.apply(selectedIndices, __spreadArray([], __read(new Array(elemsToPad).fill(0)), false));
        selectedScores.push.apply(selectedScores, __spreadArray([], __read(new Array(elemsToPad).fill(0)), false));
      }
      var result = { selectedIndices };
      if (returnScoresTensor) {
        result["selectedScores"] = selectedScores;
      }
      if (returnValidOutputs) {
        result["validOutputs"] = validOutputs;
      }
      return result;
    }
    function intersectionOverUnion(boxes, i, j) {
      var iCoord = boxes.subarray(i * 4, i * 4 + 4);
      var jCoord = boxes.subarray(j * 4, j * 4 + 4);
      var yminI = Math.min(iCoord[0], iCoord[2]);
      var xminI = Math.min(iCoord[1], iCoord[3]);
      var ymaxI = Math.max(iCoord[0], iCoord[2]);
      var xmaxI = Math.max(iCoord[1], iCoord[3]);
      var yminJ = Math.min(jCoord[0], jCoord[2]);
      var xminJ = Math.min(jCoord[1], jCoord[3]);
      var ymaxJ = Math.max(jCoord[0], jCoord[2]);
      var xmaxJ = Math.max(jCoord[1], jCoord[3]);
      var areaI = (ymaxI - yminI) * (xmaxI - xminI);
      var areaJ = (ymaxJ - yminJ) * (xmaxJ - xminJ);
      if (areaI <= 0 || areaJ <= 0) {
        return 0;
      }
      var intersectionYmin = Math.max(yminI, yminJ);
      var intersectionXmin = Math.max(xminI, xminJ);
      var intersectionYmax = Math.min(ymaxI, ymaxJ);
      var intersectionXmax = Math.min(xmaxI, xmaxJ);
      var intersectionArea = Math.max(intersectionYmax - intersectionYmin, 0) * Math.max(intersectionXmax - intersectionXmin, 0);
      return intersectionArea / (areaI + areaJ - intersectionArea);
    }
    function suppressWeight(iouThreshold, scale, iou) {
      var weight = Math.exp(scale * iou * iou);
      return iou <= iouThreshold ? weight : 0;
    }
    function ascendingComparator(c1, c2) {
      return c1.score - c2.score || c1.score === c2.score && c2.boxIndex - c1.boxIndex;
    }
    function nonMaxSuppressionAsync_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) {
      if (iouThreshold === void 0) {
        iouThreshold = 0.5;
      }
      if (scoreThreshold === void 0) {
        scoreThreshold = Number.NEGATIVE_INFINITY;
      }
      return __awaiter(this, void 0, void 0, function() {
        var $boxes, $scores, inputs, boxesAndScores, boxesVals, scoresVals, selectedIndices;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              $boxes = convertToTensor(boxes, "boxes", "nonMaxSuppressionAsync");
              $scores = convertToTensor(scores, "scores", "nonMaxSuppressionAsync");
              inputs = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);
              maxOutputSize = inputs.maxOutputSize;
              iouThreshold = inputs.iouThreshold;
              scoreThreshold = inputs.scoreThreshold;
              return [4, Promise.all([$boxes.data(), $scores.data()])];
            case 1:
              boxesAndScores = _a.sent();
              boxesVals = boxesAndScores[0];
              scoresVals = boxesAndScores[1];
              selectedIndices = nonMaxSuppressionV3Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold).selectedIndices;
              if ($boxes !== boxes) {
                $boxes.dispose();
              }
              if ($scores !== scores) {
                $scores.dispose();
              }
              return [2, tensor1d(selectedIndices, "int32")];
          }
        });
      });
    }
    var nonMaxSuppressionAsync = nonMaxSuppressionAsync_;
    function nonMaxSuppressionWithScore_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
      if (iouThreshold === void 0) {
        iouThreshold = 0.5;
      }
      if (scoreThreshold === void 0) {
        scoreThreshold = Number.NEGATIVE_INFINITY;
      }
      if (softNmsSigma === void 0) {
        softNmsSigma = 0;
      }
      var $boxes = convertToTensor(boxes, "boxes", "nonMaxSuppression");
      var $scores = convertToTensor(scores, "scores", "nonMaxSuppression");
      var params = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
      maxOutputSize = params.maxOutputSize;
      iouThreshold = params.iouThreshold;
      scoreThreshold = params.scoreThreshold;
      softNmsSigma = params.softNmsSigma;
      var inputs = { boxes: $boxes, scores: $scores };
      var attrs = { maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma };
      var result = ENGINE.runKernel(NonMaxSuppressionV5, inputs, attrs);
      return { selectedIndices: result[0], selectedScores: result[1] };
    }
    var nonMaxSuppressionWithScore = /* @__PURE__ */ op({ nonMaxSuppressionWithScore_ });
    function nonMaxSuppressionWithScoreAsync_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
      if (iouThreshold === void 0) {
        iouThreshold = 0.5;
      }
      if (scoreThreshold === void 0) {
        scoreThreshold = Number.NEGATIVE_INFINITY;
      }
      if (softNmsSigma === void 0) {
        softNmsSigma = 0;
      }
      return __awaiter(this, void 0, void 0, function() {
        var $boxes, $scores, params, boxesAndScores, boxesVals, scoresVals, _a, selectedIndices, selectedScores;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              $boxes = convertToTensor(boxes, "boxes", "nonMaxSuppressionAsync");
              $scores = convertToTensor(scores, "scores", "nonMaxSuppressionAsync");
              params = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
              maxOutputSize = params.maxOutputSize;
              iouThreshold = params.iouThreshold;
              scoreThreshold = params.scoreThreshold;
              softNmsSigma = params.softNmsSigma;
              return [4, Promise.all([$boxes.data(), $scores.data()])];
            case 1:
              boxesAndScores = _b.sent();
              boxesVals = boxesAndScores[0];
              scoresVals = boxesAndScores[1];
              _a = nonMaxSuppressionV5Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma), selectedIndices = _a.selectedIndices, selectedScores = _a.selectedScores;
              if ($boxes !== boxes) {
                $boxes.dispose();
              }
              if ($scores !== scores) {
                $scores.dispose();
              }
              return [2, {
                selectedIndices: tensor1d(selectedIndices, "int32"),
                selectedScores: tensor1d(selectedScores)
              }];
          }
        });
      });
    }
    var nonMaxSuppressionWithScoreAsync = nonMaxSuppressionWithScoreAsync_;
    function nonMaxSuppressionPadded_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize) {
      if (iouThreshold === void 0) {
        iouThreshold = 0.5;
      }
      if (scoreThreshold === void 0) {
        scoreThreshold = Number.NEGATIVE_INFINITY;
      }
      if (padToMaxOutputSize === void 0) {
        padToMaxOutputSize = false;
      }
      var $boxes = convertToTensor(boxes, "boxes", "nonMaxSuppression");
      var $scores = convertToTensor(scores, "scores", "nonMaxSuppression");
      var params = nonMaxSuppSanityCheck(
        $boxes,
        $scores,
        maxOutputSize,
        iouThreshold,
        scoreThreshold,
        null
        /* softNmsSigma */
      );
      var $maxOutputSize = params.maxOutputSize;
      var $iouThreshold = params.iouThreshold;
      var $scoreThreshold = params.scoreThreshold;
      var inputs = { boxes: $boxes, scores: $scores };
      var attrs = {
        maxOutputSize: $maxOutputSize,
        iouThreshold: $iouThreshold,
        scoreThreshold: $scoreThreshold,
        padToMaxOutputSize
      };
      var result = ENGINE.runKernel(NonMaxSuppressionV4, inputs, attrs);
      return { selectedIndices: result[0], validOutputs: result[1] };
    }
    var nonMaxSuppressionPadded = /* @__PURE__ */ op({ nonMaxSuppressionPadded_ });
    function nonMaxSuppressionPaddedAsync_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize) {
      if (iouThreshold === void 0) {
        iouThreshold = 0.5;
      }
      if (scoreThreshold === void 0) {
        scoreThreshold = Number.NEGATIVE_INFINITY;
      }
      if (padToMaxOutputSize === void 0) {
        padToMaxOutputSize = false;
      }
      return __awaiter(this, void 0, void 0, function() {
        var $boxes, $scores, params, $maxOutputSize, $iouThreshold, $scoreThreshold, _a, boxesVals, scoresVals, _b, selectedIndices, validOutputs;
        return __generator(this, function(_c) {
          switch (_c.label) {
            case 0:
              $boxes = convertToTensor(boxes, "boxes", "nonMaxSuppressionAsync");
              $scores = convertToTensor(scores, "scores", "nonMaxSuppressionAsync");
              params = nonMaxSuppSanityCheck(
                $boxes,
                $scores,
                maxOutputSize,
                iouThreshold,
                scoreThreshold,
                null
                /* softNmsSigma */
              );
              $maxOutputSize = params.maxOutputSize;
              $iouThreshold = params.iouThreshold;
              $scoreThreshold = params.scoreThreshold;
              return [4, Promise.all([$boxes.data(), $scores.data()])];
            case 1:
              _a = __read.apply(void 0, [_c.sent(), 2]), boxesVals = _a[0], scoresVals = _a[1];
              _b = nonMaxSuppressionV4Impl(boxesVals, scoresVals, $maxOutputSize, $iouThreshold, $scoreThreshold, padToMaxOutputSize), selectedIndices = _b.selectedIndices, validOutputs = _b.validOutputs;
              if ($boxes !== boxes) {
                $boxes.dispose();
              }
              if ($scores !== scores) {
                $scores.dispose();
              }
              return [2, {
                selectedIndices: tensor1d(selectedIndices, "int32"),
                validOutputs: scalar(validOutputs, "int32")
              }];
          }
        });
      });
    }
    var nonMaxSuppressionPaddedAsync = nonMaxSuppressionPaddedAsync_;
    function resizeBilinear_(images, size, alignCorners, halfPixelCenters) {
      if (alignCorners === void 0) {
        alignCorners = false;
      }
      if (halfPixelCenters === void 0) {
        halfPixelCenters = false;
      }
      var $images = convertToTensor(images, "images", "resizeBilinear");
      assert($images.rank === 3 || $images.rank === 4, function() {
        return "Error in resizeBilinear: x must be rank 3 or 4, but got " + "rank ".concat($images.rank, ".");
      });
      assert(size.length === 2, function() {
        return "Error in resizeBilinear: new shape must 2D, but got shape " + "".concat(size, ".");
      });
      assert(halfPixelCenters === false || alignCorners === false, function() {
        return "Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.";
      });
      var batchImages = $images;
      var reshapedTo4D = false;
      if ($images.rank === 3) {
        reshapedTo4D = true;
        batchImages = reshape($images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);
      }
      __read(size, 0);
      var inputs = { images: batchImages };
      var attrs = { alignCorners, halfPixelCenters, size };
      var res = ENGINE.runKernel(ResizeBilinear, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var resizeBilinear = /* @__PURE__ */ op({ resizeBilinear_ });
    function resizeNearestNeighbor_(images, size, alignCorners, halfPixelCenters) {
      if (alignCorners === void 0) {
        alignCorners = false;
      }
      if (halfPixelCenters === void 0) {
        halfPixelCenters = false;
      }
      var $images = convertToTensor(images, "images", "resizeNearestNeighbor");
      assert($images.rank === 3 || $images.rank === 4, function() {
        return "Error in resizeNearestNeighbor: x must be rank 3 or 4, but got " + "rank ".concat($images.rank, ".");
      });
      assert(size.length === 2, function() {
        return "Error in resizeNearestNeighbor: new shape must 2D, but got shape " + "".concat(size, ".");
      });
      assert($images.dtype === "float32" || $images.dtype === "int32", function() {
        return "`images` must have `int32` or `float32` as dtype";
      });
      assert(halfPixelCenters === false || alignCorners === false, function() {
        return "Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.";
      });
      var batchImages = $images;
      var reshapedTo4D = false;
      if ($images.rank === 3) {
        reshapedTo4D = true;
        batchImages = reshape($images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);
      }
      __read(size, 0);
      var inputs = { images: batchImages };
      var attrs = { alignCorners, halfPixelCenters, size };
      var res = ENGINE.runKernel(ResizeNearestNeighbor, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var resizeNearestNeighbor = /* @__PURE__ */ op({ resizeNearestNeighbor_ });
    function threshold_(image2, method, inverted, threshValue) {
      var _a;
      if (method === void 0) {
        method = "binary";
      }
      if (inverted === void 0) {
        inverted = false;
      }
      if (threshValue === void 0) {
        threshValue = 0.5;
      }
      var $image = convertToTensor(image2, "image", "threshold");
      var RED_INTENCITY_COEF = 0.2989;
      var GREEN_INTENCITY_COEF = 0.587;
      var BLUE_INTENCITY_COEF = 0.114;
      var totalPixelsInImage = $image.shape[0] * $image.shape[1];
      var $threshold = mul(tensor1d([threshValue]), 255);
      var r, g, b, grayscale;
      assert($image.rank === 3, function() {
        return "Error in threshold: image must be rank 3," + "but got rank ".concat($image.rank, ".");
      });
      assert($image.shape[2] === 3 || $image.shape[2] === 1, function() {
        return "Error in threshold: image color channel must be equal to 3 or 1" + "but got ".concat($image.shape[2], ".");
      });
      assert($image.dtype === "int32" || $image.dtype === "float32", function() {
        return "Error in dtype: image dtype must be int32 or float32," + "but got dtype ".concat($image.dtype, ".");
      });
      assert(method === "otsu" || method === "binary", function() {
        return "Method must be binary or otsu, but was ".concat(method);
      });
      if ($image.shape[2] === 3) {
        _a = __read(split($image, [1, 1, 1], -1), 3), r = _a[0], g = _a[1], b = _a[2];
        var $r = mul(r, RED_INTENCITY_COEF);
        var $g = mul(g, GREEN_INTENCITY_COEF);
        var $b = mul(b, BLUE_INTENCITY_COEF);
        grayscale = add(add($r, $g), $b);
      } else {
        grayscale = image2;
      }
      if (method === "otsu") {
        var $histogram = bincount(cast(round(grayscale), "int32"), tensor([]), 256);
        $threshold = otsu($histogram, totalPixelsInImage);
      }
      var invCondition = inverted ? lessEqual(grayscale, $threshold) : greater(grayscale, $threshold);
      var result = cast(mul(invCondition, 255), "int32");
      return result;
    }
    function otsu(histogram, total) {
      var bestThresh = tensor1d([-1]);
      var bestInBetVar = tensor1d([0]);
      var cInBetVar = tensor1d([0]);
      var classFirst, classSecond, meanFirst, meanSec, weightForeground, weightBack;
      for (var index = 0; index < histogram.size - 1; index++) {
        classFirst = slice(histogram, 0, index + 1);
        classSecond = slice(histogram, index + 1);
        weightForeground = div(sum(classFirst), total);
        weightBack = div(sum(classSecond), total);
        var meanFirstDivA = sum(mul(classFirst, range(0, classFirst.size)));
        meanFirst = div(meanFirstDivA, sum(classFirst));
        var meanSecFill = fill(classSecond.shape, classFirst.size);
        var meanSecAdd = add(range(0, classSecond.size), meanSecFill);
        var meanSecMul = mul(classSecond, meanSecAdd);
        meanSec = div(sum(meanSecMul), sum(classSecond));
        var cInBetVarSubA = sub(meanFirst, meanSec);
        var cInBetVarSubB = sub(meanFirst, meanSec);
        var cInBetVarMul = mul(weightForeground, weightBack);
        cInBetVar = mul(mul(cInBetVarMul, cInBetVarSubA), cInBetVarSubB);
        var condition = greater(cInBetVar, bestInBetVar);
        bestInBetVar = where(condition, cInBetVar, bestInBetVar);
        bestThresh = where(condition, tensor1d([index]), bestThresh);
      }
      return bestThresh;
    }
    var threshold = /* @__PURE__ */ op({ threshold_ });
    function transform_(image2, transforms, interpolation, fillMode, fillValue, outputShape) {
      if (interpolation === void 0) {
        interpolation = "nearest";
      }
      if (fillMode === void 0) {
        fillMode = "constant";
      }
      if (fillValue === void 0) {
        fillValue = 0;
      }
      var $image = convertToTensor(image2, "image", "transform", "float32");
      var $transforms = convertToTensor(transforms, "transforms", "transform", "float32");
      assert($image.rank === 4, function() {
        return "Error in transform: image must be rank 4," + "but got rank ".concat($image.rank, ".");
      });
      assert($transforms.rank === 2 && ($transforms.shape[0] === $image.shape[0] || $transforms.shape[0] === 1) && $transforms.shape[1] === 8, function() {
        return "Error in transform: Input transform should be batch x 8 or 1 x 8";
      });
      assert(outputShape == null || outputShape.length === 2, function() {
        return "Error in transform: outputShape must be [height, width] or null, " + "but got ".concat(outputShape, ".");
      });
      var inputs = { image: $image, transforms: $transforms };
      var attrs = { interpolation, fillMode, fillValue, outputShape };
      return ENGINE.runKernel(Transform, inputs, attrs);
    }
    var transform = /* @__PURE__ */ op({ transform_ });
    function bandPart_(a, numLower, numUpper) {
      var $a = convertToTensor(a, "a", "bandPart");
      assert($a.rank >= 2, function() {
        return "bandPart(): Rank must be at least 2, got ".concat($a.rank, ".");
      });
      var shape = $a.shape;
      var _a = __read($a.shape.slice(-2), 2), M = _a[0], N = _a[1];
      var $numLower;
      var $numUpper;
      if (typeof numLower === "number") {
        assert(numLower % 1 === 0, function() {
          return "bandPart(): numLower must be an integer, got ".concat(numLower, ".");
        });
        assert(numLower <= M, function() {
          return "bandPart(): numLower (".concat(numLower, ")") + " must not be greater than the number of rows (".concat(M, ").");
        });
        $numLower = convertToTensor(numLower < 0 ? M : numLower, "numLower", "bandPart");
      } else {
        assert(numLower.dtype === "int32", function() {
          return "bandPart(): numLower's dtype must be an int32.";
        });
        $numLower = where(less(numLower, 0), M, minimum(numLower, M));
      }
      if (typeof numUpper === "number") {
        assert(numUpper % 1 === 0, function() {
          return "bandPart(): numUpper must be an integer, got ".concat(numUpper, ".");
        });
        assert(numUpper <= N, function() {
          return "bandPart(): numUpper (".concat(numUpper, ")") + " must not be greater than the number of columns (".concat(N, ").");
        });
        $numUpper = convertToTensor(numUpper < 0 ? N : numUpper, "numUpper", "bandPart");
      } else {
        assert(numUpper.dtype === "int32", function() {
          return "bandPart(): numUpper's dtype must be an int32.";
        });
        $numUpper = where(less(numUpper, 0), N, minimum(numUpper, N));
      }
      var i = reshape(range(0, M, 1, "int32"), [-1, 1]);
      var j = range(0, N, 1, "int32");
      var ij = sub(i, j);
      var inBand = logicalAnd(lessEqual(ij, $numLower), greaterEqual(ij, neg($numUpper)));
      var zero = zeros([M, N], $a.dtype);
      return reshape(stack(unstack(reshape($a, [-1, M, N])).map(function(mat) {
        return where(inBand, mat, zero);
      })), shape);
    }
    var bandPart = /* @__PURE__ */ op({ bandPart_ });
    function gramSchmidt_(xs) {
      var inputIsTensor2D;
      if (Array.isArray(xs)) {
        inputIsTensor2D = false;
        assert(xs != null && xs.length > 0, function() {
          return "Gram-Schmidt process: input must not be null, undefined, or empty";
        });
        var dim_1 = xs[0].shape[0];
        var _loop_1 = function(i2) {
          assert(xs[i2].shape[0] === dim_1, function() {
            return "Gram-Schmidt: Non-unique lengths found in the input vectors: " + "(".concat(xs[i2].shape[0], " vs. ").concat(dim_1, ")");
          });
        };
        for (var i = 1; i < xs.length; ++i) {
          _loop_1(i);
        }
      } else {
        inputIsTensor2D = true;
        xs = split(xs, xs.shape[0], 0).map(function(x) {
          return squeeze(x, [0]);
        });
      }
      assert(xs.length <= xs[0].shape[0], function() {
        return "Gram-Schmidt: Number of vectors (".concat(xs.length, ") exceeds ") + "number of dimensions (".concat(xs[0].shape[0], ").");
      });
      var ys = [];
      var xs1d = xs;
      var _loop_2 = function(i2) {
        ys.push(ENGINE.tidy(function() {
          var x = xs1d[i2];
          if (i2 > 0) {
            for (var j = 0; j < i2; ++j) {
              var proj = mul(sum(mul(ys[j], x)), ys[j]);
              x = sub(x, proj);
            }
          }
          return div(x, norm(x, "euclidean"));
        }));
      };
      for (var i = 0; i < xs.length; ++i) {
        _loop_2(i);
      }
      if (inputIsTensor2D) {
        return stack(ys, 0);
      } else {
        return ys;
      }
    }
    var gramSchmidt = /* @__PURE__ */ op({ gramSchmidt_ });
    function qr_(x, fullMatrices) {
      if (fullMatrices === void 0) {
        fullMatrices = false;
      }
      assert(x.rank >= 2, function() {
        return "qr() requires input tensor to have a rank >= 2, but got rank ".concat(x.rank);
      });
      if (x.rank === 2) {
        return qr2d(x, fullMatrices);
      } else {
        var outerDimsProd = x.shape.slice(0, x.shape.length - 2).reduce(function(value, prev) {
          return value * prev;
        });
        var x2ds = unstack(reshape(x, [
          outerDimsProd,
          x.shape[x.shape.length - 2],
          x.shape[x.shape.length - 1]
        ]), 0);
        var q2ds_1 = [];
        var r2ds_1 = [];
        x2ds.forEach(function(x2d) {
          var _a = __read(qr2d(x2d, fullMatrices), 2), q2d = _a[0], r2d = _a[1];
          q2ds_1.push(q2d);
          r2ds_1.push(r2d);
        });
        var q = reshape(stack(q2ds_1, 0), x.shape);
        var r = reshape(stack(r2ds_1, 0), x.shape);
        return [q, r];
      }
    }
    function qr2d(x, fullMatrices) {
      if (fullMatrices === void 0) {
        fullMatrices = false;
      }
      return ENGINE.tidy(function() {
        assert(x.shape.length === 2, function() {
          return "qr2d() requires a 2D Tensor, but got a ".concat(x.shape.length, "D Tensor.");
        });
        var m = x.shape[0];
        var n = x.shape[1];
        var q = eye(m);
        var r = clone(x);
        var one2D = tensor2d([[1]], [1, 1]);
        var w = clone(one2D);
        var iters = m >= n ? n : m;
        var _loop_1 = function(j2) {
          var _a;
          var rTemp = r;
          var wTemp = w;
          var qTemp = q;
          _a = __read(ENGINE.tidy(function() {
            var rjEnd1 = slice(r, [j2, j2], [m - j2, 1]);
            var normX = norm(rjEnd1);
            var rjj = slice(r, [j2, j2], [1, 1]);
            var s = where(greater(rjj, 0), tensor2d([[-1]]), tensor2d([[1]]));
            var u1 = sub(rjj, mul(s, normX));
            var wPre = div(rjEnd1, u1);
            if (wPre.shape[0] === 1) {
              w = clone(one2D);
            } else {
              w = concat([
                one2D,
                slice(wPre, [1, 0], [wPre.shape[0] - 1, wPre.shape[1]])
              ], 0);
            }
            var tau = neg(div(matMul$1(s, u1), normX));
            var rjEndAll = slice(r, [j2, 0], [m - j2, n]);
            var tauTimesW = mul(tau, w);
            var wT = transpose(w);
            if (j2 === 0) {
              r = sub(rjEndAll, matMul$1(tauTimesW, matMul$1(wT, rjEndAll)));
            } else {
              var rTimesTau = sub(rjEndAll, matMul$1(tauTimesW, matMul$1(wT, rjEndAll)));
              r = concat([slice(r, [0, 0], [j2, n]), rTimesTau], 0);
            }
            var tawTimesWT = transpose(tauTimesW);
            var qAllJEnd = slice(q, [0, j2], [m, q.shape[1] - j2]);
            if (j2 === 0) {
              q = sub(qAllJEnd, matMul$1(matMul$1(qAllJEnd, w), tawTimesWT));
            } else {
              var qTimesTau = sub(qAllJEnd, matMul$1(matMul$1(qAllJEnd, w), tawTimesWT));
              q = concat([slice(q, [0, 0], [m, j2]), qTimesTau], 1);
            }
            return [w, r, q];
          }), 3), w = _a[0], r = _a[1], q = _a[2];
          dispose([rTemp, wTemp, qTemp]);
        };
        for (var j = 0; j < iters; ++j) {
          _loop_1(j);
        }
        if (!fullMatrices && m > n) {
          q = slice(q, [0, 0], [m, n]);
          r = slice(r, [0, 0], [n, n]);
        }
        return [q, r];
      });
    }
    var qr = /* @__PURE__ */ op({ qr_ });
    exports2.Reduction = void 0;
    (function(Reduction) {
      Reduction[Reduction["NONE"] = 0] = "NONE";
      Reduction[Reduction["MEAN"] = 1] = "MEAN";
      Reduction[Reduction["SUM"] = 2] = "SUM";
      Reduction[Reduction["SUM_BY_NONZERO_WEIGHTS"] = 3] = "SUM_BY_NONZERO_WEIGHTS";
    })(exports2.Reduction || (exports2.Reduction = {}));
    function computeWeightedLoss_(losses2, weights, reduction) {
      if (reduction === void 0) {
        reduction = exports2.Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $losses = convertToTensor(losses2, "losses", "computeWeightedLoss");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "computeWeightedLoss");
      }
      var weightedLoss = $weights == null ? $losses : mul($losses, $weights);
      if (reduction === exports2.Reduction.NONE) {
        return weightedLoss;
      }
      if (reduction === exports2.Reduction.SUM) {
        return sum(weightedLoss);
      }
      if (reduction === exports2.Reduction.MEAN) {
        if ($weights == null) {
          return mean(weightedLoss);
        } else {
          var broadcastFactor = $losses.size / $weights.size;
          var result = div(sum(weightedLoss), sum($weights));
          return broadcastFactor > 1 ? div(result, scalar(broadcastFactor)) : result;
        }
      }
      if (reduction === exports2.Reduction.SUM_BY_NONZERO_WEIGHTS) {
        if ($weights == null) {
          return div(sum(weightedLoss), scalar($losses.size));
        } else {
          var broadcastedWeights = mul($weights, ones($losses.shape));
          var numNonZeros = cast(sum(notEqual(broadcastedWeights, scalar(0))), "float32");
          return div(sum(weightedLoss), numNonZeros);
        }
      }
      throw Error("Unknown reduction: ".concat(reduction));
    }
    var computeWeightedLoss = /* @__PURE__ */ op({ computeWeightedLoss_ });
    function absoluteDifference_(labels, predictions, weights, reduction) {
      if (reduction === void 0) {
        reduction = exports2.Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $labels = convertToTensor(labels, "labels", "absoluteDifference");
      var $predictions = convertToTensor(predictions, "predictions", "absoluteDifference");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "absoluteDifference");
      }
      assertShapesMatch($labels.shape, $predictions.shape, "Error in absoluteDifference: ");
      var losses2 = abs(sub($labels, $predictions));
      return computeWeightedLoss(losses2, $weights, reduction);
    }
    var absoluteDifference = /* @__PURE__ */ op({ absoluteDifference_ });
    function cosineDistance_(labels, predictions, axis, weights, reduction) {
      if (reduction === void 0) {
        reduction = exports2.Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $labels = convertToTensor(labels, "labels", "cosineDistance");
      var $predictions = convertToTensor(predictions, "predictions", "cosineDistance");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "cosineDistance");
      }
      assertShapesMatch($labels.shape, $predictions.shape, "Error in cosineDistance: ");
      var one = scalar(1);
      var losses2 = sub(one, sum(mul($labels, $predictions), axis, true));
      return computeWeightedLoss(losses2, $weights, reduction);
    }
    var cosineDistance = /* @__PURE__ */ op({ cosineDistance_ });
    function hingeLoss_(labels, predictions, weights, reduction) {
      if (reduction === void 0) {
        reduction = exports2.Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $labels = convertToTensor(labels, "labels", "hingeLoss");
      var $predictions = convertToTensor(predictions, "predictions", "hingeLoss");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "hingeLoss");
      }
      assertShapesMatch($labels.shape, $predictions.shape, "Error in hingeLoss: ");
      var one = scalar(1);
      $labels = sub(mul(scalar(2), $labels), one);
      var losses2 = relu(sub(one, mul($labels, $predictions)));
      return computeWeightedLoss(losses2, $weights, reduction);
    }
    var hingeLoss = /* @__PURE__ */ op({ hingeLoss_ });
    function huberLoss_(labels, predictions, weights, delta, reduction) {
      if (delta === void 0) {
        delta = 1;
      }
      if (reduction === void 0) {
        reduction = exports2.Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $labels = convertToTensor(labels, "labels", "huberLoss");
      var $predictions = convertToTensor(predictions, "predictions", "huberLoss");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "huberLoss");
      }
      assertShapesMatch($labels.shape, $predictions.shape, "Error in huberLoss: ");
      var deltaScalar = scalar(delta);
      var error = abs(sub($predictions, $labels));
      var quadratic = minimum(error, deltaScalar);
      var linear = sub(error, quadratic);
      var losses2 = add(mul(scalar(0.5), square(quadratic)), mul(deltaScalar, linear));
      return computeWeightedLoss(losses2, $weights, reduction);
    }
    var huberLoss = /* @__PURE__ */ op({ huberLoss_ });
    function logLoss_(labels, predictions, weights, epsilon, reduction) {
      if (epsilon === void 0) {
        epsilon = 1e-7;
      }
      if (reduction === void 0) {
        reduction = exports2.Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $labels = convertToTensor(labels, "labels", "logLoss");
      var $predictions = convertToTensor(predictions, "predictions", "logLoss");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "logLoss");
      }
      assertShapesMatch($labels.shape, $predictions.shape, "Error in logLoss: ");
      var one = scalar(1);
      var epsilonScalar = scalar(epsilon);
      var l1 = neg(mul($labels, log(add($predictions, epsilonScalar))));
      var l2 = mul(sub(one, $labels), log(add(sub(one, $predictions), epsilonScalar)));
      var losses2 = sub(l1, l2);
      return computeWeightedLoss(losses2, $weights, reduction);
    }
    var logLoss = /* @__PURE__ */ op({ logLoss_ });
    function meanSquaredError_(labels, predictions, weights, reduction) {
      if (reduction === void 0) {
        reduction = exports2.Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $labels = convertToTensor(labels, "labels", "meanSquaredError");
      var $predictions = convertToTensor(predictions, "predictions", "meanSquaredError");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "meanSquaredError");
      }
      assertShapesMatch($labels.shape, $predictions.shape, "Error in meanSquaredError: ");
      var losses2 = squaredDifference($labels, $predictions);
      return computeWeightedLoss(losses2, $weights, reduction);
    }
    var meanSquaredError = /* @__PURE__ */ op({ meanSquaredError_ });
    function sigmoidCrossEntropyWithLogits_(labels, logits) {
      var $labels = convertToTensor(labels, "labels", "sigmoidCrossEntropyWithLogits");
      var $logits = convertToTensor(logits, "logits", "sigmoidCrossEntropyWithLogits");
      assertShapesMatch($labels.shape, $logits.shape, "Error in sigmoidCrossEntropyWithLogits: ");
      var maxOutput = relu($logits);
      var outputXTarget = mul($logits, $labels);
      var sigmoidOutput = log1p(exp(neg(abs($logits))));
      return add(sub(maxOutput, outputXTarget), sigmoidOutput);
    }
    function sigmoidCrossEntropy_(multiClassLabels, logits, weights, labelSmoothing, reduction) {
      if (labelSmoothing === void 0) {
        labelSmoothing = 0;
      }
      if (reduction === void 0) {
        reduction = exports2.Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $multiClassLabels = convertToTensor(multiClassLabels, "multiClassLabels", "sigmoidCrossEntropy");
      var $logits = convertToTensor(logits, "logits", "sigmoidCrossEntropy");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "sigmoidCrossEntropy");
      }
      assertShapesMatch($multiClassLabels.shape, $logits.shape, "Error in sigmoidCrossEntropy: ");
      if (labelSmoothing > 0) {
        var labelSmoothingScalar = scalar(labelSmoothing);
        var one = scalar(1);
        var half = scalar(0.5);
        $multiClassLabels = add(mul($multiClassLabels, sub(one, labelSmoothingScalar)), mul(half, labelSmoothingScalar));
      }
      var losses2 = sigmoidCrossEntropyWithLogits_($multiClassLabels, $logits);
      return computeWeightedLoss(losses2, $weights, reduction);
    }
    var sigmoidCrossEntropy = /* @__PURE__ */ op({ sigmoidCrossEntropy_ });
    function softmaxCrossEntropyWithLogits_(labels, logits, dim) {
      if (dim === void 0) {
        dim = -1;
      }
      if (dim === -1) {
        dim = logits.rank - 1;
      }
      if (dim !== logits.rank - 1) {
        throw Error("Softmax cross entropy along a non-last dimension is not yet " + "supported. Labels / logits was rank ".concat(logits.rank, " ") + "and dim was ".concat(dim));
      }
      var customOp = customGrad(function(labels2, logits2, save) {
        var keepDims = true;
        var lse = logSumExp(logits2, [dim], keepDims);
        var logResult = sub(cast(logits2, "float32"), lse);
        save([labels2, logResult]);
        var costVector = neg(mul(logResult, labels2));
        var value = sum(costVector, [dim]);
        var gradFunc = function(dy, saved) {
          var _a = __read(saved, 2), labels3 = _a[0], logResult2 = _a[1];
          var dyShape = expandShapeToKeepDim(dy.shape, [dim]);
          return [
            mul(reshape(dy, dyShape), sub(cast(labels3, "float32"), exp(logResult2))),
            mul(reshape(dy, dyShape), sub(exp(logResult2), cast(labels3, "float32")))
          ];
        };
        return { value, gradFunc };
      });
      return customOp(labels, logits);
    }
    function softmaxCrossEntropy_(onehotLabels, logits, weights, labelSmoothing, reduction) {
      if (labelSmoothing === void 0) {
        labelSmoothing = 0;
      }
      if (reduction === void 0) {
        reduction = exports2.Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $onehotLabels = convertToTensor(onehotLabels, "onehotLabels", "softmaxCrossEntropy");
      var $logits = convertToTensor(logits, "logits", "softmaxCrossEntropy");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "softmaxCrossEntropy");
      }
      assertShapesMatch($onehotLabels.shape, $logits.shape, "Error in softmaxCrossEntropy: ");
      if (labelSmoothing > 0) {
        var labelSmoothingScalar = scalar(labelSmoothing);
        var one = scalar(1);
        var numClasses = scalar($onehotLabels.shape[1]);
        $onehotLabels = add(mul($onehotLabels, sub(one, labelSmoothingScalar)), div(labelSmoothingScalar, numClasses));
      }
      var losses2 = softmaxCrossEntropyWithLogits_($onehotLabels, $logits);
      return computeWeightedLoss(losses2, $weights, reduction);
    }
    var softmaxCrossEntropy = /* @__PURE__ */ op({ softmaxCrossEntropy_ });
    function sparseFillEmptyRows_(indices, values, denseShape, defaultValue) {
      var $indices = convertToTensor(indices, "indices", "sparseFillEmptyRows", "int32");
      var $values = convertToTensor(values, "values", "sparseFillEmptyRows");
      var $denseShape = convertToTensor(denseShape, "denseShape", "sparseFillEmptyRows", "int32");
      var $defaultValue = convertToTensor(defaultValue, "defaultValue", "sparseFillEmptyRows", $values.dtype);
      if ($indices.rank !== 2) {
        throw new Error("Indices should be Tensor2D but received shape\n        ".concat($indices.shape));
      }
      if ($values.rank !== 1) {
        throw new Error("Values should be Tensor1D but received shape ".concat($values.shape));
      }
      if ($denseShape.rank !== 1) {
        throw new Error("Dense shape should be Tensor1D but received shape ".concat($denseShape.shape));
      }
      if ($defaultValue.rank !== 0) {
        throw new Error("Default value should be a scalar but received shape ".concat($defaultValue.shape));
      }
      var inputs = {
        indices: $indices,
        values: $values,
        denseShape: $denseShape,
        defaultValue: $defaultValue
      };
      var result = ENGINE.runKernel(SparseFillEmptyRows, inputs);
      return {
        outputIndices: result[0],
        outputValues: result[1],
        emptyRowIndicator: result[2],
        reverseIndexMap: result[3]
      };
    }
    var sparseFillEmptyRows = /* @__PURE__ */ op({ sparseFillEmptyRows_ });
    function sparseReshape_(inputIndices, inputShape, newShape) {
      var $inputIndices = convertToTensor(inputIndices, "inputIndices", "sparseReshape", "int32");
      var $inputShape = convertToTensor(inputShape, "inputShape", "sparseReshape", "int32");
      var $newShape = convertToTensor(newShape, "newShape", "sparseReshape", "int32");
      if ($inputIndices.rank !== 2) {
        throw new Error("Input indices should be Tensor2D but received shape\n        ".concat($inputIndices.shape));
      }
      if ($inputShape.rank !== 1) {
        throw new Error("Input shape should be Tensor1D but received shape ".concat($inputShape.shape));
      }
      if ($newShape.rank !== 1) {
        throw new Error("New shape should be Tensor1D but received shape ".concat($newShape.shape));
      }
      var inputs = {
        inputIndices: $inputIndices,
        inputShape: $inputShape,
        newShape: $newShape
      };
      var result = ENGINE.runKernel(SparseReshape, inputs);
      return { outputIndices: result[0], outputShape: result[1] };
    }
    var sparseReshape = /* @__PURE__ */ op({ sparseReshape_ });
    function sparseSegmentMean_(data, indices, segmentIds) {
      var $data = convertToTensor(data, "data", "sparseSegmentMean");
      var $indices = convertToTensor(indices, "indices", "sparseSegmentMean", "int32");
      var $segmentIds = convertToTensor(segmentIds, "segmentIds", "sparseSegmentMean", "int32");
      if ($data.rank < 1) {
        throw new Error("Data should be at least 1 dimensional but received scalar");
      }
      if ($indices.rank !== 1) {
        throw new Error("Indices should be Tensor1D but received shape\n          ".concat($indices.shape));
      }
      if ($segmentIds.rank !== 1) {
        throw new Error("Segment ids should be Tensor1D but received shape\n          ".concat($segmentIds.shape));
      }
      var inputs = {
        data: $data,
        indices: $indices,
        segmentIds: $segmentIds
      };
      return ENGINE.runKernel(SparseSegmentMean, inputs);
    }
    var sparseSegmentMean = /* @__PURE__ */ op({ sparseSegmentMean_ });
    function sparseSegmentSum_(data, indices, segmentIds) {
      var $data = convertToTensor(data, "data", "sparseSegmentSum");
      var $indices = convertToTensor(indices, "indices", "sparseSegmentSum", "int32");
      var $segmentIds = convertToTensor(segmentIds, "segmentIds", "sparseSegmentSum", "int32");
      if ($data.rank < 1) {
        throw new Error("Data should be at least 1 dimensional but received scalar");
      }
      if ($indices.rank !== 1) {
        throw new Error("Indices should be Tensor1D but received shape\n         ".concat($indices.shape));
      }
      if ($segmentIds.rank !== 1) {
        throw new Error("Segment ids should be Tensor1D but received shape\n         ".concat($segmentIds.shape));
      }
      var inputs = {
        data: $data,
        indices: $indices,
        segmentIds: $segmentIds
      };
      return ENGINE.runKernel(SparseSegmentSum, inputs);
    }
    var sparseSegmentSum = /* @__PURE__ */ op({ sparseSegmentSum_ });
    function stringNGrams_(data, dataSplits, separator, nGramWidths, leftPad, rightPad2, padWidth, preserveShortSequences) {
      var $data = convertToTensor(data, "data", "stringNGrams", "string");
      if ($data.dtype !== "string") {
        throw new Error("Data must be of datatype string");
      }
      if ($data.shape.length !== 1) {
        throw new Error("Data must be a vector, saw: ".concat($data.shape));
      }
      var $dataSplits = convertToTensor(dataSplits, "dataSplits", "stringNGrams");
      if ($dataSplits.dtype !== "int32") {
        throw new Error("Data splits must be of datatype int32");
      }
      var attrs = {
        separator,
        nGramWidths,
        leftPad,
        rightPad: rightPad2,
        padWidth,
        preserveShortSequences
      };
      var inputs = { data: $data, dataSplits: $dataSplits };
      var result = ENGINE.runKernel(StringNGrams, inputs, attrs);
      return { nGrams: result[0], nGramsSplits: result[1] };
    }
    var stringNGrams = /* @__PURE__ */ op({ stringNGrams_ });
    function stringSplit_(input, delimiter, skipEmpty) {
      if (skipEmpty === void 0) {
        skipEmpty = true;
      }
      var $input = convertToTensor(input, "input", "stringSplit", "string");
      var $delimiter = convertToTensor(delimiter, "delimiter", "stringSplit", "string");
      if ($input.rank !== 1) {
        throw new Error("Input should be Tensor1D but received shape ".concat($input.shape));
      }
      if ($delimiter.rank !== 0) {
        throw new Error("Delimiter should be a scalar but received shape ".concat($delimiter.shape));
      }
      var attrs = { skipEmpty };
      var inputs = { input: $input, delimiter: $delimiter };
      var result = ENGINE.runKernel(StringSplit, inputs, attrs);
      return { indices: result[0], values: result[1], shape: result[2] };
    }
    var stringSplit = /* @__PURE__ */ op({ stringSplit_ });
    function stringToHashBucketFast_(input, numBuckets) {
      var $input = convertToTensor(input, "input", "stringToHashBucketFast", "string");
      var attrs = { numBuckets };
      if (numBuckets <= 0) {
        throw new Error("Number of buckets must be at least 1");
      }
      var inputs = { input: $input };
      return ENGINE.runKernel(StringToHashBucketFast, inputs, attrs);
    }
    var stringToHashBucketFast = /* @__PURE__ */ op({ stringToHashBucketFast_ });
    function staticRegexReplace_(input, pattern, rewrite, replaceGlobal) {
      if (replaceGlobal === void 0) {
        replaceGlobal = true;
      }
      var $input = convertToTensor(input, "input", "staticRegexReplace", "string");
      var attrs = { pattern, rewrite, replaceGlobal };
      return ENGINE.runKernel(StaticRegexReplace, { x: $input }, attrs);
    }
    var staticRegexReplace = /* @__PURE__ */ op({ staticRegexReplace_ });
    var spectral = {
      fft,
      ifft,
      rfft,
      irfft
    };
    var signal = {
      hammingWindow,
      hannWindow,
      frame,
      stft
    };
    var image = {
      flipLeftRight,
      grayscaleToRGB,
      resizeNearestNeighbor,
      resizeBilinear,
      rgbToGrayscale,
      rotateWithOffset,
      cropAndResize,
      nonMaxSuppression,
      nonMaxSuppressionAsync,
      nonMaxSuppressionWithScore,
      nonMaxSuppressionWithScoreAsync,
      nonMaxSuppressionPadded,
      nonMaxSuppressionPaddedAsync,
      threshold,
      transform
    };
    var linalg = {
      bandPart,
      gramSchmidt,
      qr
    };
    var losses = {
      absoluteDifference,
      computeWeightedLoss,
      cosineDistance,
      hingeLoss,
      huberLoss,
      logLoss,
      meanSquaredError,
      sigmoidCrossEntropy,
      softmaxCrossEntropy
    };
    var sparse = {
      sparseFillEmptyRows,
      sparseReshape,
      sparseSegmentMean,
      sparseSegmentSum
    };
    var string = {
      stringNGrams,
      stringSplit,
      stringToHashBucketFast,
      staticRegexReplace
    };
    var GLOBAL_CUSTOM_OBJECT = /* @__PURE__ */ new Map();
    var GLOBAL_CUSTOM_NAMES = /* @__PURE__ */ new Map();
    var Serializable = (
      /** @class */
      function() {
        function Serializable2() {
        }
        Serializable2.prototype.getClassName = function() {
          return this.constructor.className;
        };
        Serializable2.fromConfig = function(cls, config) {
          return new cls(config);
        };
        return Serializable2;
      }()
    );
    var SerializationMap = (
      /** @class */
      function() {
        function SerializationMap2() {
          this.classNameMap = {};
        }
        SerializationMap2.getMap = function() {
          if (SerializationMap2.instance == null) {
            SerializationMap2.instance = new SerializationMap2();
          }
          return SerializationMap2.instance;
        };
        SerializationMap2.register = function(cls) {
          SerializationMap2.getMap().classNameMap[cls.className] = [cls, cls.fromConfig];
        };
        return SerializationMap2;
      }()
    );
    function registerClass(cls, pkg, name) {
      assert(cls.className != null, function() {
        return "Class being registered does not have the static className property defined.";
      });
      assert(typeof cls.className === "string", function() {
        return "className is required to be a string, but got type " + typeof cls.className;
      });
      assert(cls.className.length > 0, function() {
        return "Class being registered has an empty-string as its className, which is disallowed.";
      });
      if (typeof pkg === "undefined") {
        pkg = "Custom";
      }
      if (typeof name === "undefined") {
        name = cls.className;
      }
      var className = name;
      var registerName = pkg + ">" + className;
      SerializationMap.register(cls);
      GLOBAL_CUSTOM_OBJECT.set(registerName, cls);
      GLOBAL_CUSTOM_NAMES.set(cls, registerName);
      return cls;
    }
    function getRegisteredName(cls) {
      if (GLOBAL_CUSTOM_NAMES.has(cls)) {
        return GLOBAL_CUSTOM_NAMES.get(cls);
      } else {
        return cls.className;
      }
    }
    var serialization = {
      __proto__: null,
      Serializable,
      SerializationMap,
      getRegisteredName,
      registerClass
    };
    var Optimizer = (
      /** @class */
      function(_super) {
        __extends(Optimizer2, _super);
        function Optimizer2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Optimizer2.prototype.minimize = function(f, returnCost, varList) {
          if (returnCost === void 0) {
            returnCost = false;
          }
          var _a = this.computeGradients(f, varList), value = _a.value, grads2 = _a.grads;
          if (varList != null) {
            var gradArray = varList.map(function(v) {
              return { name: v.name, tensor: grads2[v.name] };
            });
            this.applyGradients(gradArray);
          } else {
            this.applyGradients(grads2);
          }
          dispose(grads2);
          if (returnCost) {
            return value;
          } else {
            value.dispose();
            return null;
          }
        };
        Object.defineProperty(Optimizer2.prototype, "iterations", {
          /**
           * The number of iterations that this optimizer instance has been invoked for.
           */
          get: function() {
            if (this.iterations_ == null) {
              this.iterations_ = 0;
            }
            return this.iterations_;
          },
          enumerable: false,
          configurable: true
        });
        Optimizer2.prototype.incrementIterations = function() {
          this.iterations_ = this.iterations + 1;
        };
        Optimizer2.prototype.computeGradients = function(f, varList) {
          return variableGrads(f, varList);
        };
        Optimizer2.prototype.dispose = function() {
          if (this.iterations_ != null) {
            dispose(this.iterations_);
          }
        };
        Optimizer2.prototype.saveIterations = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              if (this.iterations_ == null) {
                this.iterations_ = 0;
              }
              return [2, {
                name: "iter",
                // TODO(cais): Use 'int64' type when available.
                tensor: scalar(this.iterations_, "int32")
              }];
            });
          });
        };
        Optimizer2.prototype.getWeights = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              throw new Error("getWeights() is not implemented for this optimizer yet.");
            });
          });
        };
        Optimizer2.prototype.setWeights = function(weightValues) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              throw new Error("setWeights() is not implemented for this optimizer class " + "".concat(this.getClassName()));
            });
          });
        };
        Optimizer2.prototype.extractIterations = function(weightValues) {
          return __awaiter(this, void 0, void 0, function() {
            var _a;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  _a = this;
                  return [4, weightValues[0].tensor.data()];
                case 1:
                  _a.iterations_ = _b.sent()[0];
                  return [2, weightValues.slice(1)];
              }
            });
          });
        };
        return Optimizer2;
      }(Serializable)
    );
    Object.defineProperty(Optimizer, Symbol.hasInstance, {
      value: function(instance) {
        return instance.minimize != null && instance.computeGradients != null && instance.applyGradients != null;
      }
    });
    var AdadeltaOptimizer = (
      /** @class */
      function(_super) {
        __extends(AdadeltaOptimizer2, _super);
        function AdadeltaOptimizer2(learningRate, rho, epsilon) {
          if (epsilon === void 0) {
            epsilon = null;
          }
          var _this = _super.call(this) || this;
          _this.learningRate = learningRate;
          _this.rho = rho;
          _this.epsilon = epsilon;
          _this.accumulatedGrads = [];
          _this.accumulatedUpdates = [];
          if (epsilon == null) {
            _this.epsilon = ENGINE.backend.epsilon();
          }
          return _this;
        }
        Object.defineProperty(AdadeltaOptimizer2, "className", {
          /** @nocollapse */
          get: function() {
            return "Adadelta";
          },
          enumerable: false,
          configurable: true
        });
        AdadeltaOptimizer2.prototype.applyGradients = function(variableGradients) {
          var _this = this;
          var variableNames = Array.isArray(variableGradients) ? variableGradients.map(function(item) {
            return item.name;
          }) : Object.keys(variableGradients);
          variableNames.forEach(function(name, i) {
            var value = ENGINE.registeredVariables[name];
            var trainable = false;
            if (_this.accumulatedGrads[i] == null) {
              _this.accumulatedGrads[i] = {
                originalName: "".concat(name, "/accum_grad"),
                variable: tidy(function() {
                  return zerosLike(value).variable(trainable);
                })
              };
            }
            if (_this.accumulatedUpdates[i] == null) {
              _this.accumulatedUpdates[i] = {
                originalName: "".concat(name, "/accum_var"),
                variable: tidy(function() {
                  return zerosLike(value).variable(trainable);
                })
              };
            }
            var gradient = Array.isArray(variableGradients) ? variableGradients[i].tensor : variableGradients[name];
            if (gradient == null) {
              return;
            }
            var accumulatedGrad = _this.accumulatedGrads[i].variable;
            var accumulatedUpdate = _this.accumulatedUpdates[i].variable;
            tidy(function() {
              var newAccumulatedGrad = add(mul(accumulatedGrad, _this.rho), mul(square(gradient), 1 - _this.rho));
              var updates = mul(div(sqrt(add(accumulatedUpdate, _this.epsilon)), sqrt(add(accumulatedGrad, _this.epsilon))), gradient);
              var newAccumulatedUpdate = add(mul(accumulatedUpdate, _this.rho), mul(square(updates), 1 - _this.rho));
              accumulatedGrad.assign(newAccumulatedGrad);
              accumulatedUpdate.assign(newAccumulatedUpdate);
              var newValue = add(mul(updates, -_this.learningRate), value);
              value.assign(newValue);
            });
          });
          this.incrementIterations();
        };
        AdadeltaOptimizer2.prototype.dispose = function() {
          if (this.accumulatedUpdates != null) {
            dispose(this.accumulatedGrads.map(function(v) {
              return v.variable;
            }));
            dispose(this.accumulatedUpdates.map(function(v) {
              return v.variable;
            }));
          }
        };
        AdadeltaOptimizer2.prototype.getWeights = function() {
          return __awaiter(this, void 0, void 0, function() {
            var variables;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  variables = __spreadArray(__spreadArray([], __read(this.accumulatedGrads), false), __read(this.accumulatedUpdates), false);
                  return [4, this.saveIterations()];
                case 1:
                  return [2, [_a.sent()].concat(variables.map(function(v) {
                    return { name: v.originalName, tensor: v.variable };
                  }))];
              }
            });
          });
        };
        AdadeltaOptimizer2.prototype.setWeights = function(weightValues) {
          return __awaiter(this, void 0, void 0, function() {
            var variableCount, trainable;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.extractIterations(weightValues)];
                case 1:
                  weightValues = _a.sent();
                  variableCount = weightValues.length / 2;
                  trainable = false;
                  this.accumulatedGrads = weightValues.slice(0, variableCount).map(function(v) {
                    return {
                      originalName: v.name,
                      variable: v.tensor.variable(trainable)
                    };
                  });
                  this.accumulatedUpdates = weightValues.slice(variableCount, variableCount * 2).map(function(v) {
                    return {
                      originalName: v.name,
                      variable: v.tensor.variable(trainable)
                    };
                  });
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        AdadeltaOptimizer2.prototype.getConfig = function() {
          return {
            "learningRate": this.learningRate,
            "rho": this.rho,
            "epsilon": this.epsilon
          };
        };
        AdadeltaOptimizer2.fromConfig = function(cls, config) {
          return new cls(config["learningRate"], config["rho"], config["epsilon"]);
        };
        return AdadeltaOptimizer2;
      }(Optimizer)
    );
    var AdagradOptimizer = (
      /** @class */
      function(_super) {
        __extends(AdagradOptimizer2, _super);
        function AdagradOptimizer2(learningRate, initialAccumulatorValue) {
          if (initialAccumulatorValue === void 0) {
            initialAccumulatorValue = 0.1;
          }
          var _this = _super.call(this) || this;
          _this.learningRate = learningRate;
          _this.initialAccumulatorValue = initialAccumulatorValue;
          _this.accumulatedGrads = [];
          return _this;
        }
        Object.defineProperty(AdagradOptimizer2, "className", {
          /** @nocollapse */
          get: function() {
            return "Adagrad";
          },
          enumerable: false,
          configurable: true
        });
        AdagradOptimizer2.prototype.applyGradients = function(variableGradients) {
          var _this = this;
          var variableNames = Array.isArray(variableGradients) ? variableGradients.map(function(item) {
            return item.name;
          }) : Object.keys(variableGradients);
          variableNames.forEach(function(name, i) {
            var value = ENGINE.registeredVariables[name];
            if (_this.accumulatedGrads[i] == null) {
              var trainable_1 = false;
              _this.accumulatedGrads[i] = {
                originalName: "".concat(name, "/accumulator"),
                variable: tidy(function() {
                  return fill(value.shape, _this.initialAccumulatorValue).variable(trainable_1);
                })
              };
            }
            var gradient = Array.isArray(variableGradients) ? variableGradients[i].tensor : variableGradients[name];
            if (gradient == null) {
              return;
            }
            var accumulatedGrad = _this.accumulatedGrads[i].variable;
            tidy(function() {
              var newAccumulatedGrad = add(accumulatedGrad, square(gradient));
              accumulatedGrad.assign(newAccumulatedGrad);
              var newValue = add(mul(div(gradient, sqrt(add(newAccumulatedGrad, ENGINE.backend.epsilon()))), -_this.learningRate), value);
              value.assign(newValue);
            });
          });
          this.incrementIterations();
        };
        AdagradOptimizer2.prototype.dispose = function() {
          if (this.accumulatedGrads != null) {
            dispose(this.accumulatedGrads.map(function(v) {
              return v.variable;
            }));
          }
        };
        AdagradOptimizer2.prototype.getWeights = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.saveIterations()];
                case 1:
                  return [2, [_a.sent()].concat(this.accumulatedGrads.map(function(v) {
                    return { name: v.originalName, tensor: v.variable };
                  }))];
              }
            });
          });
        };
        AdagradOptimizer2.prototype.setWeights = function(weightValues) {
          return __awaiter(this, void 0, void 0, function() {
            var trainable;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.extractIterations(weightValues)];
                case 1:
                  weightValues = _a.sent();
                  trainable = false;
                  this.accumulatedGrads = weightValues.map(function(v) {
                    return { originalName: v.name, variable: v.tensor.variable(trainable) };
                  });
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        AdagradOptimizer2.prototype.getConfig = function() {
          return {
            "learningRate": this.learningRate,
            "initialAccumulatorValue": this.initialAccumulatorValue
          };
        };
        AdagradOptimizer2.fromConfig = function(cls, config) {
          return new cls(config["learningRate"], config["initialAccumulatorValue"]);
        };
        return AdagradOptimizer2;
      }(Optimizer)
    );
    var AdamOptimizer = (
      /** @class */
      function(_super) {
        __extends(AdamOptimizer2, _super);
        function AdamOptimizer2(learningRate, beta1, beta2, epsilon) {
          if (epsilon === void 0) {
            epsilon = null;
          }
          var _this = _super.call(this) || this;
          _this.learningRate = learningRate;
          _this.beta1 = beta1;
          _this.beta2 = beta2;
          _this.epsilon = epsilon;
          _this.accumulatedFirstMoment = [];
          _this.accumulatedSecondMoment = [];
          tidy(function() {
            _this.accBeta1 = scalar(beta1).variable();
            _this.accBeta2 = scalar(beta2).variable();
          });
          if (epsilon == null) {
            _this.epsilon = ENGINE.backend.epsilon();
          }
          return _this;
        }
        Object.defineProperty(AdamOptimizer2, "className", {
          /** @nocollapse */
          get: function() {
            return "Adam";
          },
          enumerable: false,
          configurable: true
        });
        AdamOptimizer2.prototype.applyGradients = function(variableGradients) {
          var _this = this;
          var varNames = Array.isArray(variableGradients) ? variableGradients.map(function(v) {
            return v.name;
          }) : Object.keys(variableGradients);
          tidy(function() {
            var oneMinusAccBeta1 = sub(1, _this.accBeta1);
            var oneMinusAccBeta2 = sub(1, _this.accBeta2);
            varNames.forEach(function(name, i) {
              var value = ENGINE.registeredVariables[name];
              var trainable = false;
              if (_this.accumulatedFirstMoment[i] == null) {
                _this.accumulatedFirstMoment[i] = {
                  originalName: "".concat(name, "/m"),
                  variable: tidy(function() {
                    return zerosLike(value).variable(trainable);
                  })
                };
              }
              if (_this.accumulatedSecondMoment[i] == null) {
                _this.accumulatedSecondMoment[i] = {
                  originalName: "".concat(name, "/v"),
                  variable: tidy(function() {
                    return zerosLike(value).variable(trainable);
                  })
                };
              }
              var gradient = Array.isArray(variableGradients) ? variableGradients[i].tensor : variableGradients[name];
              if (gradient == null) {
                return;
              }
              var firstMoment = _this.accumulatedFirstMoment[i].variable;
              var secondMoment = _this.accumulatedSecondMoment[i].variable;
              var newFirstMoment = add(mul(firstMoment, _this.beta1), mul(gradient, 1 - _this.beta1));
              var newSecondMoment = add(mul(secondMoment, _this.beta2), mul(square(gradient), 1 - _this.beta2));
              var biasCorrectedFirstMoment = div(newFirstMoment, oneMinusAccBeta1);
              var biasCorrectedSecondMoment = div(newSecondMoment, oneMinusAccBeta2);
              firstMoment.assign(newFirstMoment);
              secondMoment.assign(newSecondMoment);
              var newValue = add(mul(div(biasCorrectedFirstMoment, add(sqrt(biasCorrectedSecondMoment), _this.epsilon)), -_this.learningRate), value);
              value.assign(newValue);
            });
            _this.accBeta1.assign(mul(_this.accBeta1, _this.beta1));
            _this.accBeta2.assign(mul(_this.accBeta2, _this.beta2));
          });
          this.incrementIterations();
        };
        AdamOptimizer2.prototype.dispose = function() {
          this.accBeta1.dispose();
          this.accBeta2.dispose();
          if (this.accumulatedFirstMoment != null) {
            dispose(this.accumulatedFirstMoment.map(function(v) {
              return v.variable;
            }));
          }
          if (this.accumulatedSecondMoment != null) {
            dispose(this.accumulatedSecondMoment.map(function(v) {
              return v.variable;
            }));
          }
        };
        AdamOptimizer2.prototype.getWeights = function() {
          return __awaiter(this, void 0, void 0, function() {
            var variables;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  variables = __spreadArray(__spreadArray([], __read(this.accumulatedFirstMoment), false), __read(this.accumulatedSecondMoment), false);
                  return [4, this.saveIterations()];
                case 1:
                  return [2, [_a.sent()].concat(variables.map(function(v) {
                    return { name: v.originalName, tensor: v.variable };
                  }))];
              }
            });
          });
        };
        AdamOptimizer2.prototype.setWeights = function(weightValues) {
          return __awaiter(this, void 0, void 0, function() {
            var variableCount, trainable;
            var _this = this;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.extractIterations(weightValues)];
                case 1:
                  weightValues = _a.sent();
                  tidy(function() {
                    _this.accBeta1.assign(pow(_this.beta1, _this.iterations_ + 1));
                    _this.accBeta2.assign(pow(_this.beta2, _this.iterations_ + 1));
                  });
                  variableCount = weightValues.length / 2;
                  trainable = false;
                  this.accumulatedFirstMoment = weightValues.slice(0, variableCount).map(function(v) {
                    return {
                      originalName: v.name,
                      variable: v.tensor.variable(trainable)
                    };
                  });
                  this.accumulatedSecondMoment = weightValues.slice(variableCount, variableCount * 2).map(function(v) {
                    return {
                      originalName: v.name,
                      variable: v.tensor.variable(trainable)
                    };
                  });
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        AdamOptimizer2.prototype.getConfig = function() {
          return {
            "learningRate": this.learningRate,
            "beta1": this.beta1,
            "beta2": this.beta2,
            "epsilon": this.epsilon
          };
        };
        AdamOptimizer2.fromConfig = function(cls, config) {
          return new cls(config["learningRate"], config["beta1"], config["beta2"], config["epsilon"]);
        };
        return AdamOptimizer2;
      }(Optimizer)
    );
    var AdamaxOptimizer = (
      /** @class */
      function(_super) {
        __extends(AdamaxOptimizer2, _super);
        function AdamaxOptimizer2(learningRate, beta1, beta2, epsilon, decay) {
          if (epsilon === void 0) {
            epsilon = null;
          }
          if (decay === void 0) {
            decay = 0;
          }
          var _this = _super.call(this) || this;
          _this.learningRate = learningRate;
          _this.beta1 = beta1;
          _this.beta2 = beta2;
          _this.epsilon = epsilon;
          _this.decay = decay;
          _this.accumulatedFirstMoment = [];
          _this.accumulatedWeightedInfNorm = [];
          tidy(function() {
            _this.iteration = scalar(0).variable();
            _this.accBeta1 = scalar(beta1).variable();
          });
          if (epsilon == null) {
            _this.epsilon = ENGINE.backend.epsilon();
          }
          return _this;
        }
        Object.defineProperty(AdamaxOptimizer2, "className", {
          /** @nocollapse */
          get: function() {
            return "Adamax";
          },
          enumerable: false,
          configurable: true
        });
        AdamaxOptimizer2.prototype.applyGradients = function(variableGradients) {
          var _this = this;
          var variableNames = Array.isArray(variableGradients) ? variableGradients.map(function(item) {
            return item.name;
          }) : Object.keys(variableGradients);
          tidy(function() {
            var oneMinusAccBeta1 = sub(1, _this.accBeta1);
            var lr = div(-_this.learningRate, add(mul(_this.iteration, _this.decay), 1));
            variableNames.forEach(function(name, i) {
              var value = ENGINE.registeredVariables[name];
              var trainable = false;
              if (_this.accumulatedFirstMoment[i] == null) {
                _this.accumulatedFirstMoment[i] = {
                  originalName: "".concat(name, "/m"),
                  variable: zerosLike(value).variable(trainable)
                };
              }
              if (_this.accumulatedWeightedInfNorm[i] == null) {
                _this.accumulatedWeightedInfNorm[i] = {
                  originalName: "".concat(name, "/v"),
                  variable: zerosLike(value).variable(trainable)
                };
              }
              var gradient = Array.isArray(variableGradients) ? variableGradients[i].tensor : variableGradients[name];
              if (gradient == null) {
                return;
              }
              var firstMoment = _this.accumulatedFirstMoment[i].variable;
              var weightedInfNorm = _this.accumulatedWeightedInfNorm[i].variable;
              var newFirstMoment = add(mul(firstMoment, _this.beta1), mul(gradient, 1 - _this.beta1));
              var ut0 = mul(weightedInfNorm, _this.beta2);
              var ut1 = abs(gradient);
              var newWeightedInfNorm = maximum(ut0, ut1);
              firstMoment.assign(newFirstMoment);
              weightedInfNorm.assign(newWeightedInfNorm);
              var newValue = add(mul(div(lr, oneMinusAccBeta1), div(newFirstMoment, add(newWeightedInfNorm, _this.epsilon))), value);
              value.assign(newValue);
            });
            _this.iteration.assign(add(_this.iteration, 1));
            _this.accBeta1.assign(mul(_this.accBeta1, _this.beta1));
          });
          this.incrementIterations();
        };
        AdamaxOptimizer2.prototype.dispose = function() {
          this.accBeta1.dispose();
          this.iteration.dispose();
          if (this.accumulatedFirstMoment != null) {
            dispose(this.accumulatedFirstMoment.map(function(v) {
              return v.variable;
            }));
          }
          if (this.accumulatedWeightedInfNorm != null) {
            dispose(this.accumulatedWeightedInfNorm.map(function(v) {
              return v.variable;
            }));
          }
        };
        AdamaxOptimizer2.prototype.getWeights = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              throw new Error("getWeights() is not implemented for Adamax yet.");
            });
          });
        };
        AdamaxOptimizer2.prototype.setWeights = function(weightValues) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              throw new Error("setWeights() is not implemented for Adamax yet.");
            });
          });
        };
        AdamaxOptimizer2.prototype.getConfig = function() {
          return {
            "learningRate": this.learningRate,
            "beta1": this.beta1,
            "beta2": this.beta2,
            "epsilon": this.epsilon,
            "decay": this.decay
          };
        };
        AdamaxOptimizer2.fromConfig = function(cls, config) {
          return new cls(config["learningRate"], config["beta1"], config["beta2"], config["epsilon"], config["decay"]);
        };
        return AdamaxOptimizer2;
      }(Optimizer)
    );
    var SGDOptimizer = (
      /** @class */
      function(_super) {
        __extends(SGDOptimizer2, _super);
        function SGDOptimizer2(learningRate) {
          var _this = _super.call(this) || this;
          _this.learningRate = learningRate;
          _this.setLearningRate(learningRate);
          return _this;
        }
        Object.defineProperty(SGDOptimizer2, "className", {
          /** @nocollapse */
          get: function() {
            return "SGD";
          },
          enumerable: false,
          configurable: true
        });
        SGDOptimizer2.prototype.applyGradients = function(variableGradients) {
          var _this = this;
          var varNames = Array.isArray(variableGradients) ? variableGradients.map(function(v) {
            return v.name;
          }) : Object.keys(variableGradients);
          varNames.forEach(function(name, i) {
            var gradient = Array.isArray(variableGradients) ? variableGradients[i].tensor : variableGradients[name];
            if (gradient == null) {
              return;
            }
            var value = ENGINE.registeredVariables[name];
            tidy(function() {
              var newValue = add(mul(_this.c, gradient), value);
              value.assign(newValue);
            });
          });
          this.incrementIterations();
        };
        SGDOptimizer2.prototype.setLearningRate = function(learningRate) {
          this.learningRate = learningRate;
          if (this.c != null) {
            this.c.dispose();
          }
          this.c = keep(scalar(-learningRate));
        };
        SGDOptimizer2.prototype.dispose = function() {
          this.c.dispose();
        };
        SGDOptimizer2.prototype.getWeights = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.saveIterations()];
                case 1:
                  return [2, [_a.sent()]];
              }
            });
          });
        };
        SGDOptimizer2.prototype.setWeights = function(weightValues) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.extractIterations(weightValues)];
                case 1:
                  weightValues = _a.sent();
                  if (weightValues.length !== 0) {
                    throw new Error("SGD optimizer does not have settable weights.");
                  }
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        SGDOptimizer2.prototype.getConfig = function() {
          return { "learningRate": this.learningRate };
        };
        SGDOptimizer2.fromConfig = function(cls, config) {
          return new cls(config["learningRate"]);
        };
        return SGDOptimizer2;
      }(Optimizer)
    );
    var MomentumOptimizer = (
      /** @class */
      function(_super) {
        __extends(MomentumOptimizer2, _super);
        function MomentumOptimizer2(learningRate, momentum, useNesterov) {
          if (useNesterov === void 0) {
            useNesterov = false;
          }
          var _this = _super.call(this, learningRate) || this;
          _this.learningRate = learningRate;
          _this.momentum = momentum;
          _this.useNesterov = useNesterov;
          _this.accumulations = [];
          _this.m = scalar(_this.momentum);
          return _this;
        }
        Object.defineProperty(MomentumOptimizer2, "className", {
          /** @nocollapse */
          // Name matters for Python compatibility.
          get: function() {
            return "Momentum";
          },
          enumerable: false,
          configurable: true
        });
        MomentumOptimizer2.prototype.applyGradients = function(variableGradients) {
          var _this = this;
          var variableNames = Array.isArray(variableGradients) ? variableGradients.map(function(item) {
            return item.name;
          }) : Object.keys(variableGradients);
          variableNames.forEach(function(name, i) {
            var value = ENGINE.registeredVariables[name];
            if (_this.accumulations[i] == null) {
              var trainable_1 = false;
              _this.accumulations[i] = {
                originalName: "".concat(name, "/momentum"),
                variable: tidy(function() {
                  return zerosLike(value).variable(trainable_1);
                })
              };
            }
            var accumulation = _this.accumulations[i].variable;
            var gradient = Array.isArray(variableGradients) ? variableGradients[i].tensor : variableGradients[name];
            if (gradient == null) {
              return;
            }
            tidy(function() {
              var newValue;
              var newAccumulation = add(mul(_this.m, accumulation), gradient);
              if (_this.useNesterov) {
                newValue = add(mul(_this.c, add(gradient, mul(newAccumulation, _this.m))), value);
              } else {
                newValue = add(mul(_this.c, newAccumulation), value);
              }
              accumulation.assign(newAccumulation);
              value.assign(newValue);
            });
          });
          this.incrementIterations();
        };
        MomentumOptimizer2.prototype.dispose = function() {
          this.m.dispose();
          if (this.accumulations != null) {
            dispose(this.accumulations.map(function(v) {
              return v.variable;
            }));
          }
        };
        MomentumOptimizer2.prototype.setMomentum = function(momentum) {
          this.momentum = momentum;
        };
        MomentumOptimizer2.prototype.getWeights = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.saveIterations()];
                case 1:
                  return [2, [_a.sent()].concat(this.accumulations.map(function(v) {
                    return { name: v.originalName, tensor: v.variable };
                  }))];
              }
            });
          });
        };
        MomentumOptimizer2.prototype.setWeights = function(weightValues) {
          return __awaiter(this, void 0, void 0, function() {
            var trainable;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.extractIterations(weightValues)];
                case 1:
                  weightValues = _a.sent();
                  trainable = false;
                  this.accumulations = weightValues.map(function(v) {
                    return { originalName: v.name, variable: v.tensor.variable(trainable) };
                  });
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        MomentumOptimizer2.prototype.getConfig = function() {
          return {
            "learningRate": this.learningRate,
            "momentum": this.momentum,
            "useNesterov": this.useNesterov
          };
        };
        MomentumOptimizer2.fromConfig = function(cls, config) {
          return new cls(config["learningRate"], config["momentum"], config["useNesterov"]);
        };
        return MomentumOptimizer2;
      }(SGDOptimizer)
    );
    var RMSPropOptimizer = (
      /** @class */
      function(_super) {
        __extends(RMSPropOptimizer2, _super);
        function RMSPropOptimizer2(learningRate, decay, momentum, epsilon, centered) {
          if (decay === void 0) {
            decay = 0.9;
          }
          if (momentum === void 0) {
            momentum = 0;
          }
          if (epsilon === void 0) {
            epsilon = null;
          }
          if (centered === void 0) {
            centered = false;
          }
          var _this = _super.call(this) || this;
          _this.learningRate = learningRate;
          _this.decay = decay;
          _this.momentum = momentum;
          _this.epsilon = epsilon;
          _this.accumulatedMeanSquares = [];
          _this.accumulatedMoments = [];
          _this.accumulatedMeanGrads = [];
          _this.centered = centered;
          if (epsilon == null) {
            _this.epsilon = ENGINE.backend.epsilon();
          }
          if (learningRate == null) {
            throw new Error("learningRate for RMSPropOptimizer must be defined.");
          }
          return _this;
        }
        Object.defineProperty(RMSPropOptimizer2, "className", {
          /** @nocollapse */
          get: function() {
            return "RMSProp";
          },
          enumerable: false,
          configurable: true
        });
        RMSPropOptimizer2.prototype.applyGradients = function(variableGradients) {
          var _this = this;
          var variableNames = Array.isArray(variableGradients) ? variableGradients.map(function(item) {
            return item.name;
          }) : Object.keys(variableGradients);
          variableNames.forEach(function(name, i) {
            var value = ENGINE.registeredVariables[name];
            var trainable = false;
            if (_this.accumulatedMeanSquares[i] == null) {
              _this.accumulatedMeanSquares[i] = {
                originalName: "".concat(name, "/rms"),
                variable: tidy(function() {
                  return zerosLike(value).variable(trainable);
                })
              };
            }
            if (_this.accumulatedMoments[i] == null) {
              _this.accumulatedMoments[i] = {
                originalName: "".concat(name, "/momentum"),
                variable: tidy(function() {
                  return zerosLike(value).variable(trainable);
                })
              };
            }
            if (_this.accumulatedMeanGrads[i] == null && _this.centered) {
              _this.accumulatedMeanGrads[i] = {
                originalName: "".concat(name, "/mg"),
                variable: tidy(function() {
                  return zerosLike(value).variable(trainable);
                })
              };
            }
            var gradient = Array.isArray(variableGradients) ? variableGradients[i].tensor : variableGradients[name];
            if (gradient == null) {
              return;
            }
            var accumulatedMeanSquare = _this.accumulatedMeanSquares[i].variable;
            var accumulatedMoments = _this.accumulatedMoments[i].variable;
            tidy(function() {
              var newAccumulatedMeanSquare = add(mul(accumulatedMeanSquare, _this.decay), mul(square(gradient), 1 - _this.decay));
              if (_this.centered) {
                var accumulatedMeanGrad = _this.accumulatedMeanGrads[i].variable;
                var newAccumulatedMeanGrad = add(mul(accumulatedMeanGrad, _this.decay), mul(gradient, 1 - _this.decay));
                var gradContribution = div(mul(gradient, _this.learningRate), sqrt(sub(newAccumulatedMeanSquare, add(square(newAccumulatedMeanGrad), _this.epsilon))));
                var newAccumulatedMoments = add(mul(accumulatedMoments, _this.momentum), gradContribution);
                accumulatedMeanSquare.assign(newAccumulatedMeanSquare);
                accumulatedMeanGrad.assign(newAccumulatedMeanGrad);
                accumulatedMoments.assign(newAccumulatedMoments);
                var newValue = sub(value, newAccumulatedMoments);
                value.assign(newValue);
              } else {
                var newAccumulatedMeanSquare_1 = add(mul(accumulatedMeanSquare, _this.decay), mul(square(gradient), 1 - _this.decay));
                var newAccumulatedMoments = add(mul(accumulatedMoments, _this.momentum), div(mul(gradient, _this.learningRate), sqrt(add(newAccumulatedMeanSquare_1, _this.epsilon))));
                accumulatedMeanSquare.assign(newAccumulatedMeanSquare_1);
                accumulatedMoments.assign(newAccumulatedMoments);
                var newValue = sub(value, newAccumulatedMoments);
                value.assign(newValue);
              }
            });
          });
          this.incrementIterations();
        };
        RMSPropOptimizer2.prototype.dispose = function() {
          if (this.accumulatedMeanSquares != null) {
            dispose(this.accumulatedMeanSquares.map(function(v) {
              return v.variable;
            }));
          }
          if (this.accumulatedMeanGrads != null && this.centered) {
            dispose(this.accumulatedMeanGrads.map(function(v) {
              return v.variable;
            }));
          }
          if (this.accumulatedMoments != null) {
            dispose(this.accumulatedMoments.map(function(v) {
              return v.variable;
            }));
          }
        };
        RMSPropOptimizer2.prototype.getWeights = function() {
          return __awaiter(this, void 0, void 0, function() {
            var variables;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  variables = __spreadArray(__spreadArray([], __read(this.accumulatedMeanSquares), false), __read(this.accumulatedMoments), false);
                  if (this.centered) {
                    variables.push.apply(variables, __spreadArray([], __read(this.accumulatedMeanGrads), false));
                  }
                  return [4, this.saveIterations()];
                case 1:
                  return [2, [_a.sent()].concat(variables.map(function(v) {
                    return { name: v.originalName, tensor: v.variable };
                  }))];
              }
            });
          });
        };
        RMSPropOptimizer2.prototype.setWeights = function(weightValues) {
          return __awaiter(this, void 0, void 0, function() {
            var variableCount, trainable;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.extractIterations(weightValues)];
                case 1:
                  weightValues = _a.sent();
                  variableCount = this.centered ? weightValues.length / 3 : weightValues.length / 2;
                  trainable = false;
                  this.accumulatedMeanSquares = weightValues.slice(0, variableCount).map(function(v) {
                    return {
                      originalName: v.name,
                      variable: v.tensor.variable(trainable)
                    };
                  });
                  this.accumulatedMoments = weightValues.slice(variableCount, variableCount * 2).map(function(v) {
                    return {
                      originalName: v.name,
                      variable: v.tensor.variable(trainable)
                    };
                  });
                  if (this.centered) {
                    this.accumulatedMeanGrads = weightValues.slice(variableCount * 2, variableCount * 3).map(function(v) {
                      return {
                        originalName: v.name,
                        variable: v.tensor.variable(trainable)
                      };
                    });
                  }
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        RMSPropOptimizer2.prototype.getConfig = function() {
          return {
            "learningRate": this.learningRate,
            "decay": this.decay,
            "momentum": this.momentum,
            "epsilon": this.epsilon,
            "centered": this.centered
          };
        };
        RMSPropOptimizer2.fromConfig = function(cls, config) {
          return new cls(config["learningRate"], config["decay"], config["momentum"], config["epsilon"], config["centered"]);
        };
        return RMSPropOptimizer2;
      }(Optimizer)
    );
    var OPTIMIZERS = [
      AdadeltaOptimizer,
      AdagradOptimizer,
      AdamOptimizer,
      AdamaxOptimizer,
      MomentumOptimizer,
      RMSPropOptimizer,
      SGDOptimizer
    ];
    function registerOptimizers() {
      var e_1, _a;
      try {
        for (var OPTIMIZERS_1 = __values(OPTIMIZERS), OPTIMIZERS_1_1 = OPTIMIZERS_1.next(); !OPTIMIZERS_1_1.done; OPTIMIZERS_1_1 = OPTIMIZERS_1.next()) {
          var optimizer = OPTIMIZERS_1_1.value;
          registerClass(optimizer);
        }
      } catch (e_1_1) {
        e_1 = { error: e_1_1 };
      } finally {
        try {
          if (OPTIMIZERS_1_1 && !OPTIMIZERS_1_1.done && (_a = OPTIMIZERS_1.return)) _a.call(OPTIMIZERS_1);
        } finally {
          if (e_1) throw e_1.error;
        }
      }
    }
    var DEFAULT_FILE_NAME_PREFIX = "model";
    var DEFAULT_JSON_EXTENSION_NAME = ".json";
    var DEFAULT_WEIGHT_DATA_EXTENSION_NAME = ".weights.bin";
    function defer(f) {
      return new Promise(function(resolve) {
        return setTimeout(resolve);
      }).then(f);
    }
    var BrowserDownloads = (
      /** @class */
      function() {
        function BrowserDownloads2(fileNamePrefix) {
          if (!env().getBool("IS_BROWSER")) {
            throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");
          }
          if (fileNamePrefix.startsWith(BrowserDownloads2.URL_SCHEME)) {
            fileNamePrefix = fileNamePrefix.slice(BrowserDownloads2.URL_SCHEME.length);
          }
          if (fileNamePrefix == null || fileNamePrefix.length === 0) {
            fileNamePrefix = DEFAULT_FILE_NAME_PREFIX;
          }
          this.modelJsonFileName = fileNamePrefix + DEFAULT_JSON_EXTENSION_NAME;
          this.weightDataFileName = fileNamePrefix + DEFAULT_WEIGHT_DATA_EXTENSION_NAME;
        }
        BrowserDownloads2.prototype.save = function(modelArtifacts) {
          return __awaiter(this, void 0, void 0, function() {
            var weightBuffer, weightsURL, weightsManifest, modelJSON, modelJsonURL, jsonAnchor_1, weightDataAnchor_1;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  if (typeof document === "undefined") {
                    throw new Error("Browser downloads are not supported in this environment since `document` is not present");
                  }
                  weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);
                  weightsURL = window.URL.createObjectURL(new Blob([weightBuffer], { type: "application/octet-stream" }));
                  if (!(modelArtifacts.modelTopology instanceof ArrayBuffer)) return [3, 1];
                  throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");
                case 1:
                  weightsManifest = [{
                    paths: ["./" + this.weightDataFileName],
                    weights: modelArtifacts.weightSpecs
                  }];
                  modelJSON = getModelJSONForModelArtifacts(modelArtifacts, weightsManifest);
                  modelJsonURL = window.URL.createObjectURL(new Blob([JSON.stringify(modelJSON)], { type: "application/json" }));
                  jsonAnchor_1 = this.modelJsonAnchor == null ? document.createElement("a") : this.modelJsonAnchor;
                  jsonAnchor_1.download = this.modelJsonFileName;
                  jsonAnchor_1.href = modelJsonURL;
                  return [4, defer(function() {
                    return jsonAnchor_1.dispatchEvent(new MouseEvent("click"));
                  })];
                case 2:
                  _a.sent();
                  if (!(modelArtifacts.weightData != null)) return [3, 4];
                  weightDataAnchor_1 = this.weightDataAnchor == null ? document.createElement("a") : this.weightDataAnchor;
                  weightDataAnchor_1.download = this.weightDataFileName;
                  weightDataAnchor_1.href = weightsURL;
                  return [4, defer(function() {
                    return weightDataAnchor_1.dispatchEvent(new MouseEvent("click"));
                  })];
                case 3:
                  _a.sent();
                  _a.label = 4;
                case 4:
                  return [2, { modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts) }];
              }
            });
          });
        };
        return BrowserDownloads2;
      }()
    );
    BrowserDownloads.URL_SCHEME = "downloads://";
    var BrowserFiles = (
      /** @class */
      function() {
        function BrowserFiles2(files) {
          if (files == null || files.length < 1) {
            throw new Error("When calling browserFiles, at least 1 file is required, " + "but received ".concat(files));
          }
          this.jsonFile = files[0];
          this.weightsFiles = files.slice(1);
        }
        BrowserFiles2.prototype.load = function() {
          return __awaiter(this, void 0, void 0, function() {
            var _this = this;
            return __generator(this, function(_a) {
              return [2, new Promise(function(resolve, reject) {
                var jsonReader = new FileReader();
                jsonReader.onload = function(event) {
                  var modelJSON = JSON.parse(event.target.result);
                  var modelTopology = modelJSON.modelTopology;
                  if (modelTopology == null) {
                    reject(new Error("modelTopology field is missing from file ".concat(_this.jsonFile.name)));
                    return;
                  }
                  var weightsManifest = modelJSON.weightsManifest;
                  if (weightsManifest == null) {
                    reject(new Error("weightManifest field is missing from file ".concat(_this.jsonFile.name)));
                    return;
                  }
                  if (_this.weightsFiles.length === 0) {
                    resolve({ modelTopology });
                    return;
                  }
                  var modelArtifactsPromise = getModelArtifactsForJSON(modelJSON, function(weightsManifest2) {
                    return _this.loadWeights(weightsManifest2);
                  });
                  resolve(modelArtifactsPromise);
                };
                jsonReader.onerror = function(error) {
                  return reject("Failed to read model topology and weights manifest JSON " + "from file '".concat(_this.jsonFile.name, "'. BrowserFiles supports loading ") + "Keras-style tf.Model artifacts only.");
                };
                jsonReader.readAsText(_this.jsonFile);
              })];
            });
          });
        };
        BrowserFiles2.prototype.loadWeights = function(weightsManifest) {
          var e_1, _a;
          var _this = this;
          var weightSpecs = [];
          var paths = [];
          try {
            for (var weightsManifest_1 = __values(weightsManifest), weightsManifest_1_1 = weightsManifest_1.next(); !weightsManifest_1_1.done; weightsManifest_1_1 = weightsManifest_1.next()) {
              var entry = weightsManifest_1_1.value;
              weightSpecs.push.apply(weightSpecs, __spreadArray([], __read(entry.weights), false));
              paths.push.apply(paths, __spreadArray([], __read(entry.paths), false));
            }
          } catch (e_1_1) {
            e_1 = { error: e_1_1 };
          } finally {
            try {
              if (weightsManifest_1_1 && !weightsManifest_1_1.done && (_a = weightsManifest_1.return)) _a.call(weightsManifest_1);
            } finally {
              if (e_1) throw e_1.error;
            }
          }
          var pathToFile = this.checkManifestAndWeightFiles(weightsManifest);
          var promises = paths.map(function(path) {
            return _this.loadWeightsFile(path, pathToFile[path]);
          });
          return Promise.all(promises).then(function(buffers) {
            return [weightSpecs, buffers];
          });
        };
        BrowserFiles2.prototype.loadWeightsFile = function(path, file) {
          return new Promise(function(resolve, reject) {
            var weightFileReader = new FileReader();
            weightFileReader.onload = function(event) {
              var weightData = event.target.result;
              resolve(weightData);
            };
            weightFileReader.onerror = function(error) {
              return reject("Failed to weights data from file of path '".concat(path, "'."));
            };
            weightFileReader.readAsArrayBuffer(file);
          });
        };
        BrowserFiles2.prototype.checkManifestAndWeightFiles = function(manifest) {
          var e_2, _a;
          var _this = this;
          var basenames = [];
          var fileNames = this.weightsFiles.map(function(file) {
            return basename(file.name);
          });
          var pathToFile = {};
          try {
            for (var manifest_1 = __values(manifest), manifest_1_1 = manifest_1.next(); !manifest_1_1.done; manifest_1_1 = manifest_1.next()) {
              var group = manifest_1_1.value;
              group.paths.forEach(function(path) {
                var pathBasename = basename(path);
                if (basenames.indexOf(pathBasename) !== -1) {
                  throw new Error("Duplicate file basename found in weights manifest: " + "'".concat(pathBasename, "'"));
                }
                basenames.push(pathBasename);
                if (fileNames.indexOf(pathBasename) === -1) {
                  throw new Error("Weight file with basename '".concat(pathBasename, "' is not provided."));
                } else {
                  pathToFile[path] = _this.weightsFiles[fileNames.indexOf(pathBasename)];
                }
              });
            }
          } catch (e_2_1) {
            e_2 = { error: e_2_1 };
          } finally {
            try {
              if (manifest_1_1 && !manifest_1_1.done && (_a = manifest_1.return)) _a.call(manifest_1);
            } finally {
              if (e_2) throw e_2.error;
            }
          }
          if (basenames.length !== this.weightsFiles.length) {
            throw new Error("Mismatch in the number of files in weights manifest " + "(".concat(basenames.length, ") and the number of weight files provided ") + "(".concat(this.weightsFiles.length, ")."));
          }
          return pathToFile;
        };
        return BrowserFiles2;
      }()
    );
    var browserDownloadsRouter = function(url) {
      if (!env().getBool("IS_BROWSER")) {
        return null;
      } else {
        if (!Array.isArray(url) && url.startsWith(BrowserDownloads.URL_SCHEME)) {
          return browserDownloads(url.slice(BrowserDownloads.URL_SCHEME.length));
        } else {
          return null;
        }
      }
    };
    IORouterRegistry.registerSaveRouter(browserDownloadsRouter);
    function browserDownloads(fileNamePrefix) {
      if (fileNamePrefix === void 0) {
        fileNamePrefix = "model";
      }
      return new BrowserDownloads(fileNamePrefix);
    }
    function browserFiles(files) {
      return new BrowserFiles(files);
    }
    function monitorPromisesProgress(promises, onProgress, startFraction, endFraction) {
      checkPromises(promises);
      startFraction = startFraction == null ? 0 : startFraction;
      endFraction = endFraction == null ? 1 : endFraction;
      checkFraction(startFraction, endFraction);
      var resolvedPromise = 0;
      var registerMonitor = function(promise) {
        promise.then(function(value) {
          var fraction = startFraction + ++resolvedPromise / promises.length * (endFraction - startFraction);
          onProgress(fraction);
          return value;
        });
        return promise;
      };
      function checkPromises(promises2) {
        assert(promises2 != null && Array.isArray(promises2) && promises2.length > 0, function() {
          return "promises must be a none empty array";
        });
      }
      function checkFraction(startFraction2, endFraction2) {
        assert(startFraction2 >= 0 && startFraction2 <= 1, function() {
          return "Progress fraction must be in range [0, 1], but " + "got startFraction ".concat(startFraction2);
        });
        assert(endFraction2 >= 0 && endFraction2 <= 1, function() {
          return "Progress fraction must be in range [0, 1], but " + "got endFraction ".concat(endFraction2);
        });
        assert(endFraction2 >= startFraction2, function() {
          return "startFraction must be no more than endFraction, but " + "got startFraction ".concat(startFraction2, " and endFraction ") + "".concat(endFraction2);
        });
      }
      return Promise.all(promises.map(registerMonitor));
    }
    function loadWeightsAsArrayBuffer(fetchURLs, loadOptions) {
      return __awaiter(this, void 0, void 0, function() {
        var fetchFunc, requests, fetchStartFraction, fetchEndFraction, responses, _b, bufferPromises, bufferStartFraction, bufferEndFraction, buffers, _c;
        return __generator(this, function(_d) {
          switch (_d.label) {
            case 0:
              if (loadOptions == null) {
                loadOptions = {};
              }
              fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch : loadOptions.fetchFunc;
              requests = fetchURLs.map(function(fetchURL) {
                return fetchFunc(fetchURL, loadOptions.requestInit, { isBinary: true });
              });
              fetchStartFraction = 0;
              fetchEndFraction = 0.5;
              if (!(loadOptions.onProgress == null)) return [3, 2];
              return [4, Promise.all(requests)];
            case 1:
              _b = _d.sent();
              return [3, 4];
            case 2:
              return [4, monitorPromisesProgress(requests, loadOptions.onProgress, fetchStartFraction, fetchEndFraction)];
            case 3:
              _b = _d.sent();
              _d.label = 4;
            case 4:
              responses = _b;
              bufferPromises = responses.map(function(response) {
                return response.arrayBuffer();
              });
              bufferStartFraction = 0.5;
              bufferEndFraction = 1;
              if (!(loadOptions.onProgress == null)) return [3, 6];
              return [4, Promise.all(bufferPromises)];
            case 5:
              _c = _d.sent();
              return [3, 8];
            case 6:
              return [4, monitorPromisesProgress(bufferPromises, loadOptions.onProgress, bufferStartFraction, bufferEndFraction)];
            case 7:
              _c = _d.sent();
              _d.label = 8;
            case 8:
              buffers = _c;
              return [2, buffers];
          }
        });
      });
    }
    function streamWeights(fetchURLs, loadOptions) {
      var _this = this;
      var _a;
      var fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch : loadOptions.fetchFunc;
      var fetchIndex = 0;
      var chunkReader;
      (_a = loadOptions.onProgress) === null || _a === void 0 ? void 0 : _a.call(loadOptions, 0);
      return new ReadableStream({
        pull: function(controller) {
          return __awaiter(_this, void 0, void 0, function() {
            var _a2, body, _b, done, value;
            return __generator(this, function(_c) {
              switch (_c.label) {
                case 0:
                  if (!(fetchIndex < fetchURLs.length)) return [3, 4];
                  if (!!chunkReader) return [3, 2];
                  return [4, fetchFunc(fetchURLs[fetchIndex], loadOptions.requestInit, { isBinary: true })];
                case 1:
                  body = _c.sent().body;
                  chunkReader = body.getReader();
                  _c.label = 2;
                case 2:
                  return [4, chunkReader.read()];
                case 3:
                  _b = _c.sent(), done = _b.done, value = _b.value;
                  if (done) {
                    fetchIndex++;
                    chunkReader = void 0;
                    (_a2 = loadOptions.onProgress) === null || _a2 === void 0 ? void 0 : _a2.call(loadOptions, fetchIndex / fetchURLs.length);
                    return [3, 0];
                  }
                  controller.enqueue(value);
                  return [
                    2
                    /*return*/
                  ];
                case 4:
                  controller.close();
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        }
      });
    }
    function loadWeights(manifest, filePathPrefix, weightNames, requestInit) {
      if (filePathPrefix === void 0) {
        filePathPrefix = "";
      }
      return __awaiter(this, void 0, void 0, function() {
        var fetchWeights, loadWeights2;
        return __generator(this, function(_b) {
          fetchWeights = function(fetchUrls) {
            return loadWeightsAsArrayBuffer(fetchUrls, { requestInit });
          };
          loadWeights2 = weightsLoaderFactory(fetchWeights);
          return [2, loadWeights2(manifest, filePathPrefix, weightNames)];
        });
      });
    }
    function weightsLoaderFactory(fetchWeightsFunction) {
      var _this = this;
      return function(manifest, filePathPrefix, weightNames) {
        if (filePathPrefix === void 0) {
          filePathPrefix = "";
        }
        return __awaiter(_this, void 0, void 0, function() {
          var groupIndicesToFetchMap, groupWeightsToFetch, weightsFound, allManifestWeightNames, weightsNotFound, groupIndicesToFetch, fetchUrls, buffers, weightsTensorMap, bufferIndexOffset;
          return __generator(this, function(_b) {
            switch (_b.label) {
              case 0:
                groupIndicesToFetchMap = manifest.map(function() {
                  return false;
                });
                groupWeightsToFetch = {};
                weightsFound = weightNames != null ? weightNames.map(function() {
                  return false;
                }) : [];
                allManifestWeightNames = [];
                manifest.forEach(function(manifestGroupConfig, groupIndex) {
                  var groupOffset = 0;
                  manifestGroupConfig.weights.forEach(function(weightsEntry) {
                    var rawDtype = "quantization" in weightsEntry ? weightsEntry.quantization.dtype : weightsEntry.dtype;
                    var weightsBytes = DTYPE_VALUE_SIZE_MAP[rawDtype] * sizeFromShape(weightsEntry.shape);
                    var enqueueWeightsForFetchingFn = function() {
                      groupIndicesToFetchMap[groupIndex] = true;
                      if (groupWeightsToFetch[groupIndex] == null) {
                        groupWeightsToFetch[groupIndex] = [];
                      }
                      groupWeightsToFetch[groupIndex].push({
                        manifestEntry: weightsEntry,
                        groupOffset,
                        sizeBytes: weightsBytes
                      });
                    };
                    if (weightNames != null) {
                      weightNames.forEach(function(weightName, weightIndex) {
                        if (weightName === weightsEntry.name) {
                          enqueueWeightsForFetchingFn();
                          weightsFound[weightIndex] = true;
                        }
                      });
                    } else {
                      enqueueWeightsForFetchingFn();
                    }
                    allManifestWeightNames.push(weightsEntry.name);
                    groupOffset += weightsBytes;
                  });
                });
                if (!weightsFound.every(function(found) {
                  return found;
                })) {
                  weightsNotFound = weightNames.filter(function(_, i) {
                    return !weightsFound[i];
                  });
                  throw new Error("Could not find weights in manifest with names: " + "".concat(weightsNotFound.join(", "), ". \n") + "Manifest JSON has weights with names: " + "".concat(allManifestWeightNames.join(", "), "."));
                }
                groupIndicesToFetch = groupIndicesToFetchMap.reduce(function(accumulator, shouldFetch, i) {
                  if (shouldFetch) {
                    accumulator.push(i);
                  }
                  return accumulator;
                }, []);
                fetchUrls = [];
                groupIndicesToFetch.forEach(function(i) {
                  manifest[i].paths.forEach(function(filepath) {
                    var fetchUrl = filePathPrefix + (!filePathPrefix.endsWith("/") ? "/" : "") + filepath;
                    fetchUrls.push(fetchUrl);
                  });
                });
                return [4, fetchWeightsFunction(fetchUrls)];
              case 1:
                buffers = _b.sent();
                weightsTensorMap = {};
                bufferIndexOffset = 0;
                groupIndicesToFetch.forEach(function(i) {
                  var numBuffers = manifest[i].paths.length;
                  var weightsBuffer = new CompositeArrayBuffer(buffers.slice(bufferIndexOffset, bufferIndexOffset + numBuffers));
                  var weightsEntries = groupWeightsToFetch[i];
                  weightsEntries.forEach(function(weightsEntry) {
                    var byteBuffer = weightsBuffer.slice(weightsEntry.groupOffset, weightsEntry.groupOffset + weightsEntry.sizeBytes);
                    var nameToTensorMap = decodeWeights(byteBuffer, [weightsEntry.manifestEntry]);
                    for (var name in nameToTensorMap) {
                      weightsTensorMap[name] = nameToTensorMap[name];
                    }
                  });
                  bufferIndexOffset += numBuffers;
                });
                return [2, weightsTensorMap];
            }
          });
        });
      };
    }
    var OCTET_STREAM_MIME_TYPE = "application/octet-stream";
    var JSON_TYPE = "application/json";
    var HTTPRequest = (
      /** @class */
      function() {
        function HTTPRequest2(path, loadOptions) {
          this.DEFAULT_METHOD = "POST";
          if (loadOptions == null) {
            loadOptions = {};
          }
          this.weightPathPrefix = loadOptions.weightPathPrefix;
          this.weightUrlConverter = loadOptions.weightUrlConverter;
          if (loadOptions.fetchFunc != null) {
            assert(typeof loadOptions.fetchFunc === "function", function() {
              return "Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)";
            });
            this.fetch = loadOptions.fetchFunc;
          } else {
            this.fetch = env().platform.fetch;
          }
          assert(path != null && path.length > 0, function() {
            return "URL path for http must not be null, undefined or empty.";
          });
          if (Array.isArray(path)) {
            assert(path.length === 2, function() {
              return "URL paths for http must have a length of 2, " + "(actual length is ".concat(path.length, ").");
            });
          }
          this.path = path;
          if (loadOptions.requestInit != null && loadOptions.requestInit.body != null) {
            throw new Error("requestInit is expected to have no pre-existing body, but has one.");
          }
          this.requestInit = loadOptions.requestInit || {};
          this.loadOptions = loadOptions;
        }
        HTTPRequest2.prototype.save = function(modelArtifacts) {
          return __awaiter(this, void 0, void 0, function() {
            var init, weightsManifest, modelTopologyAndWeightManifest, weightBuffer, response;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
                    throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");
                  }
                  init = Object.assign({ method: this.DEFAULT_METHOD }, this.requestInit);
                  init.body = new FormData();
                  weightsManifest = [{
                    paths: ["./model.weights.bin"],
                    weights: modelArtifacts.weightSpecs
                  }];
                  modelTopologyAndWeightManifest = getModelJSONForModelArtifacts(modelArtifacts, weightsManifest);
                  init.body.append("model.json", new Blob([JSON.stringify(modelTopologyAndWeightManifest)], { type: JSON_TYPE }), "model.json");
                  if (modelArtifacts.weightData != null) {
                    weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);
                    init.body.append("model.weights.bin", new Blob([weightBuffer], { type: OCTET_STREAM_MIME_TYPE }), "model.weights.bin");
                  }
                  return [4, this.fetch(this.path, init)];
                case 1:
                  response = _a.sent();
                  if (response.ok) {
                    return [2, {
                      modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts),
                      responses: [response]
                    }];
                  } else {
                    throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status " + "".concat(response.status, "."));
                  }
              }
            });
          });
        };
        HTTPRequest2.prototype.loadModelJSON = function() {
          return __awaiter(this, void 0, void 0, function() {
            var modelConfigRequest, modelJSON, message, modelTopology, weightsManifest;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.fetch(this.path, this.requestInit)];
                case 1:
                  modelConfigRequest = _a.sent();
                  if (!modelConfigRequest.ok) {
                    throw new Error("Request to ".concat(this.path, " failed with status code ") + "".concat(modelConfigRequest.status, ". Please verify this URL points to ") + "the model JSON of the model to load.");
                  }
                  _a.label = 2;
                case 2:
                  _a.trys.push([2, 4, , 5]);
                  return [4, modelConfigRequest.json()];
                case 3:
                  modelJSON = _a.sent();
                  return [3, 5];
                case 4:
                  _a.sent();
                  message = "Failed to parse model JSON of response from ".concat(this.path, ".");
                  if (this.path.endsWith(".pb")) {
                    message += " 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.";
                  } else {
                    message += " Please make sure the server is serving valid JSON for this request.";
                  }
                  throw new Error(message);
                case 5:
                  modelTopology = modelJSON.modelTopology;
                  weightsManifest = modelJSON.weightsManifest;
                  if (modelTopology == null && weightsManifest == null) {
                    throw new Error("The JSON from HTTP path ".concat(this.path, " contains neither model ") + "topology or manifest for weights.");
                  }
                  return [2, modelJSON];
              }
            });
          });
        };
        HTTPRequest2.prototype.load = function() {
          return __awaiter(this, void 0, void 0, function() {
            var modelJSON;
            var _this = this;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  if (this.loadOptions.streamWeights) {
                    return [2, this.loadStream()];
                  }
                  return [4, this.loadModelJSON()];
                case 1:
                  modelJSON = _a.sent();
                  return [2, getModelArtifactsForJSON(modelJSON, function(weightsManifest) {
                    return _this.loadWeights(weightsManifest);
                  })];
              }
            });
          });
        };
        HTTPRequest2.prototype.loadStream = function() {
          return __awaiter(this, void 0, void 0, function() {
            var modelJSON, fetchURLs, weightSpecs, stream;
            var _this = this;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.loadModelJSON()];
                case 1:
                  modelJSON = _a.sent();
                  return [4, this.getWeightUrls(modelJSON.weightsManifest)];
                case 2:
                  fetchURLs = _a.sent();
                  weightSpecs = getWeightSpecs(modelJSON.weightsManifest);
                  stream = function() {
                    return streamWeights(fetchURLs, _this.loadOptions);
                  };
                  return [2, Object.assign(Object.assign({}, modelJSON), { weightSpecs, getWeightStream: stream })];
              }
            });
          });
        };
        HTTPRequest2.prototype.getWeightUrls = function(weightsManifest) {
          return __awaiter(this, void 0, void 0, function() {
            var weightPath, _a, prefix, suffix, pathPrefix, fetchURLs, urlPromises, weightsManifest_1, weightsManifest_1_1, weightsGroup, _b, _c, path, _d, _e, _f, _g;
            var e_2, _h, e_3, _j;
            return __generator(this, function(_k) {
              switch (_k.label) {
                case 0:
                  weightPath = Array.isArray(this.path) ? this.path[1] : this.path;
                  _a = __read(parseUrl(weightPath), 2), prefix = _a[0], suffix = _a[1];
                  pathPrefix = this.weightPathPrefix || prefix;
                  fetchURLs = [];
                  urlPromises = [];
                  try {
                    for (weightsManifest_1 = __values(weightsManifest), weightsManifest_1_1 = weightsManifest_1.next(); !weightsManifest_1_1.done; weightsManifest_1_1 = weightsManifest_1.next()) {
                      weightsGroup = weightsManifest_1_1.value;
                      try {
                        for (_b = (e_3 = void 0, __values(weightsGroup.paths)), _c = _b.next(); !_c.done; _c = _b.next()) {
                          path = _c.value;
                          if (this.weightUrlConverter != null) {
                            urlPromises.push(this.weightUrlConverter(path));
                          } else {
                            fetchURLs.push(pathPrefix + path + suffix);
                          }
                        }
                      } catch (e_3_1) {
                        e_3 = { error: e_3_1 };
                      } finally {
                        try {
                          if (_c && !_c.done && (_j = _b.return)) _j.call(_b);
                        } finally {
                          if (e_3) throw e_3.error;
                        }
                      }
                    }
                  } catch (e_2_1) {
                    e_2 = { error: e_2_1 };
                  } finally {
                    try {
                      if (weightsManifest_1_1 && !weightsManifest_1_1.done && (_h = weightsManifest_1.return)) _h.call(weightsManifest_1);
                    } finally {
                      if (e_2) throw e_2.error;
                    }
                  }
                  if (!this.weightUrlConverter) return [3, 2];
                  _e = (_d = fetchURLs.push).apply;
                  _f = [fetchURLs];
                  _g = [[]];
                  return [4, Promise.all(urlPromises)];
                case 1:
                  _e.apply(_d, _f.concat([__spreadArray.apply(void 0, _g.concat([__read.apply(void 0, [_k.sent()]), false]))]));
                  _k.label = 2;
                case 2:
                  return [2, fetchURLs];
              }
            });
          });
        };
        HTTPRequest2.prototype.loadWeights = function(weightsManifest) {
          return __awaiter(this, void 0, void 0, function() {
            var fetchURLs, weightSpecs, buffers;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.getWeightUrls(weightsManifest)];
                case 1:
                  fetchURLs = _a.sent();
                  weightSpecs = getWeightSpecs(weightsManifest);
                  return [4, loadWeightsAsArrayBuffer(fetchURLs, this.loadOptions)];
                case 2:
                  buffers = _a.sent();
                  return [2, [weightSpecs, buffers]];
              }
            });
          });
        };
        return HTTPRequest2;
      }()
    );
    HTTPRequest.URL_SCHEME_REGEX = /^https?:\/\//;
    function parseUrl(url) {
      var lastSlash = url.lastIndexOf("/");
      var lastSearchParam = url.lastIndexOf("?");
      var prefix = url.substring(0, lastSlash);
      var suffix = lastSearchParam > lastSlash ? url.substring(lastSearchParam) : "";
      return [prefix + "/", suffix];
    }
    function isHTTPScheme(url) {
      return url.match(HTTPRequest.URL_SCHEME_REGEX) != null;
    }
    var httpRouter = function(url, loadOptions) {
      if (typeof fetch === "undefined" && (loadOptions == null || loadOptions.fetchFunc == null)) {
        return null;
      } else {
        var isHTTP = true;
        if (Array.isArray(url)) {
          isHTTP = url.every(function(urlItem) {
            return isHTTPScheme(urlItem);
          });
        } else {
          isHTTP = isHTTPScheme(url);
        }
        if (isHTTP) {
          return http(url, loadOptions);
        }
      }
      return null;
    };
    IORouterRegistry.registerSaveRouter(httpRouter);
    IORouterRegistry.registerLoadRouter(httpRouter);
    function http(path, loadOptions) {
      return new HTTPRequest(path, loadOptions);
    }
    function browserHTTPRequest(path, loadOptions) {
      return http(path, loadOptions);
    }
    var PassthroughLoader = (
      /** @class */
      function() {
        function PassthroughLoader2(modelArtifacts) {
          this.modelArtifacts = modelArtifacts;
        }
        PassthroughLoader2.prototype.load = function() {
          return this.modelArtifacts;
        };
        return PassthroughLoader2;
      }()
    );
    var PassthroughSaver = (
      /** @class */
      function() {
        function PassthroughSaver2(saveHandler) {
          this.saveHandler = saveHandler;
        }
        PassthroughSaver2.prototype.save = function(modelArtifacts) {
          return this.saveHandler(modelArtifacts);
        };
        return PassthroughSaver2;
      }()
    );
    var PassthroughAsync = (
      /** @class */
      /* @__PURE__ */ function() {
        function PassthroughAsync2(handler) {
          if (handler.load) {
            this.load = function() {
              return Promise.resolve(handler.load());
            };
          }
          if (handler.save) {
            this.save = function(modelArtifacts) {
              return Promise.resolve(handler.save(modelArtifacts));
            };
          }
        }
        return PassthroughAsync2;
      }()
    );
    function fromMemory(modelArtifacts, weightSpecs, weightData, trainingConfig) {
      var args = arguments;
      return new PassthroughAsync(fromMemorySync.apply(void 0, __spreadArray([], __read(args), false)));
    }
    function fromMemorySync(modelArtifacts, weightSpecs, weightData, trainingConfig) {
      if (arguments.length === 1) {
        var isModelArtifacts = modelArtifacts.modelTopology != null || modelArtifacts.weightSpecs != null;
        if (isModelArtifacts) {
          return new PassthroughLoader(modelArtifacts);
        } else {
          console.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.");
          return new PassthroughLoader({ modelTopology: modelArtifacts });
        }
      } else {
        console.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.");
        return new PassthroughLoader({
          modelTopology: modelArtifacts,
          weightSpecs,
          weightData,
          trainingConfig
        });
      }
    }
    function withSaveHandler(saveHandler) {
      return new PassthroughSaver(saveHandler);
    }
    function withSaveHandlerSync(saveHandler) {
      return new PassthroughSaver(saveHandler);
    }
    var io = {
      __proto__: null,
      CompositeArrayBuffer,
      browserFiles,
      browserHTTPRequest,
      concatenateArrayBuffers,
      copyModel,
      decodeWeights,
      decodeWeightsStream,
      encodeWeights,
      fromMemory,
      fromMemorySync,
      getLoadHandlers,
      getModelArtifactsForJSON,
      getModelArtifactsForJSONSync,
      getModelArtifactsInfoForJSON,
      getSaveHandlers,
      getWeightSpecs,
      http,
      isHTTPScheme,
      listModels,
      loadWeights,
      moveModel,
      registerLoadRouter,
      registerSaveRouter,
      removeModel,
      weightsLoaderFactory,
      withSaveHandler,
      withSaveHandlerSync
    };
    function confusionMatrix_(labels, predictions, numClasses) {
      var $labels = convertToTensor(labels, "labels", "confusionMatrix");
      var $predictions = convertToTensor(predictions, "predictions", "confusionMatrix");
      assert(numClasses == null || numClasses > 0 && Number.isInteger(numClasses), function() {
        return "If provided, numClasses must be a positive integer, " + "but got ".concat(numClasses);
      });
      assert($labels.rank === 1, function() {
        return "Expected the rank of labels to be 1, but got ".concat($labels.rank);
      });
      assert($predictions.rank === 1, function() {
        return "Expected the rank of predictions to be 1, " + "but got ".concat($predictions.rank);
      });
      assert($labels.shape[0] === $predictions.shape[0], function() {
        return "Mismatch in the number of examples: " + "".concat($labels.shape[0], " vs. ").concat($predictions.shape[0], ". ") + "Labels and predictions should have the same number of elements.";
      });
      assert(numClasses > 0 && Number.isInteger(numClasses), function() {
        return "numClasses is required to be a positive integer, but got " + "".concat(numClasses);
      });
      var oneHotLabels = oneHot(cast($labels, "int32"), numClasses);
      var oneHotPredictions = oneHot(cast($predictions, "int32"), numClasses);
      var oneHotLabelsT = transpose(oneHotLabels);
      var product = matMul$1(oneHotLabelsT, oneHotPredictions);
      return cast(product, "int32");
    }
    var confusionMatrix = /* @__PURE__ */ op({ confusionMatrix_ });
    var math = {
      __proto__: null,
      confusionMatrix
    };
    var fromPixels2DContext;
    var hasToPixelsWarned = false;
    function fromPixels_(pixels, numChannels) {
      if (numChannels === void 0) {
        numChannels = 3;
      }
      if (numChannels > 4) {
        throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");
      }
      if (pixels == null) {
        throw new Error("pixels passed to tf.browser.fromPixels() can not be null");
      }
      var isPixelData2 = false;
      var isImageData = false;
      var isVideo = false;
      var isImage = false;
      var isCanvasLike = false;
      var isImageBitmap = false;
      if (pixels.data instanceof Uint8Array) {
        isPixelData2 = true;
      } else if (typeof ImageData !== "undefined" && pixels instanceof ImageData) {
        isImageData = true;
      } else if (typeof HTMLVideoElement !== "undefined" && pixels instanceof HTMLVideoElement) {
        isVideo = true;
      } else if (typeof HTMLImageElement !== "undefined" && pixels instanceof HTMLImageElement) {
        isImage = true;
      } else if (pixels.getContext != null) {
        isCanvasLike = true;
      } else if (typeof ImageBitmap !== "undefined" && pixels instanceof ImageBitmap) {
        isImageBitmap = true;
      } else {
        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 ".concat(pixels.constructor.name));
      }
      var kernel = getKernel(FromPixels, ENGINE.backendName);
      if (kernel != null) {
        var inputs = { pixels };
        var attrs = { numChannels };
        return ENGINE.runKernel(FromPixels, inputs, attrs);
      }
      var _a = __read(isVideo ? [
        pixels.videoWidth,
        pixels.videoHeight
      ] : [pixels.width, pixels.height], 2), width = _a[0], height = _a[1];
      var vals;
      if (isCanvasLike) {
        vals = // tslint:disable-next-line:no-any
        pixels.getContext("2d").getImageData(0, 0, width, height).data;
      } else if (isImageData || isPixelData2) {
        vals = pixels.data;
      } else if (isImage || isVideo || isImageBitmap) {
        if (fromPixels2DContext == null) {
          if (typeof document === "undefined") {
            if (typeof OffscreenCanvas !== "undefined" && typeof OffscreenCanvasRenderingContext2D !== "undefined") {
              fromPixels2DContext = new OffscreenCanvas(1, 1).getContext("2d");
            } else {
              throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");
            }
          } else {
            fromPixels2DContext = document.createElement("canvas").getContext("2d", { willReadFrequently: true });
          }
        }
        fromPixels2DContext.canvas.width = width;
        fromPixels2DContext.canvas.height = height;
        fromPixels2DContext.drawImage(pixels, 0, 0, width, height);
        vals = fromPixels2DContext.getImageData(0, 0, width, height).data;
      }
      var values;
      if (numChannels === 4) {
        values = new Int32Array(vals);
      } else {
        var numPixels = width * height;
        values = new Int32Array(numPixels * numChannels);
        for (var i = 0; i < numPixels; i++) {
          for (var channel = 0; channel < numChannels; ++channel) {
            values[i * numChannels + channel] = vals[i * 4 + channel];
          }
        }
      }
      var outShape = [height, width, numChannels];
      return tensor3d(values, outShape, "int32");
    }
    function isPixelData(pixels) {
      return pixels != null && pixels.data instanceof Uint8Array;
    }
    function isImageBitmapFullySupported() {
      return typeof window !== "undefined" && typeof ImageBitmap !== "undefined" && window.hasOwnProperty("createImageBitmap");
    }
    function isNonEmptyPixels(pixels) {
      return pixels != null && pixels.width !== 0 && pixels.height !== 0;
    }
    function canWrapPixelsToImageBitmap(pixels) {
      return isImageBitmapFullySupported() && !(pixels instanceof ImageBitmap) && isNonEmptyPixels(pixels) && !isPixelData(pixels);
    }
    function fromPixelsAsync(pixels, numChannels) {
      if (numChannels === void 0) {
        numChannels = 3;
      }
      return __awaiter(this, void 0, void 0, function() {
        var inputs, imageBitmap;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              inputs = null;
              if (!(env().getBool("WRAP_TO_IMAGEBITMAP") && canWrapPixelsToImageBitmap(pixels))) return [3, 5];
              imageBitmap = void 0;
              _a.label = 1;
            case 1:
              _a.trys.push([1, 3, , 4]);
              return [4, createImageBitmap(pixels, { premultiplyAlpha: "none" })];
            case 2:
              imageBitmap = _a.sent();
              return [3, 4];
            case 3:
              _a.sent();
              imageBitmap = null;
              return [3, 4];
            case 4:
              if (imageBitmap != null && imageBitmap.width === pixels.width && imageBitmap.height === pixels.height) {
                inputs = imageBitmap;
              } else {
                inputs = pixels;
              }
              return [3, 6];
            case 5:
              inputs = pixels;
              _a.label = 6;
            case 6:
              return [2, fromPixels_(inputs, numChannels)];
          }
        });
      });
    }
    function validateImgTensor(img) {
      if (img.rank !== 2 && img.rank !== 3) {
        throw new Error("toPixels only supports rank 2 or 3 tensors, got rank ".concat(img.rank, "."));
      }
      var depth = img.rank === 2 ? 1 : img.shape[2];
      if (depth > 4 || depth === 2) {
        throw new Error("toPixels only supports depth of size " + "1, 3 or 4 but got ".concat(depth));
      }
      if (img.dtype !== "float32" && img.dtype !== "int32") {
        throw new Error("Unsupported type for toPixels: ".concat(img.dtype, ".") + " Please use float32 or int32 tensors.");
      }
    }
    function validateImageOptions(imageOptions) {
      var alpha = (imageOptions === null || imageOptions === void 0 ? void 0 : imageOptions.alpha) || 1;
      if (alpha > 1 || alpha < 0) {
        throw new Error("Alpha value ".concat(alpha, " is suppoed to be in range [0 - 1]."));
      }
    }
    function toPixels(img, canvas) {
      return __awaiter(this, void 0, void 0, function() {
        var $img, originalImgTensor, _a, height, width, depth, data, multiplier, bytes, i, rgba, d, value, j, kernel, ctx, imageData;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              $img = convertToTensor(img, "img", "toPixels");
              if (!(img instanceof Tensor)) {
                originalImgTensor = $img;
                $img = cast(originalImgTensor, "int32");
                originalImgTensor.dispose();
              }
              validateImgTensor($img);
              _a = __read($img.shape.slice(0, 2), 2), height = _a[0], width = _a[1];
              depth = $img.rank === 2 ? 1 : $img.shape[2];
              return [4, $img.data()];
            case 1:
              data = _b.sent();
              multiplier = $img.dtype === "float32" ? 255 : 1;
              bytes = new Uint8ClampedArray(width * height * 4);
              for (i = 0; i < height * width; ++i) {
                rgba = [0, 0, 0, 255];
                for (d = 0; d < depth; d++) {
                  value = data[i * depth + d];
                  if ($img.dtype === "float32") {
                    if (value < 0 || value > 1) {
                      throw new Error("Tensor values for a float32 Tensor must be in the " + "range [0 - 1] but encountered ".concat(value, "."));
                    }
                  } else if ($img.dtype === "int32") {
                    if (value < 0 || value > 255) {
                      throw new Error("Tensor values for a int32 Tensor must be in the " + "range [0 - 255] but encountered ".concat(value, "."));
                    }
                  }
                  if (depth === 1) {
                    rgba[0] = value * multiplier;
                    rgba[1] = value * multiplier;
                    rgba[2] = value * multiplier;
                  } else {
                    rgba[d] = value * multiplier;
                  }
                }
                j = i * 4;
                bytes[j + 0] = Math.round(rgba[0]);
                bytes[j + 1] = Math.round(rgba[1]);
                bytes[j + 2] = Math.round(rgba[2]);
                bytes[j + 3] = Math.round(rgba[3]);
              }
              if (canvas != null) {
                if (!hasToPixelsWarned) {
                  kernel = getKernel(Draw, ENGINE.backendName);
                  if (kernel != null) {
                    console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead.");
                    hasToPixelsWarned = true;
                  }
                }
                canvas.width = width;
                canvas.height = height;
                ctx = canvas.getContext("2d");
                imageData = new ImageData(bytes, width, height);
                ctx.putImageData(imageData, 0, 0);
              }
              if ($img !== img) {
                $img.dispose();
              }
              return [2, bytes];
          }
        });
      });
    }
    function draw(image2, canvas, options) {
      var $img = convertToTensor(image2, "img", "draw");
      if (!(image2 instanceof Tensor)) {
        var originalImgTensor = $img;
        $img = cast(originalImgTensor, "int32");
        originalImgTensor.dispose();
      }
      validateImgTensor($img);
      validateImageOptions(options === null || options === void 0 ? void 0 : options.imageOptions);
      var inputs = { image: $img };
      var attrs = { canvas, options };
      ENGINE.runKernel(Draw, inputs, attrs);
    }
    var fromPixels = /* @__PURE__ */ op({ fromPixels_ });
    var browser = {
      __proto__: null,
      draw,
      fromPixels,
      fromPixelsAsync,
      toPixels
    };
    function prepareAndValidate(tensor2, indices) {
      var tensorRank = tensor2.shape.length;
      var indicesRank = indices.shape.length;
      if (tensorRank < 1) {
        throw new Error("tf.gatherND() expects the input to be rank 1 or higher," + " but the rank was ".concat(tensorRank, "."));
      }
      if (indicesRank < 1) {
        throw new Error("tf.gatherND() expects the indices to be rank 1 or higher," + " but the rank was ".concat(indicesRank, "."));
      }
      if (indices.dtype !== "int32") {
        throw new Error("tf.gatherND() expects the indices to be int32 type," + " but the dtype was ".concat(indices.dtype, "."));
      }
      if (indices.shape[indicesRank - 1] > tensorRank) {
        throw new Error("index innermost dimension length must be <= tensor rank; saw: " + "".concat(indices.shape[indicesRank - 1], " vs. ").concat(tensorRank));
      }
      if (sizeFromShape(tensor2.shape) === 0) {
        throw new Error("Requested more than 0 entries, but input is empty." + " Input shape: ".concat(tensor2.shape, "."));
      }
      var indicesShape = indices.shape;
      var sliceRank = indicesShape[indicesShape.length - 1];
      var nResult = 1;
      for (var i = 0; i < indicesShape.length - 1; ++i) {
        nResult *= indicesShape[i];
      }
      var inputShape = tensor2.shape;
      var resultShape = indicesShape.slice();
      resultShape.pop();
      var sliceSize = 1;
      for (var i = sliceRank; i < tensorRank; ++i) {
        sliceSize *= inputShape[i];
        resultShape.push(inputShape[i]);
      }
      var strides = __spreadArray(__spreadArray([], __read(computeStrides(tensor2.shape).map(function(stride) {
        return stride / sliceSize;
      })), false), [1], false).slice(0, sliceRank);
      return [resultShape, nResult, sliceSize, strides];
    }
    var gather_nd_util = {
      __proto__: null,
      prepareAndValidate
    };
    var NEW_AXIS = -2;
    var SHRINK_AXIS = -1;
    function assertParamsValid(input, begin, size) {
      var inputRank = input.shape.length;
      assert(inputRank === begin.length, function() {
        return "Error in slice".concat(inputRank, "D: Length of begin ").concat(begin, " must ") + "match the rank of the array (".concat(inputRank, ").");
      });
      assert(inputRank === size.length, function() {
        return "Error in slice".concat(inputRank, "D: Length of size ").concat(size, " must ") + "match the rank of the array (".concat(inputRank, ").");
      });
      var _loop_1 = function(i2) {
        assert(begin[i2] + size[i2] <= input.shape[i2], function() {
          return "Error in slice".concat(inputRank, "D: begin[").concat(i2, "] + size[").concat(i2, "] ") + "(".concat(begin[i2] + size[i2], ") would overflow input.shape[").concat(i2, "] (").concat(input.shape[i2], ")");
        });
      };
      for (var i = 0; i < inputRank; ++i) {
        _loop_1(i);
      }
    }
    function maskToAxes(mask) {
      var axes = [];
      var axis = 0;
      while (mask > 0) {
        if (mask & 1) {
          axes.push(axis);
        }
        mask /= 2;
        axis++;
      }
      return axes;
    }
    function computeOutShape$2(begin, end, strides) {
      var size = [];
      for (var axis = 0; axis < begin.length; axis++) {
        size[axis] = Math.ceil((end[axis] - begin[axis]) / strides[axis]);
      }
      return size;
    }
    function stridesWithElidedDims(strides, ellipsisInsertionIndex, numElidedAxes, inputShape) {
      var newStrides = __spreadArray([], __read(strides), false);
      for (var i = newStrides.length; i < inputShape.length; i++) {
        newStrides.push(1);
      }
      for (var i = 0; i < numElidedAxes; i++) {
        if (i === 0) {
          newStrides[ellipsisInsertionIndex] = 1;
        } else {
          newStrides.splice(
            ellipsisInsertionIndex,
            0,
            1
            /* element to add */
          );
          newStrides.pop();
        }
      }
      return newStrides;
    }
    function unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, normalizedAxis) {
      if (normalizedAxis <= ellipsisInsertionIndex) {
        return normalizedAxis;
      }
      return normalizedAxis - (numElidedAxes - 1);
    }
    function getElidedAxes(numElidedAxes, ellipsisInsertionIndex) {
      var elidedAxes = [];
      for (var i = 0; i < numElidedAxes; i++) {
        elidedAxes.push(ellipsisInsertionIndex + i);
      }
      return elidedAxes;
    }
    function getNormalizedAxes(inputShape, ellipsisAxes, numInterpolatedAxes, begin, end, strides, beginMask, endMask, ellipsisMask) {
      var inputRank = inputShape.length;
      var normalizedBegin = new Array(inputRank), normalizedEnd = new Array(inputRank), normalizedStrides = new Array(inputRank);
      if (ellipsisAxes.length && numInterpolatedAxes > 0) {
        var fullIndex = ellipsisAxes[0];
        var numElidedAxes = numInterpolatedAxes + 1;
        normalizedBegin = startIndicesWithElidedDims(beginMask, fullIndex, numElidedAxes, begin, inputShape);
        normalizedEnd = stopIndicesWithElidedDims(endMask, fullIndex, numElidedAxes, end, inputShape);
        normalizedStrides = stridesWithElidedDims(strides, fullIndex, numElidedAxes, inputShape);
      } else {
        for (var axis = 0; axis < inputRank; axis++) {
          normalizedBegin[axis] = startForAxis(beginMask, begin, strides, inputShape, axis, ellipsisMask);
          normalizedEnd[axis] = stopForAxis(endMask, end, strides, inputShape, axis, ellipsisMask);
          normalizedStrides[axis] = stridesForAxis(strides, axis, ellipsisMask);
        }
      }
      return {
        begin: normalizedBegin,
        end: normalizedEnd,
        strides: normalizedStrides
      };
    }
    function startIndicesWithElidedDims(beginMask, ellipsisInsertionIndex, numElidedAxes, originalBegin, inputShape) {
      var newIndices = __spreadArray([], __read(inputShape), false);
      var elidedAxes = getElidedAxes(numElidedAxes, ellipsisInsertionIndex);
      for (var axis = 0; axis < newIndices.length; axis++) {
        if (elidedAxes.indexOf(axis) > -1) {
          newIndices[axis] = 0;
        } else {
          var originalAxis = unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, axis);
          var originalValue = originalBegin[originalAxis];
          if (beginMask & 1 << originalAxis) {
            originalValue = 0;
          }
          newIndices[axis] = originalValue;
        }
      }
      return newIndices;
    }
    function stopIndicesWithElidedDims(endMask, ellipsisInsertionIndex, numElidedAxes, originalEnd, inputShape) {
      var newIndices = __spreadArray([], __read(inputShape), false);
      var elidedAxes = getElidedAxes(numElidedAxes, ellipsisInsertionIndex);
      for (var axis = 0; axis < newIndices.length; axis++) {
        if (elidedAxes.indexOf(axis) > -1) {
          newIndices[axis] = Number.MAX_SAFE_INTEGER;
        } else {
          var originalAxis = unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, axis);
          var originalValue = originalEnd[originalAxis];
          if (endMask & 1 << originalAxis) {
            originalValue = Number.MAX_SAFE_INTEGER;
          }
          newIndices[axis] = originalValue;
        }
      }
      for (var i = 0; i < newIndices.length; i++) {
        var axisSize = inputShape[i];
        if (newIndices[i] < 0) {
          newIndices[i] += axisSize;
        }
        newIndices[i] = clamp(0, newIndices[i], inputShape[i]);
      }
      return newIndices;
    }
    function stridesForAxis(strides, axis, ellipsisMask) {
      var stride = strides[axis];
      if (ellipsisMask & 1 << axis || stride == null) {
        stride = 1;
      }
      return stride;
    }
    function startForAxis(beginMask, startIndices, strides, inputShape, axis, ellipsisMask) {
      var start = startIndices[axis];
      var stride = strides[axis] || 1;
      if (beginMask & 1 << axis || ellipsisMask & 1 << axis || start == null) {
        if (stride > 0) {
          start = Number.MIN_SAFE_INTEGER;
        } else {
          start = Number.MAX_SAFE_INTEGER;
        }
      }
      var axisSize = inputShape[axis];
      if (start < 0) {
        start += axisSize;
      }
      start = clamp(0, start, axisSize - 1);
      return start;
    }
    function stopForAxis(endMask, stopIndices, strides, inputShape, axis, ellipsisMask) {
      var stop = stopIndices[axis];
      var stride = strides[axis] || 1;
      if (endMask & 1 << axis || ellipsisMask & 1 << axis || stop == null) {
        if (stride > 0) {
          stop = Number.MAX_SAFE_INTEGER;
        } else {
          stop = Number.MIN_SAFE_INTEGER;
        }
      }
      var axisSize = inputShape[axis];
      if (stop < 0) {
        stop += axisSize;
      }
      if (stride > 0) {
        stop = clamp(0, stop, axisSize);
      } else {
        stop = clamp(-1, stop, axisSize - 1);
      }
      return stop;
    }
    function isSliceContinous(shape, begin, size) {
      var firstNonOneAxis = size.length;
      for (var i = 0; i < size.length; i++) {
        if (size[i] > 1) {
          firstNonOneAxis = i;
          break;
        }
      }
      for (var i = firstNonOneAxis + 1; i < size.length; i++) {
        if (begin[i] > 0 || size[i] !== shape[i]) {
          return false;
        }
      }
      return true;
    }
    function computeFlatOffset(begin, strides) {
      var flatOffset = begin.length > 0 ? begin[begin.length - 1] : 1;
      for (var i = 0; i < begin.length - 1; i++) {
        flatOffset += begin[i] * strides[i];
      }
      return flatOffset;
    }
    function parseSliceParams(x, begin, size) {
      var begin_;
      var xRank = x.shape.length;
      if (typeof begin === "number") {
        begin_ = __spreadArray([begin], __read(new Array(xRank - 1).fill(0)), false);
      } else if (begin.length < xRank) {
        begin_ = begin.concat(new Array(xRank - begin.length).fill(0));
      } else {
        begin_ = begin.slice();
      }
      begin_.forEach(function(d) {
        assert(d !== -1, function() {
          return "slice() does not support negative begin indexing.";
        });
      });
      var size_;
      if (size == null) {
        size_ = new Array(xRank).fill(-1);
      } else if (typeof size === "number") {
        size_ = __spreadArray([size], __read(new Array(xRank - 1).fill(-1)), false);
      } else if (size.length < xRank) {
        size_ = size.concat(new Array(xRank - size.length).fill(-1));
      } else {
        size_ = size;
      }
      size_ = size_.map(function(d, i) {
        if (d >= 0) {
          return d;
        } else {
          assert(d === -1, function() {
            return "Negative size values should be exactly -1 but got " + "".concat(d, " for the slice() size at index ").concat(i, ".");
          });
          return x.shape[i] - begin_[i];
        }
      });
      return [begin_, size_];
    }
    function sliceInfo(xShape, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask) {
      var stridesNonNull;
      if (strides == null) {
        stridesNonNull = new Array(begin.length);
        stridesNonNull.fill(1);
      } else {
        stridesNonNull = strides;
      }
      if (ellipsisMask != null && (ellipsisMask & ellipsisMask - 1) !== 0) {
        throw new Error("Multiple ellipses in slice is not allowed.");
      }
      var ellipsisSeen = false;
      var sparseSpec = {
        dims: stridesNonNull.length,
        numAddAxisAfterEllipsis: 0,
        begin: begin.slice(),
        end: end.slice(),
        strides: stridesNonNull.slice(),
        beginMask,
        endMask,
        ellipsisMask,
        newAxisMask,
        shrinkAxisMask
      };
      for (var i = 0; i < sparseSpec.dims; i++) {
        if (ellipsisSeen && (1 << i & newAxisMask) !== 0) {
          sparseSpec.numAddAxisAfterEllipsis++;
        }
        if (1 << i & ellipsisMask) {
          ellipsisSeen = true;
        }
      }
      if (!ellipsisSeen) {
        sparseSpec.ellipsisMask |= 1 << sparseSpec.dims;
        sparseSpec.dims++;
      }
      var denseSpec = {
        dims: xShape.length,
        beginMask: 0,
        endMask: 0,
        beginValid: false,
        endValid: false
      };
      buildDenseSpec(sparseSpec, denseSpec);
      var isIdentity = true;
      var sliceDim0 = true;
      var isSimpleSlice = true;
      var processingShape = [];
      var finalShape = [];
      for (var i = 0; i < xShape.length; ++i) {
        if (denseSpec.strides[i] === 0) {
          throw Error("strides[".concat(i, "] must be non-zero"));
        }
        var shrinkI = !!(denseSpec.shrinkAxisMask & 1 << i);
        var dimI = xShape[i];
        if (dimI === -1) {
          processingShape.push(shrinkI ? 1 : -1);
          continue;
        }
        var masks = [denseSpec.beginMask & 1 << i, denseSpec.endMask & 1 << i];
        var validRange = [
          denseSpec.strides[i] > 0 ? 0 : -1,
          denseSpec.strides[i] > 0 ? dimI : dimI - 1
        ];
        if (shrinkI && denseSpec.strides[i] <= 0) {
          throw Error("only stride 1 allowed on non-range indexing.");
        }
        isSimpleSlice = isSimpleSlice && denseSpec.strides[i] === 1;
        var beginAndEndMasked = !!(denseSpec.beginMask & 1 << i && denseSpec.endMask & 1 << i);
        if (denseSpec.beginValid && denseSpec.endValid) {
          if (shrinkI) {
            var xFwd = denseSpec.begin[i] < 0 ? dimI + denseSpec.begin[i] : denseSpec.begin[i];
            denseSpec.begin[i] = xFwd;
            denseSpec.end[i] = denseSpec.begin[i] + 1;
            if (xFwd < 0 || xFwd >= dimI) {
              throw Error("slice index ".concat(denseSpec.begin[i], " of dimension ").concat(i, " out of bounds."));
            }
          } else {
            denseSpec.begin[i] = canonical(denseSpec.begin[i], 0, denseSpec.strides[i], dimI, masks, validRange);
            denseSpec.end[i] = canonical(denseSpec.end[i], 1, denseSpec.strides[i], dimI, masks, validRange);
          }
          var takeAllInDimension = denseSpec.strides[i] === 1 && denseSpec.begin[i] === 0 && denseSpec.end[i] === dimI;
          isIdentity = isIdentity && takeAllInDimension;
          sliceDim0 = sliceDim0 && (i === 0 && denseSpec.strides[i] === 1 || takeAllInDimension);
        } else {
          isIdentity = isIdentity && (denseSpec.strides[i] === 1 && beginAndEndMasked);
          sliceDim0 = sliceDim0 && (i === 0 && denseSpec.strides[i] === 1 || beginAndEndMasked);
        }
        var intervalLength = void 0;
        var knownInterval = false;
        if (denseSpec.beginValid && denseSpec.endValid) {
          intervalLength = denseSpec.end[i] - denseSpec.begin[i];
          knownInterval = true;
        } else if (shrinkI) {
          intervalLength = 1;
          knownInterval = true;
        } else if (beginAndEndMasked) {
          if (dimI >= 0) {
            if (denseSpec.strides[i] < 0) {
              intervalLength = -dimI;
            } else {
              intervalLength = dimI;
            }
            knownInterval = true;
          }
        }
        if (knownInterval) {
          var sizeI = void 0;
          if (intervalLength === 0 || intervalLength < 0 !== denseSpec.strides[i] < 0) {
            sizeI = 0;
          } else {
            sizeI = Math.trunc(intervalLength / denseSpec.strides[i]) + (intervalLength % denseSpec.strides[i] !== 0 ? 1 : 0);
          }
          processingShape.push(sizeI);
        } else {
          processingShape.push(-1);
        }
      }
      for (var denseDim = 0; denseDim < denseSpec.finalShapeGatherIndices.length; ++denseDim) {
        var gatherIndex = denseSpec.finalShapeGatherIndices[denseDim];
        if (gatherIndex >= 0) {
          finalShape.push(processingShape[gatherIndex]);
        } else if (gatherIndex === NEW_AXIS) {
          finalShape.push(1);
        }
      }
      var finalShapeSparse = finalShape.filter(function(dim, i2) {
        return denseSpec.finalShapeGatherIndices[i2] !== NEW_AXIS;
      });
      return {
        finalShapeSparse,
        finalShape,
        isIdentity,
        sliceDim0,
        isSimpleSlice,
        begin: denseSpec.begin,
        end: denseSpec.end,
        strides: denseSpec.strides
      };
    }
    function buildDenseSpec(sparse2, dense) {
      dense.beginMask = 0;
      dense.endMask = 0;
      dense.shrinkAxisMask = 0;
      var fullIndex = 0;
      dense.beginValid = sparse2.begin != null;
      dense.endValid = sparse2.end != null;
      dense.begin = new Array(dense.dims);
      dense.end = new Array(dense.dims);
      dense.strides = new Array(dense.dims);
      dense.finalShapeGatherIndices = [];
      dense.finalShapeGatherIndicesSparse = [];
      dense.inputShapeGatherIndicesSparse = new Array(dense.dims);
      for (var i = 0; i < sparse2.dims; i++) {
        if (1 << i & sparse2.ellipsisMask) {
          var nextIndex = Math.min(dense.dims - (sparse2.dims - i) + 1 + sparse2.numAddAxisAfterEllipsis, dense.dims);
          for (; fullIndex < nextIndex; fullIndex++) {
            dense.begin[fullIndex] = 0;
            dense.end[fullIndex] = 0;
            dense.strides[fullIndex] = 1;
            dense.beginMask |= 1 << fullIndex;
            dense.endMask |= 1 << fullIndex;
            dense.finalShapeGatherIndices.push(fullIndex);
            dense.finalShapeGatherIndicesSparse.push(-1);
            dense.inputShapeGatherIndicesSparse[fullIndex] = i;
          }
        } else if (1 << i & sparse2.newAxisMask) {
          dense.finalShapeGatherIndices.push(NEW_AXIS);
          dense.finalShapeGatherIndicesSparse.push(-1);
        } else {
          if (fullIndex === dense.begin.length) {
            throw Error("Index out of range using input dim ".concat(fullIndex, "; input ") + "has only ".concat(dense.dims, " dims, ").concat(dense.begin.length, "."));
          }
          if (sparse2.begin != null) {
            dense.begin[fullIndex] = sparse2.begin[i];
          }
          if (sparse2.end != null) {
            dense.end[fullIndex] = sparse2.end[i];
          }
          dense.strides[fullIndex] = sparse2.strides[i];
          if (sparse2.beginMask & 1 << i) {
            dense.beginMask |= 1 << fullIndex;
          }
          if (sparse2.endMask & 1 << i) {
            dense.endMask |= 1 << fullIndex;
          }
          if (sparse2.shrinkAxisMask & 1 << i) {
            dense.finalShapeGatherIndices.push(SHRINK_AXIS);
            dense.finalShapeGatherIndicesSparse.push(-1);
            dense.shrinkAxisMask |= 1 << fullIndex;
          } else {
            dense.finalShapeGatherIndices.push(fullIndex);
            dense.finalShapeGatherIndicesSparse.push(i);
          }
          dense.inputShapeGatherIndicesSparse[fullIndex] = i;
          fullIndex++;
        }
      }
    }
    function canonical(x, c, strideI, dimI, masks, validRange) {
      if (masks[c]) {
        return strideI > 0 ? validRange[c] : validRange[c + 1 & 1];
      } else {
        var xFwd = x < 0 ? dimI + x : x;
        return xFwd < validRange[0] ? validRange[0] : xFwd > validRange[1] ? validRange[1] : xFwd;
      }
    }
    var slice_util = {
      __proto__: null,
      assertParamsValid,
      computeFlatOffset,
      computeOutShape: computeOutShape$2,
      getNormalizedAxes,
      isSliceContinous,
      maskToAxes,
      parseSliceParams,
      sliceInfo,
      startForAxis,
      startIndicesWithElidedDims,
      stopForAxis,
      stopIndicesWithElidedDims,
      stridesForAxis,
      stridesWithElidedDims
    };
    var version = "4.22.0";
    var OptimizerConstructors = (
      /** @class */
      function() {
        function OptimizerConstructors2() {
        }
        OptimizerConstructors2.sgd = function(learningRate) {
          return new SGDOptimizer(learningRate);
        };
        OptimizerConstructors2.momentum = function(learningRate, momentum, useNesterov) {
          if (useNesterov === void 0) {
            useNesterov = false;
          }
          return new MomentumOptimizer(learningRate, momentum, useNesterov);
        };
        OptimizerConstructors2.rmsprop = function(learningRate, decay, momentum, epsilon, centered) {
          if (decay === void 0) {
            decay = 0.9;
          }
          if (momentum === void 0) {
            momentum = 0;
          }
          if (epsilon === void 0) {
            epsilon = null;
          }
          if (centered === void 0) {
            centered = false;
          }
          return new RMSPropOptimizer(learningRate, decay, momentum, epsilon, centered);
        };
        OptimizerConstructors2.adam = function(learningRate, beta1, beta2, epsilon) {
          if (learningRate === void 0) {
            learningRate = 1e-3;
          }
          if (beta1 === void 0) {
            beta1 = 0.9;
          }
          if (beta2 === void 0) {
            beta2 = 0.999;
          }
          if (epsilon === void 0) {
            epsilon = null;
          }
          return new AdamOptimizer(learningRate, beta1, beta2, epsilon);
        };
        OptimizerConstructors2.adadelta = function(learningRate, rho, epsilon) {
          if (learningRate === void 0) {
            learningRate = 1e-3;
          }
          if (rho === void 0) {
            rho = 0.95;
          }
          if (epsilon === void 0) {
            epsilon = null;
          }
          return new AdadeltaOptimizer(learningRate, rho, epsilon);
        };
        OptimizerConstructors2.adamax = function(learningRate, beta1, beta2, epsilon, decay) {
          if (learningRate === void 0) {
            learningRate = 2e-3;
          }
          if (beta1 === void 0) {
            beta1 = 0.9;
          }
          if (beta2 === void 0) {
            beta2 = 0.999;
          }
          if (epsilon === void 0) {
            epsilon = null;
          }
          if (decay === void 0) {
            decay = 0;
          }
          return new AdamaxOptimizer(learningRate, beta1, beta2, epsilon, decay);
        };
        OptimizerConstructors2.adagrad = function(learningRate, initialAccumulatorValue) {
          if (initialAccumulatorValue === void 0) {
            initialAccumulatorValue = 0.1;
          }
          return new AdagradOptimizer(learningRate, initialAccumulatorValue);
        };
        return OptimizerConstructors2;
      }()
    );
    var train = OptimizerConstructors;
    var delayCallback = function() {
      if (typeof requestAnimationFrame !== "undefined") {
        return requestAnimationFrame;
      } else if (typeof setImmediate !== "undefined") {
        return setImmediate;
      }
      return function(f) {
        return f();
      };
    }();
    function nextFrame() {
      return new Promise(function(resolve) {
        return delayCallback(function() {
          return resolve();
        });
      });
    }
    function assertParamsConsistent(shapes, axis) {
      var rank = shapes[0].length;
      shapes.forEach(function(shape, i) {
        assert(shape.length === rank, function() {
          return "Error in concat".concat(rank, "D: rank of tensors[").concat(i, "] must be the same ") + "as the rank of the rest (".concat(rank, ")");
        });
      });
      assert(axis >= 0 && axis < rank, function() {
        return "Error in concat".concat(rank, "D: axis must be between 0 and ").concat(rank - 1, ".");
      });
      var firstShape = shapes[0];
      shapes.forEach(function(shape, i) {
        for (var r = 0; r < rank; r++) {
          assert(r === axis || shape[r] === firstShape[r], function() {
            return "Error in concat".concat(rank, "D: Shape of tensors[").concat(i, "] (").concat(shape, ") ") + "does not match the shape of the rest (".concat(firstShape, ") ") + "along the non-concatenated axis ".concat(i, ".");
          });
        }
      });
    }
    function computeOutShape$1(shapes, axis) {
      var outputShape = shapes[0].slice();
      for (var i = 1; i < shapes.length; i++) {
        outputShape[axis] += shapes[i][axis];
      }
      return outputShape;
    }
    var RowPartitionType;
    (function(RowPartitionType2) {
      RowPartitionType2[RowPartitionType2["FIRST_DIM_SIZE"] = 0] = "FIRST_DIM_SIZE";
      RowPartitionType2[RowPartitionType2["VALUE_ROWIDS"] = 1] = "VALUE_ROWIDS";
      RowPartitionType2[RowPartitionType2["ROW_LENGTHS"] = 2] = "ROW_LENGTHS";
      RowPartitionType2[RowPartitionType2["ROW_SPLITS"] = 3] = "ROW_SPLITS";
      RowPartitionType2[RowPartitionType2["ROW_LIMITS"] = 4] = "ROW_LIMITS";
      RowPartitionType2[RowPartitionType2["ROW_STARTS"] = 5] = "ROW_STARTS";
    })(RowPartitionType || (RowPartitionType = {}));
    function combineRaggedTensorToTensorShapes(raggedRank, shape, valueShape) {
      var outputShape = new Array();
      if (valueShape == null && shape == null) {
        return outputShape;
      }
      if (shape == null) {
        while (outputShape.length < raggedRank + valueShape.length) {
          outputShape.push(-1);
        }
      } else {
        outputShape = shape.slice();
      }
      if (valueShape == null) {
        return outputShape;
      }
      if (raggedRank + valueShape.length !== outputShape.length) {
        throw new Error("rt input.shape and shape=".concat(shape, " are incompatible: rt input.rank = ").concat(raggedRank + valueShape.length, ", but shape.rank = ").concat(outputShape.length));
      }
      for (var i = 1; i < valueShape.length; ++i) {
        var valueDim = valueShape[i];
        var outputShapeDimIndex = outputShape[outputShape.length - valueShape.length + i];
        var outputShapeDim = outputShape[outputShapeDimIndex];
        if (valueDim >= 0) {
          if (outputShapeDim >= 0) {
            if (outputShapeDim !== valueDim) {
              throw new Error("rt input.shape and shape=".concat(shape, " are incompatible: rt input.shape[").concat(i + raggedRank, "] = ").concat(valueDim, " but shape[").concat(i + raggedRank, "] = ").concat(outputShapeDim));
            }
          } else {
            outputShape[outputShapeDimIndex] = valueDim;
          }
        }
      }
      return outputShape;
    }
    function getRowPartitionTypesHelper(rowPartitionTypeStrings) {
      var e_1, _a;
      var stringToType = {
        "FIRST_DIM_SIZE": RowPartitionType.FIRST_DIM_SIZE,
        "VALUE_ROWIDS": RowPartitionType.VALUE_ROWIDS,
        "ROW_LENGTHS": RowPartitionType.ROW_LENGTHS,
        "ROW_SPLITS": RowPartitionType.ROW_SPLITS,
        "ROW_LIMITS": RowPartitionType.ROW_LIMITS,
        "ROW_STARTS": RowPartitionType.ROW_STARTS
      };
      var result = [];
      try {
        for (var rowPartitionTypeStrings_1 = __values(rowPartitionTypeStrings), rowPartitionTypeStrings_1_1 = rowPartitionTypeStrings_1.next(); !rowPartitionTypeStrings_1_1.done; rowPartitionTypeStrings_1_1 = rowPartitionTypeStrings_1.next()) {
          var typeStr = rowPartitionTypeStrings_1_1.value;
          if (typeStr in stringToType) {
            result.push(stringToType[typeStr]);
          } else {
            break;
          }
        }
      } catch (e_1_1) {
        e_1 = { error: e_1_1 };
      } finally {
        try {
          if (rowPartitionTypeStrings_1_1 && !rowPartitionTypeStrings_1_1.done && (_a = rowPartitionTypeStrings_1.return)) _a.call(rowPartitionTypeStrings_1);
        } finally {
          if (e_1) throw e_1.error;
        }
      }
      return result;
    }
    function getRaggedRank(rowPartitionTypes) {
      if (rowPartitionTypes.length === 0) {
        return 0;
      }
      if (rowPartitionTypes[0] === RowPartitionType.FIRST_DIM_SIZE) {
        return rowPartitionTypes.length - 1;
      }
      return rowPartitionTypes.length;
    }
    function validateDefaultValueShape(defaultValueShape, valueShape) {
      if (defaultValueShape == null || valueShape == null) {
        return;
      }
      var defaultNDims = defaultValueShape.length;
      var valuesNDims = valueShape.length;
      if (defaultNDims >= valuesNDims) {
        throw new Error("defaultValue.shape=".concat(defaultValueShape, " and ragged tensor flatValues.shape=").concat(valueShape, ", are incompatible: defaultValue.rank = ").concat(defaultNDims, " must be less than ragged tensor input flatValues.rank = ").concat(valuesNDims, ")"));
      }
      for (var i = 0; i < Math.min(defaultNDims, valuesNDims - 1); ++i) {
        var defaultDim = defaultValueShape[i];
        var valueDim = valueShape[i + 1];
        if (defaultDim >= 0 && valueDim >= 0 && defaultDim !== 1 && defaultDim !== valueDim) {
          throw new Error("defaultValue.shape=".concat(defaultValueShape, ", and ragged tensor input flatValues.shape=").concat(valueShape, " are incompatible: defaultValue.shape[").concat(i - defaultValueShape.length, "] = ").concat(defaultDim, " but ragged tensor input.flatValues.shape[").concat(i - defaultValueShape.length, "] = ").concat(valueDim));
        }
      }
    }
    var PARALLELIZE_THRESHOLD = 30;
    function computeOptimalWindowSize(inSize) {
      if (inSize <= PARALLELIZE_THRESHOLD) {
        return inSize;
      }
      return nearestDivisor(inSize, Math.floor(Math.sqrt(inSize)));
    }
    function getImageCenter(center, imageHeight, imageWidth) {
      var centerX = imageWidth * (typeof center === "number" ? center : center[0]);
      var centerY = imageHeight * (typeof center === "number" ? center : center[1]);
      return [centerX, centerY];
    }
    function getReshaped(inputShape, blockShape, prod2, batchToSpace) {
      if (batchToSpace === void 0) {
        batchToSpace = true;
      }
      var reshaped = [];
      if (batchToSpace) {
        reshaped = reshaped.concat(blockShape.slice(0));
        reshaped.push(inputShape[0] / prod2);
        reshaped = reshaped.concat(inputShape.slice(1));
      } else {
        reshaped = reshaped.concat(inputShape[0]);
        var spatialLength = blockShape.length;
        for (var i = 0; i < spatialLength; ++i) {
          reshaped = reshaped.concat([inputShape[i + 1] / blockShape[i], blockShape[i]]);
        }
        reshaped = reshaped.concat(inputShape.slice(spatialLength + 1));
      }
      return reshaped;
    }
    function getPermuted(reshapedRank, blockShapeRank, batchToSpace) {
      if (batchToSpace === void 0) {
        batchToSpace = true;
      }
      var permuted = [];
      if (batchToSpace) {
        permuted.push(blockShapeRank);
        for (var i = blockShapeRank + 1; i < reshapedRank; ++i) {
          if (i <= 2 * blockShapeRank) {
            permuted.push(i);
            permuted.push(i - (blockShapeRank + 1));
          } else {
            permuted.push(i);
          }
        }
      } else {
        var permutedBeforeBatch = [];
        var permutedAfterBatch = [];
        for (var i = 1; i < reshapedRank; ++i) {
          if (i >= blockShapeRank * 2 + 1 || i % 2 === 1) {
            permutedAfterBatch.push(i);
          } else {
            permutedBeforeBatch.push(i);
          }
        }
        permuted.push.apply(permuted, __spreadArray([], __read(permutedBeforeBatch), false));
        permuted.push(0);
        permuted.push.apply(permuted, __spreadArray([], __read(permutedAfterBatch), false));
      }
      return permuted;
    }
    function getReshapedPermuted(inputShape, blockShape, prod2, batchToSpace) {
      if (batchToSpace === void 0) {
        batchToSpace = true;
      }
      var reshapedPermuted = [];
      if (batchToSpace) {
        reshapedPermuted.push(inputShape[0] / prod2);
      } else {
        reshapedPermuted.push(inputShape[0] * prod2);
      }
      for (var i = 1; i < inputShape.length; ++i) {
        if (i <= blockShape.length) {
          if (batchToSpace) {
            reshapedPermuted.push(blockShape[i - 1] * inputShape[i]);
          } else {
            reshapedPermuted.push(inputShape[i] / blockShape[i - 1]);
          }
        } else {
          reshapedPermuted.push(inputShape[i]);
        }
      }
      return reshapedPermuted;
    }
    function getSliceBeginCoords(crops, blockShape) {
      var sliceBeginCoords = [0];
      for (var i = 0; i < blockShape; ++i) {
        sliceBeginCoords.push(crops[i][0]);
      }
      return sliceBeginCoords;
    }
    function getSliceSize(uncroppedShape, crops, blockShape) {
      var sliceSize = uncroppedShape.slice(0, 1);
      for (var i = 0; i < blockShape; ++i) {
        sliceSize.push(uncroppedShape[i + 1] - crops[i][0] - crops[i][1]);
      }
      return sliceSize;
    }
    var SELU_SCALEALPHA = 1.7580993408473768;
    var SELU_SCALE = 1.0507009873554805;
    var ERF_P = 0.3275911;
    var ERF_A1 = 0.254829592;
    var ERF_A2 = -0.284496736;
    var ERF_A3 = 1.421413741;
    var ERF_A4 = -1.453152027;
    var ERF_A5 = 1.061405429;
    function mergeRealAndImagArrays(real2, imag2) {
      if (real2.length !== imag2.length) {
        throw new Error("Cannot merge real and imag arrays of different lengths. real:" + "".concat(real2.length, ", imag: ").concat(imag2.length, "."));
      }
      var result = new Float32Array(real2.length * 2);
      for (var i = 0; i < result.length; i += 2) {
        result[i] = real2[i / 2];
        result[i + 1] = imag2[i / 2];
      }
      return result;
    }
    function splitRealAndImagArrays(complex2) {
      var real2 = new Float32Array(complex2.length / 2);
      var imag2 = new Float32Array(complex2.length / 2);
      for (var i = 0; i < complex2.length; i += 2) {
        real2[i / 2] = complex2[i];
        imag2[i / 2] = complex2[i + 1];
      }
      return { real: real2, imag: imag2 };
    }
    function complexWithEvenIndex(complex2) {
      var len = Math.ceil(complex2.length / 4);
      var real2 = new Float32Array(len);
      var imag2 = new Float32Array(len);
      for (var i = 0; i < complex2.length; i += 4) {
        real2[Math.floor(i / 4)] = complex2[i];
        imag2[Math.floor(i / 4)] = complex2[i + 1];
      }
      return { real: real2, imag: imag2 };
    }
    function complexWithOddIndex(complex2) {
      var len = Math.floor(complex2.length / 4);
      var real2 = new Float32Array(len);
      var imag2 = new Float32Array(len);
      for (var i = 2; i < complex2.length; i += 4) {
        real2[Math.floor(i / 4)] = complex2[i];
        imag2[Math.floor(i / 4)] = complex2[i + 1];
      }
      return { real: real2, imag: imag2 };
    }
    function getComplexWithIndex(complex2, index) {
      var real2 = complex2[index * 2];
      var imag2 = complex2[index * 2 + 1];
      return { real: real2, imag: imag2 };
    }
    function assignToTypedArray(data, real2, imag2, index) {
      data[index * 2] = real2;
      data[index * 2 + 1] = imag2;
    }
    function exponents(n, inverse) {
      var real2 = new Float32Array(n / 2);
      var imag2 = new Float32Array(n / 2);
      for (var i = 0; i < Math.ceil(n / 2); i++) {
        var x = (inverse ? 2 : -2) * Math.PI * (i / n);
        real2[i] = Math.cos(x);
        imag2[i] = Math.sin(x);
      }
      return { real: real2, imag: imag2 };
    }
    function exponent(k, n, inverse) {
      var x = (inverse ? 2 : -2) * Math.PI * (k / n);
      var real2 = Math.cos(x);
      var imag2 = Math.sin(x);
      return { real: real2, imag: imag2 };
    }
    var ARROW = "->";
    var ARROW_REGEX = /->/g;
    var COMMA = ",";
    var ELLIPSIS = "...";
    function decodeEinsumEquation(equation, numTensors) {
      equation = equation.replace(/\s/g, "");
      var numArrows = (equation.length - equation.replace(ARROW_REGEX, "").length) / ARROW.length;
      if (numArrows < 1) {
        throw new Error("Equations without an arrow are not supported.");
      } else if (numArrows > 1) {
        throw new Error('Equation must contain exactly one arrow ("'.concat(ARROW, '").'));
      }
      var _a = __read(equation.split(ARROW), 2), inputString = _a[0], outputString = _a[1];
      assert(inputString.indexOf(ELLIPSIS) === -1, function() {
        return 'The ellipsis notation ("'.concat(ELLIPSIS, '") is not supported yet.');
      });
      var inputTerms = inputString.split(COMMA);
      var numInputs = inputTerms.length;
      if (numTensors !== numInputs) {
        throw new Error("Expected ".concat(numInputs, " input tensors, received ").concat(numTensors));
      }
      if (numInputs > 2) {
        throw new Error("Support for more than 2 input tensors is not implemented yet.");
      }
      var allDims = [];
      var _loop_1 = function(i2) {
        var dimName2 = outputString[i2];
        if (!inputTerms.some(function(inputTerm) {
          return inputTerm.indexOf(dimName2) !== -1;
        })) {
          throw new Error("Output subscripts contain the label ".concat(dimName2, " ") + "not present in the input subscripts.");
        }
        if (allDims.indexOf(dimName2) === -1) {
          allDims.push(dimName2);
        }
      };
      for (var i = 0; i < outputString.length; ++i) {
        _loop_1(i);
      }
      for (var i = 0; i < inputString.length; ++i) {
        var dimName = inputString[i];
        if (allDims.indexOf(dimName) === -1 && dimName !== COMMA) {
          allDims.push(dimName);
        }
      }
      var idDims = new Array(inputTerms.length);
      for (var i = 0; i < numInputs; ++i) {
        if (new Set(inputTerms[i].split("")).size !== inputTerms[i].length) {
          throw new Error("Found duplicate axes in input component ".concat(inputTerms[i], ". ") + "Support for duplicate axes in input is not implemented yet.");
        }
        idDims[i] = [];
        for (var j = 0; j < inputTerms[i].length; ++j) {
          idDims[i].push(allDims.indexOf(inputTerms[i][j]));
        }
      }
      var numDims = allDims.length;
      var numOutDims = outputString.length;
      var summedDims = [];
      for (var i = numOutDims; i < numDims; ++i) {
        summedDims.push(i);
      }
      return { allDims, summedDims, idDims };
    }
    function getEinsumPermutation(nDims, idDims) {
      var permutationIndices = new Array(nDims);
      permutationIndices.fill(-1);
      for (var i = 0; i < idDims.length; ++i) {
        permutationIndices[idDims[i]] = i;
      }
      var expandDims2 = [];
      for (var i = 0; i < nDims; ++i) {
        if (permutationIndices[i] === -1) {
          expandDims2.push(i);
        }
      }
      permutationIndices = permutationIndices.filter(function(d) {
        return d !== -1;
      });
      return { permutationIndices, expandDims: expandDims2 };
    }
    function checkEinsumDimSizes(nDims, idDims, tensors) {
      var dimSizes = new Array(nDims);
      var _loop_2 = function(i2) {
        var shape = tensors[i2].shape;
        var _loop_3 = function(j2) {
          if (dimSizes[idDims[i2][j2]] === void 0) {
            dimSizes[idDims[i2][j2]] = shape[j2];
          } else {
            assert(dimSizes[idDims[i2][j2]] === shape[j2], function() {
              return "Expected dimension ".concat(dimSizes[idDims[i2][j2]], " at axis ").concat(j2, " ") + "of input shaped ".concat(JSON.stringify(shape), ", ") + "but got dimension ".concat(shape[j2]);
            });
          }
        };
        for (var j = 0; j < idDims[i2].length; ++j) {
          _loop_3(j);
        }
      };
      for (var i = 0; i < tensors.length; ++i) {
        _loop_2(i);
      }
    }
    function getEinsumComputePath(summedDims, idDims) {
      var e_1, _a;
      var path = summedDims;
      var steps = [];
      var nSteps = 0;
      if (summedDims.length === 0) {
        path.push(-1);
      }
      nSteps = summedDims.length + 1;
      for (var i = 0; i < nSteps; ++i) {
        steps.push([]);
      }
      var computedTermIndices = [];
      for (var i = 0; i < path.length; ++i) {
        var summedDim = path[i];
        var termIndices = findTermsWithDim(idDims, summedDim);
        try {
          for (var termIndices_1 = (e_1 = void 0, __values(termIndices)), termIndices_1_1 = termIndices_1.next(); !termIndices_1_1.done; termIndices_1_1 = termIndices_1.next()) {
            var termIndex = termIndices_1_1.value;
            if (computedTermIndices.indexOf(termIndex) === -1) {
              steps[i].push(termIndex);
              computedTermIndices.push(termIndex);
            }
          }
        } catch (e_1_1) {
          e_1 = { error: e_1_1 };
        } finally {
          try {
            if (termIndices_1_1 && !termIndices_1_1.done && (_a = termIndices_1.return)) _a.call(termIndices_1);
          } finally {
            if (e_1) throw e_1.error;
          }
        }
      }
      return { path, steps };
    }
    function isIdentityPermutation(perm) {
      return perm.every(function(dim, index) {
        return dim === index;
      });
    }
    function findTermsWithDim(idDims, dim) {
      var termIndices = [];
      for (var i = 0; i < idDims.length; ++i) {
        if (idDims[i].length === 0 || idDims[i].indexOf(dim) !== -1 || dim === -1) {
          termIndices.push(i);
        }
      }
      return termIndices;
    }
    function prepareSplitSize(x, numOrSizeSplits, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var splitSizes = [];
      if (typeof numOrSizeSplits === "number") {
        assert(x.shape[axis] % numOrSizeSplits === 0, function() {
          return "Number of splits must evenly divide the axis.";
        });
        splitSizes = new Array(numOrSizeSplits).fill(x.shape[axis] / numOrSizeSplits);
      } else {
        var numOfNegs = numOrSizeSplits.reduce(function(count, value) {
          if (value === -1) {
            count += 1;
          }
          return count;
        }, 0);
        assert(numOfNegs <= 1, function() {
          return "There should be only one negative value in split array.";
        });
        var negIndex = numOrSizeSplits.indexOf(-1);
        if (negIndex !== -1) {
          var total = numOrSizeSplits.reduce(function(a, b) {
            return b > 0 ? a + b : a;
          });
          numOrSizeSplits[negIndex] = x.shape[axis] - total;
        }
        assert(x.shape[axis] === numOrSizeSplits.reduce(function(a, b) {
          return a + b;
        }), function() {
          return "The sum of sizes must match the size of the axis dimension.";
        });
        splitSizes = numOrSizeSplits;
      }
      return splitSizes;
    }
    function getSparseFillEmptyRowsIndicesDenseShapeMismatch(indicesLength) {
      return "Received SparseTensor with denseShape[0] = 0 but\n  indices.shape[0] = ".concat(indicesLength);
    }
    function getSparseFillEmptyRowsNegativeIndexErrorMessage(index, value) {
      return "indices(".concat(index, ", 0) is invalid: ").concat(value, " < 0");
    }
    function getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(index, value, limit) {
      return "indices(".concat(index, ", 0) is invalid: ").concat(value, " >= ").concat(limit);
    }
    function getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(dim1, dim2) {
      return "only one output dimension may be -1, not both ".concat(dim1, " and ").concat(dim2);
    }
    function getSparseReshapeNegativeOutputDimErrorMessage(dim, value) {
      return "size ".concat(dim, " must be non-negative, not ").concat(value);
    }
    function getSparseReshapeEmptyTensorZeroOutputDimErrorMessage() {
      return "reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero";
    }
    function getSparseReshapeInputOutputMultipleErrorMessage(inputShape, outputShape) {
      var inputSize = sizeFromShape(inputShape);
      var outputSize = sizeFromShape(outputShape);
      return "Input to reshape is a SparseTensor with ".concat(inputSize, "\n  dense values, but the requested shape requires a multiple of ").concat(outputSize, ". inputShape=").concat(inputShape, " outputShape= ").concat(outputShape);
    }
    function getSparseReshapeInputOutputMismatchErrorMessage(inputShape, outputShape) {
      var inputSize = sizeFromShape(inputShape);
      var outputSize = sizeFromShape(outputShape);
      return "Input to reshape is a tensor with ".concat(inputSize, " dense values, but the requested shape has ").concat(outputSize, ". inputShape=").concat(inputShape, " outputShape=").concat(outputShape);
    }
    function getSparseSegmentReductionNegativeSegmentIdsErrorMessage() {
      return "segment ids must be >= 0";
    }
    function getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage() {
      return "segment ids are not increasing";
    }
    function getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(segmentId, outputRows) {
      return "Segment id ".concat(segmentId, " out of range [0, ").concat(outputRows, "), possibly because segmentIds input is not sorted.");
    }
    function getSparseSegmentReductionIndicesOutOfRangeErrorMessage(index, indexValue, inputRows) {
      return "Bad: indices[".concat(index, "] == ").concat(indexValue, " out of range [0, ").concat(inputRows, ")");
    }
    function segOpComputeOptimalWindowSize(inSize, numSegments) {
      var done = false;
      var res;
      if (inSize <= PARALLELIZE_THRESHOLD) {
        res = inSize;
        done = true;
      } else {
        res = nearestDivisor(inSize, Math.floor(Math.sqrt(inSize)));
      }
      while (!done) {
        if (res > numSegments || res === inSize) {
          done = true;
        } else {
          res = nearestDivisor(inSize, res + 1);
        }
      }
      return res;
    }
    function computeOutShape(aShape, axis, numSegments) {
      var outShape = [];
      var rank = aShape.length;
      for (var dim = 0; dim < rank; dim++) {
        if (dim !== axis) {
          outShape.push(aShape[dim]);
        } else {
          outShape.push(numSegments);
        }
      }
      return outShape;
    }
    function collectGatherOpShapeInfo(x, indices, axis, batchDims) {
      var indicesRank = indices.shape.length;
      var xRank = x.shape.length;
      if (batchDims !== 0) {
        if (batchDims < -indicesRank || batchDims > indicesRank) {
          throw new Error("Expect batchDims in the range of [-".concat(indicesRank, ", ").concat(indicesRank, "], but got ").concat(batchDims));
        }
      }
      if (batchDims < 0) {
        batchDims += indicesRank;
      }
      if (batchDims > xRank) {
        throw new Error("batchDims (".concat(batchDims, ") must be less than rank(x) (\n    ").concat(xRank, ")."));
      }
      if (axis < batchDims) {
        throw new Error("batchDims (".concat(batchDims, ") must be less than or equal to axis (").concat(axis, ")."));
      }
      for (var i = 0; i < batchDims; ++i) {
        if (x.shape[i] !== indices.shape[i]) {
          throw new Error("x.shape[".concat(i, "]: ").concat(x.shape[i], " should be equal to indices.shape[").concat(i, "]: ").concat(indices.shape[i], "."));
        }
      }
      var dimSize = x.shape[axis];
      var outputShape = [];
      var batchSize = 1;
      var outerSize = 1;
      var sliceSize = 1;
      for (var i = 0; i < batchDims; ++i) {
        outputShape.push(x.shape[i]);
        batchSize *= x.shape[i];
      }
      for (var i = batchDims; i < axis; i++) {
        outputShape.push(x.shape[i]);
        outerSize *= x.shape[i];
      }
      for (var i = batchDims; i < indicesRank; i++) {
        outputShape.push(indices.shape[i]);
      }
      for (var i = axis + 1; i < xRank; i++) {
        outputShape.push(x.shape[i]);
        sliceSize *= x.shape[i];
      }
      return { batchSize, sliceSize, outerSize, dimSize, outputShape };
    }
    var segment_util = {
      __proto__: null,
      collectGatherOpShapeInfo,
      computeOutShape,
      segOpComputeOptimalWindowSize
    };
    function fromUint8ToStringArray(vals) {
      try {
        return vals.map(function(val) {
          return decodeString(val);
        });
      } catch (err) {
        throw new Error("Failed to decode encoded string bytes into utf-8, error: ".concat(err));
      }
    }
    function fromStringArrayToUint8(strings) {
      return strings.map(function(s) {
        return encodeString(s);
      });
    }
    var backend_util = {
      __proto__: null,
      ERF_A1,
      ERF_A2,
      ERF_A3,
      ERF_A4,
      ERF_A5,
      ERF_P,
      PARALLELIZE_THRESHOLD,
      get RowPartitionType() {
        return RowPartitionType;
      },
      SELU_SCALE,
      SELU_SCALEALPHA,
      applyActivation,
      assertAndGetBroadcastShape,
      assertAxesAreInnerMostDims,
      assertParamsConsistent,
      assignToTypedArray,
      axesAreInnerMostDims,
      calculateShapes,
      checkEinsumDimSizes,
      checkPadOnDimRoundingMode,
      combineLocations,
      combineRaggedTensorToTensorShapes,
      complexWithEvenIndex,
      complexWithOddIndex,
      computeConv2DInfo,
      computeConv3DInfo,
      computeDefaultPad,
      computeDilation2DInfo,
      computeOptimalWindowSize,
      computeOutAndReduceShapes,
      computeOutShape: computeOutShape$1,
      computePool2DInfo,
      computePool3DInfo,
      convertConv2DDataFormat,
      decodeEinsumEquation,
      eitherStridesOrDilationsAreOne,
      expandShapeToKeepDim,
      exponent,
      exponents,
      fromStringArrayToUint8,
      fromUint8ToStringArray,
      getAxesPermutation,
      getBroadcastDims,
      getComplexWithIndex,
      getEinsumComputePath,
      getEinsumPermutation,
      getFusedBiasGradient,
      getFusedDyActivation,
      getImageCenter,
      getInnerMostAxes,
      getPermuted,
      getRaggedRank,
      getReductionAxes,
      getReshaped,
      getReshapedPermuted,
      getRowPartitionTypesHelper,
      getSliceBeginCoords,
      getSliceSize,
      getSparseFillEmptyRowsIndicesDenseShapeMismatch,
      getSparseFillEmptyRowsNegativeIndexErrorMessage,
      getSparseFillEmptyRowsOutOfRangeIndexErrorMessage,
      getSparseReshapeEmptyTensorZeroOutputDimErrorMessage,
      getSparseReshapeInputOutputMismatchErrorMessage,
      getSparseReshapeInputOutputMultipleErrorMessage,
      getSparseReshapeMultipleNegativeOneOutputDimErrorMessage,
      getSparseReshapeNegativeOutputDimErrorMessage,
      getSparseSegmentReductionIndicesOutOfRangeErrorMessage,
      getSparseSegmentReductionNegativeSegmentIdsErrorMessage,
      getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage,
      getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage,
      getUndoAxesPermutation,
      isIdentityPermutation,
      log: log$1,
      mergeRealAndImagArrays,
      prepareAndValidate,
      prepareSplitSize,
      segment_util,
      shouldFuse,
      slice_util,
      splitRealAndImagArrays,
      stridesOrDilationsArePositive,
      tupleValuesAreOne,
      upcastType,
      validateDefaultValueShape,
      validateInput: validateInput$1,
      validateUpdateShape,
      warn
    };
    var kernel_impls = {
      __proto__: null,
      nonMaxSuppressionV3Impl,
      nonMaxSuppressionV4Impl,
      nonMaxSuppressionV5Impl,
      whereImpl
    };
    registerOptimizers();
    exports2.Abs = Abs;
    exports2.Acos = Acos;
    exports2.Acosh = Acosh;
    exports2.AdadeltaOptimizer = AdadeltaOptimizer;
    exports2.AdagradOptimizer = AdagradOptimizer;
    exports2.AdamOptimizer = AdamOptimizer;
    exports2.AdamaxOptimizer = AdamaxOptimizer;
    exports2.Add = Add;
    exports2.AddN = AddN;
    exports2.All = All;
    exports2.Any = Any;
    exports2.ArgMax = ArgMax;
    exports2.ArgMin = ArgMin;
    exports2.Asin = Asin;
    exports2.Asinh = Asinh;
    exports2.Atan = Atan;
    exports2.Atan2 = Atan2;
    exports2.Atanh = Atanh;
    exports2.AvgPool = AvgPool;
    exports2.AvgPool3D = AvgPool3D;
    exports2.AvgPool3DGrad = AvgPool3DGrad;
    exports2.AvgPoolGrad = AvgPoolGrad;
    exports2.BatchMatMul = BatchMatMul;
    exports2.BatchToSpaceND = BatchToSpaceND;
    exports2.Bincount = Bincount;
    exports2.BitwiseAnd = BitwiseAnd;
    exports2.BroadcastArgs = BroadcastArgs;
    exports2.BroadcastTo = BroadcastTo;
    exports2.Cast = Cast;
    exports2.Ceil = Ceil;
    exports2.ClipByValue = ClipByValue;
    exports2.Complex = Complex;
    exports2.ComplexAbs = ComplexAbs;
    exports2.Concat = Concat;
    exports2.Conv2D = Conv2D;
    exports2.Conv2DBackpropFilter = Conv2DBackpropFilter;
    exports2.Conv2DBackpropInput = Conv2DBackpropInput;
    exports2.Conv3D = Conv3D;
    exports2.Conv3DBackpropFilterV2 = Conv3DBackpropFilterV2;
    exports2.Conv3DBackpropInputV2 = Conv3DBackpropInputV2;
    exports2.Cos = Cos;
    exports2.Cosh = Cosh;
    exports2.CropAndResize = CropAndResize;
    exports2.Cumprod = Cumprod;
    exports2.Cumsum = Cumsum;
    exports2.DataStorage = DataStorage;
    exports2.DenseBincount = DenseBincount;
    exports2.DepthToSpace = DepthToSpace;
    exports2.DepthwiseConv2dNative = DepthwiseConv2dNative;
    exports2.DepthwiseConv2dNativeBackpropFilter = DepthwiseConv2dNativeBackpropFilter;
    exports2.DepthwiseConv2dNativeBackpropInput = DepthwiseConv2dNativeBackpropInput;
    exports2.Diag = Diag;
    exports2.Dilation2D = Dilation2D;
    exports2.Dilation2DBackpropFilter = Dilation2DBackpropFilter;
    exports2.Dilation2DBackpropInput = Dilation2DBackpropInput;
    exports2.Draw = Draw;
    exports2.Einsum = Einsum;
    exports2.Elu = Elu;
    exports2.EluGrad = EluGrad;
    exports2.Environment = Environment;
    exports2.Equal = Equal;
    exports2.Erf = Erf;
    exports2.Exp = Exp;
    exports2.ExpandDims = ExpandDims;
    exports2.Expm1 = Expm1;
    exports2.FFT = FFT;
    exports2.Fill = Fill;
    exports2.FlipLeftRight = FlipLeftRight;
    exports2.Floor = Floor;
    exports2.FloorDiv = FloorDiv;
    exports2.FromPixels = FromPixels;
    exports2.FusedBatchNorm = FusedBatchNorm;
    exports2.FusedConv2D = FusedConv2D;
    exports2.FusedDepthwiseConv2D = FusedDepthwiseConv2D;
    exports2.GatherNd = GatherNd;
    exports2.GatherV2 = GatherV2;
    exports2.Greater = Greater;
    exports2.GreaterEqual = GreaterEqual;
    exports2.IFFT = IFFT;
    exports2.Identity = Identity;
    exports2.Imag = Imag;
    exports2.IsFinite = IsFinite;
    exports2.IsInf = IsInf;
    exports2.IsNan = IsNan;
    exports2.KernelBackend = KernelBackend;
    exports2.LRN = LRN;
    exports2.LRNGrad = LRNGrad;
    exports2.LeakyRelu = LeakyRelu;
    exports2.Less = Less;
    exports2.LessEqual = LessEqual;
    exports2.LinSpace = LinSpace;
    exports2.Log = Log;
    exports2.Log1p = Log1p;
    exports2.LogSoftmax = LogSoftmax;
    exports2.LogicalAnd = LogicalAnd;
    exports2.LogicalNot = LogicalNot;
    exports2.LogicalOr = LogicalOr;
    exports2.LogicalXor = LogicalXor;
    exports2.LowerBound = LowerBound;
    exports2.MatrixBandPart = MatrixBandPart;
    exports2.Max = Max;
    exports2.MaxPool = MaxPool;
    exports2.MaxPool3D = MaxPool3D;
    exports2.MaxPool3DGrad = MaxPool3DGrad;
    exports2.MaxPoolGrad = MaxPoolGrad;
    exports2.MaxPoolWithArgmax = MaxPoolWithArgmax;
    exports2.Maximum = Maximum;
    exports2.Mean = Mean;
    exports2.Min = Min;
    exports2.Minimum = Minimum;
    exports2.MirrorPad = MirrorPad;
    exports2.Mod = Mod;
    exports2.MomentumOptimizer = MomentumOptimizer;
    exports2.Multinomial = Multinomial;
    exports2.Multiply = Multiply;
    exports2.Neg = Neg;
    exports2.NonMaxSuppressionV3 = NonMaxSuppressionV3;
    exports2.NonMaxSuppressionV4 = NonMaxSuppressionV4;
    exports2.NonMaxSuppressionV5 = NonMaxSuppressionV5;
    exports2.NotEqual = NotEqual;
    exports2.OP_SCOPE_SUFFIX = OP_SCOPE_SUFFIX;
    exports2.OneHot = OneHot;
    exports2.OnesLike = OnesLike;
    exports2.Optimizer = Optimizer;
    exports2.OptimizerConstructors = OptimizerConstructors;
    exports2.Pack = Pack;
    exports2.PadV2 = PadV2;
    exports2.Pool = Pool;
    exports2.Pow = Pow;
    exports2.Prelu = Prelu;
    exports2.Prod = Prod;
    exports2.RMSPropOptimizer = RMSPropOptimizer;
    exports2.RaggedGather = RaggedGather;
    exports2.RaggedRange = RaggedRange;
    exports2.RaggedTensorToTensor = RaggedTensorToTensor;
    exports2.Range = Range;
    exports2.Real = Real;
    exports2.RealDiv = RealDiv;
    exports2.Reciprocal = Reciprocal;
    exports2.Relu = Relu;
    exports2.Relu6 = Relu6;
    exports2.Reshape = Reshape;
    exports2.ResizeBilinear = ResizeBilinear;
    exports2.ResizeBilinearGrad = ResizeBilinearGrad;
    exports2.ResizeNearestNeighbor = ResizeNearestNeighbor;
    exports2.ResizeNearestNeighborGrad = ResizeNearestNeighborGrad;
    exports2.Reverse = Reverse;
    exports2.RotateWithOffset = RotateWithOffset;
    exports2.Round = Round;
    exports2.Rsqrt = Rsqrt;
    exports2.SGDOptimizer = SGDOptimizer;
    exports2.ScatterNd = ScatterNd;
    exports2.SearchSorted = SearchSorted;
    exports2.Select = Select;
    exports2.Selu = Selu;
    exports2.Sigmoid = Sigmoid;
    exports2.Sign = Sign;
    exports2.Sin = Sin;
    exports2.Sinh = Sinh;
    exports2.Slice = Slice;
    exports2.Softmax = Softmax;
    exports2.Softplus = Softplus;
    exports2.SpaceToBatchND = SpaceToBatchND;
    exports2.SparseFillEmptyRows = SparseFillEmptyRows;
    exports2.SparseReshape = SparseReshape;
    exports2.SparseSegmentMean = SparseSegmentMean;
    exports2.SparseSegmentSum = SparseSegmentSum;
    exports2.SparseToDense = SparseToDense;
    exports2.SplitV = SplitV;
    exports2.Sqrt = Sqrt;
    exports2.Square = Square;
    exports2.SquaredDifference = SquaredDifference;
    exports2.StaticRegexReplace = StaticRegexReplace;
    exports2.Step = Step;
    exports2.StridedSlice = StridedSlice;
    exports2.StringNGrams = StringNGrams;
    exports2.StringSplit = StringSplit;
    exports2.StringToHashBucketFast = StringToHashBucketFast;
    exports2.Sub = Sub;
    exports2.Sum = Sum;
    exports2.Tan = Tan;
    exports2.Tanh = Tanh;
    exports2.Tensor = Tensor;
    exports2.TensorBuffer = TensorBuffer;
    exports2.TensorScatterUpdate = TensorScatterUpdate;
    exports2.Tile = Tile;
    exports2.TopK = TopK;
    exports2.Transform = Transform;
    exports2.Transpose = Transpose;
    exports2.Unique = Unique;
    exports2.Unpack = Unpack;
    exports2.UnsortedSegmentSum = UnsortedSegmentSum;
    exports2.UpperBound = UpperBound;
    exports2.Variable = Variable;
    exports2.ZerosLike = ZerosLike;
    exports2._FusedMatMul = _FusedMatMul;
    exports2.abs = abs;
    exports2.acos = acos;
    exports2.acosh = acosh;
    exports2.add = add;
    exports2.addN = addN;
    exports2.all = all;
    exports2.any = any;
    exports2.argMax = argMax;
    exports2.argMin = argMin;
    exports2.asin = asin;
    exports2.asinh = asinh;
    exports2.atan = atan;
    exports2.atan2 = atan2;
    exports2.atanh = atanh;
    exports2.avgPool = avgPool;
    exports2.avgPool3d = avgPool3d;
    exports2.backend = backend;
    exports2.backend_util = backend_util;
    exports2.basicLSTMCell = basicLSTMCell;
    exports2.batchNorm = batchNorm;
    exports2.batchNorm2d = batchNorm2d;
    exports2.batchNorm3d = batchNorm3d;
    exports2.batchNorm4d = batchNorm4d;
    exports2.batchToSpaceND = batchToSpaceND;
    exports2.bincount = bincount;
    exports2.bitwiseAnd = bitwiseAnd;
    exports2.booleanMaskAsync = booleanMaskAsync;
    exports2.broadcastArgs = broadcastArgs;
    exports2.broadcastTo = broadcastTo;
    exports2.broadcast_util = broadcast_util;
    exports2.browser = browser;
    exports2.buffer = buffer;
    exports2.cast = cast;
    exports2.ceil = ceil;
    exports2.clipByValue = clipByValue;
    exports2.clone = clone;
    exports2.complex = complex;
    exports2.concat = concat;
    exports2.concat1d = concat1d;
    exports2.concat2d = concat2d;
    exports2.concat3d = concat3d;
    exports2.concat4d = concat4d;
    exports2.conv1d = conv1d;
    exports2.conv2d = conv2d$1;
    exports2.conv2dTranspose = conv2dTranspose;
    exports2.conv3d = conv3d;
    exports2.conv3dTranspose = conv3dTranspose;
    exports2.copyRegisteredKernels = copyRegisteredKernels;
    exports2.cos = cos;
    exports2.cosh = cosh;
    exports2.cosineWindow = cosineWindow;
    exports2.cumprod = cumprod;
    exports2.cumsum = cumsum;
    exports2.customGrad = customGrad;
    exports2.denseBincount = denseBincount;
    exports2.deprecationWarn = deprecationWarn;
    exports2.depthToSpace = depthToSpace;
    exports2.depthwiseConv2d = depthwiseConv2d$1;
    exports2.device_util = device_util;
    exports2.diag = diag;
    exports2.dilation2d = dilation2d;
    exports2.disableDeprecationWarnings = disableDeprecationWarnings;
    exports2.dispose = dispose;
    exports2.disposeVariables = disposeVariables;
    exports2.div = div;
    exports2.divNoNan = divNoNan;
    exports2.dot = dot;
    exports2.dropout = dropout;
    exports2.einsum = einsum;
    exports2.elu = elu;
    exports2.enableDebugMode = enableDebugMode;
    exports2.enableProdMode = enableProdMode;
    exports2.enclosingPowerOfTwo = enclosingPowerOfTwo;
    exports2.engine = engine;
    exports2.ensureShape = ensureShape;
    exports2.env = env;
    exports2.equal = equal;
    exports2.erf = erf;
    exports2.euclideanNorm = euclideanNorm;
    exports2.exp = exp;
    exports2.expandDims = expandDims;
    exports2.expm1 = expm1;
    exports2.eye = eye;
    exports2.fft = fft;
    exports2.fill = fill;
    exports2.findBackend = findBackend;
    exports2.findBackendFactory = findBackendFactory;
    exports2.floor = floor;
    exports2.floorDiv = floorDiv;
    exports2.fused = fused_ops;
    exports2.gather = gather;
    exports2.gatherND = gatherND;
    exports2.gather_util = gather_nd_util;
    exports2.getBackend = getBackend;
    exports2.getGradient = getGradient;
    exports2.getKernel = getKernel;
    exports2.getKernelsForBackend = getKernelsForBackend;
    exports2.grad = grad;
    exports2.grads = grads;
    exports2.greater = greater;
    exports2.greaterEqual = greaterEqual;
    exports2.ifft = ifft;
    exports2.imag = imag;
    exports2.image = image;
    exports2.inTopKAsync = inTopKAsync;
    exports2.io = io;
    exports2.irfft = irfft;
    exports2.isFinite = isFinite$1;
    exports2.isInf = isInf;
    exports2.isNaN = isNaN$1;
    exports2.keep = keep;
    exports2.kernel_impls = kernel_impls;
    exports2.leakyRelu = leakyRelu;
    exports2.less = less;
    exports2.lessEqual = lessEqual;
    exports2.linalg = linalg;
    exports2.linspace = linspace;
    exports2.localResponseNormalization = localResponseNormalization;
    exports2.log = log;
    exports2.log1p = log1p;
    exports2.logSigmoid = logSigmoid;
    exports2.logSoftmax = logSoftmax;
    exports2.logSumExp = logSumExp;
    exports2.logicalAnd = logicalAnd;
    exports2.logicalNot = logicalNot;
    exports2.logicalOr = logicalOr;
    exports2.logicalXor = logicalXor;
    exports2.losses = losses;
    exports2.lowerBound = lowerBound;
    exports2.matMul = matMul$1;
    exports2.math = math;
    exports2.max = max;
    exports2.maxPool = maxPool;
    exports2.maxPool3d = maxPool3d;
    exports2.maxPoolWithArgmax = maxPoolWithArgmax;
    exports2.maximum = maximum;
    exports2.mean = mean;
    exports2.memory = memory;
    exports2.meshgrid = meshgrid;
    exports2.min = min;
    exports2.minimum = minimum;
    exports2.mirrorPad = mirrorPad;
    exports2.mod = mod;
    exports2.moments = moments;
    exports2.movingAverage = movingAverage;
    exports2.mul = mul;
    exports2.multiRNNCell = multiRNNCell;
    exports2.multinomial = multinomial;
    exports2.neg = neg;
    exports2.nextFrame = nextFrame;
    exports2.norm = norm;
    exports2.notEqual = notEqual;
    exports2.oneHot = oneHot;
    exports2.ones = ones;
    exports2.onesLike = onesLike;
    exports2.op = op;
    exports2.outerProduct = outerProduct;
    exports2.pad = pad;
    exports2.pad1d = pad1d;
    exports2.pad2d = pad2d;
    exports2.pad3d = pad3d;
    exports2.pad4d = pad4d;
    exports2.pool = pool;
    exports2.pow = pow;
    exports2.prelu = prelu;
    exports2.print = print;
    exports2.prod = prod;
    exports2.profile = profile;
    exports2.raggedGather = raggedGather;
    exports2.raggedRange = raggedRange;
    exports2.raggedTensorToTensor = raggedTensorToTensor;
    exports2.rand = rand;
    exports2.randomGamma = randomGamma;
    exports2.randomNormal = randomNormal;
    exports2.randomStandardNormal = randomStandardNormal;
    exports2.randomUniform = randomUniform;
    exports2.randomUniformInt = randomUniformInt;
    exports2.range = range;
    exports2.ready = ready;
    exports2.real = real;
    exports2.reciprocal = reciprocal;
    exports2.registerBackend = registerBackend;
    exports2.registerGradient = registerGradient;
    exports2.registerKernel = registerKernel;
    exports2.relu = relu;
    exports2.relu6 = relu6;
    exports2.removeBackend = removeBackend;
    exports2.reshape = reshape;
    exports2.reverse = reverse;
    exports2.reverse1d = reverse1d;
    exports2.reverse2d = reverse2d;
    exports2.reverse3d = reverse3d;
    exports2.reverse4d = reverse4d;
    exports2.rfft = rfft;
    exports2.round = round;
    exports2.rsqrt = rsqrt;
    exports2.scalar = scalar;
    exports2.scatterND = scatterND;
    exports2.scatter_util = scatter_nd_util;
    exports2.searchSorted = searchSorted;
    exports2.selu = selu;
    exports2.separableConv2d = separableConv2d;
    exports2.serialization = serialization;
    exports2.setBackend = setBackend;
    exports2.setPlatform = setPlatform;
    exports2.setdiff1dAsync = setdiff1dAsync;
    exports2.sigmoid = sigmoid;
    exports2.sign = sign;
    exports2.signal = signal;
    exports2.sin = sin;
    exports2.sinh = sinh;
    exports2.slice = slice;
    exports2.slice1d = slice1d;
    exports2.slice2d = slice2d;
    exports2.slice3d = slice3d;
    exports2.slice4d = slice4d;
    exports2.slice_util = slice_util;
    exports2.softmax = softmax;
    exports2.softplus = softplus;
    exports2.spaceToBatchND = spaceToBatchND;
    exports2.sparse = sparse;
    exports2.sparseToDense = sparseToDense;
    exports2.spectral = spectral;
    exports2.split = split;
    exports2.sqrt = sqrt;
    exports2.square = square;
    exports2.squaredDifference = squaredDifference;
    exports2.squeeze = squeeze;
    exports2.stack = stack;
    exports2.step = step;
    exports2.stridedSlice = stridedSlice;
    exports2.string = string;
    exports2.sub = sub;
    exports2.sum = sum;
    exports2.sumOutType = sumOutType;
    exports2.tan = tan;
    exports2.tanh = tanh;
    exports2.tensor = tensor;
    exports2.tensor1d = tensor1d;
    exports2.tensor2d = tensor2d;
    exports2.tensor3d = tensor3d;
    exports2.tensor4d = tensor4d;
    exports2.tensor5d = tensor5d;
    exports2.tensor6d = tensor6d;
    exports2.tensorScatterUpdate = tensorScatterUpdate;
    exports2.tensor_util = tensor_util;
    exports2.test_util = test_util;
    exports2.tidy = tidy;
    exports2.tile = tile;
    exports2.time = time;
    exports2.topk = topk;
    exports2.train = train;
    exports2.transpose = transpose;
    exports2.truncatedNormal = truncatedNormal;
    exports2.unique = unique;
    exports2.unregisterGradient = unregisterGradient;
    exports2.unregisterKernel = unregisterKernel;
    exports2.unsortedSegmentSum = unsortedSegmentSum;
    exports2.unstack = unstack;
    exports2.upcastType = upcastType;
    exports2.upperBound = upperBound;
    exports2.util = util;
    exports2.valueAndGrad = valueAndGrad;
    exports2.valueAndGrads = valueAndGrads;
    exports2.variable = variable;
    exports2.variableGrads = variableGrads;
    exports2.version_core = version;
    exports2.where = where;
    exports2.whereAsync = whereAsync;
    exports2.zeros = zeros;
    exports2.zerosLike = zerosLike;
  }
});

// node_modules/long/src/long.js
var require_long = __commonJS({
  "node_modules/long/src/long.js"(exports2, module2) {
    module2.exports = Long;
    var wasm = null;
    try {
      wasm = 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 Long(low, high, unsigned) {
      this.low = low | 0;
      this.high = high | 0;
      this.unsigned = !!unsigned;
    }
    Long.prototype.__isLong__;
    Object.defineProperty(Long.prototype, "__isLong__", { value: true });
    function isLong(obj) {
      return (obj && obj["__isLong__"]) === true;
    }
    Long.isLong = isLong;
    var INT_CACHE = {};
    var UINT_CACHE = {};
    function fromInt(value, unsigned) {
      var obj, cachedObj, cache;
      if (unsigned) {
        value >>>= 0;
        if (cache = 0 <= value && value < 256) {
          cachedObj = UINT_CACHE[value];
          if (cachedObj)
            return cachedObj;
        }
        obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
        if (cache)
          UINT_CACHE[value] = obj;
        return obj;
      } else {
        value |= 0;
        if (cache = -128 <= value && value < 128) {
          cachedObj = INT_CACHE[value];
          if (cachedObj)
            return cachedObj;
        }
        obj = fromBits(value, value < 0 ? -1 : 0, false);
        if (cache)
          INT_CACHE[value] = obj;
        return obj;
      }
    }
    Long.fromInt = fromInt;
    function fromNumber(value, unsigned) {
      if (isNaN(value))
        return unsigned ? UZERO : ZERO;
      if (unsigned) {
        if (value < 0)
          return UZERO;
        if (value >= TWO_PWR_64_DBL)
          return MAX_UNSIGNED_VALUE;
      } else {
        if (value <= -TWO_PWR_63_DBL)
          return MIN_VALUE;
        if (value + 1 >= TWO_PWR_63_DBL)
          return MAX_VALUE;
      }
      if (value < 0)
        return fromNumber(-value, unsigned).neg();
      return fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned);
    }
    Long.fromNumber = fromNumber;
    function fromBits(lowBits, highBits, unsigned) {
      return new Long(lowBits, highBits, unsigned);
    }
    Long.fromBits = fromBits;
    var pow_dbl = Math.pow;
    function fromString(str, unsigned, radix) {
      if (str.length === 0)
        throw Error("empty string");
      if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
        return ZERO;
      if (typeof unsigned === "number") {
        radix = unsigned, unsigned = false;
      } else {
        unsigned = !!unsigned;
      }
      radix = radix || 10;
      if (radix < 2 || 36 < radix)
        throw RangeError("radix");
      var p;
      if ((p = str.indexOf("-")) > 0)
        throw Error("interior hyphen");
      else if (p === 0) {
        return fromString(str.substring(1), unsigned, radix).neg();
      }
      var radixToPower = fromNumber(pow_dbl(radix, 8));
      var result = ZERO;
      for (var i = 0; i < str.length; i += 8) {
        var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
        if (size < 8) {
          var power = fromNumber(pow_dbl(radix, size));
          result = result.mul(power).add(fromNumber(value));
        } else {
          result = result.mul(radixToPower);
          result = result.add(fromNumber(value));
        }
      }
      result.unsigned = unsigned;
      return result;
    }
    Long.fromString = fromString;
    function fromValue(val, unsigned) {
      if (typeof val === "number")
        return fromNumber(val, unsigned);
      if (typeof val === "string")
        return fromString(val, unsigned);
      return fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned);
    }
    Long.fromValue = fromValue;
    var TWO_PWR_16_DBL = 1 << 16;
    var TWO_PWR_24_DBL = 1 << 24;
    var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
    var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
    var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
    var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
    var ZERO = fromInt(0);
    Long.ZERO = ZERO;
    var UZERO = fromInt(0, true);
    Long.UZERO = UZERO;
    var ONE = fromInt(1);
    Long.ONE = ONE;
    var UONE = fromInt(1, true);
    Long.UONE = UONE;
    var NEG_ONE = fromInt(-1);
    Long.NEG_ONE = NEG_ONE;
    var MAX_VALUE = fromBits(4294967295 | 0, 2147483647 | 0, false);
    Long.MAX_VALUE = MAX_VALUE;
    var MAX_UNSIGNED_VALUE = fromBits(4294967295 | 0, 4294967295 | 0, true);
    Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
    var MIN_VALUE = fromBits(0, 2147483648 | 0, false);
    Long.MIN_VALUE = MIN_VALUE;
    var LongPrototype = Long.prototype;
    LongPrototype.toInt = function toInt() {
      return this.unsigned ? this.low >>> 0 : this.low;
    };
    LongPrototype.toNumber = function toNumber() {
      if (this.unsigned)
        return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
      return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
    };
    LongPrototype.toString = function toString(radix) {
      radix = radix || 10;
      if (radix < 2 || 36 < radix)
        throw RangeError("radix");
      if (this.isZero())
        return "0";
      if (this.isNegative()) {
        if (this.eq(MIN_VALUE)) {
          var radixLong = fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
          return div.toString(radix) + rem1.toInt().toString(radix);
        } else
          return "-" + this.neg().toString(radix);
      }
      var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), rem = this;
      var result = "";
      while (true) {
        var remDiv = rem.div(radixToPower), intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, digits = intval.toString(radix);
        rem = remDiv;
        if (rem.isZero())
          return digits + result;
        else {
          while (digits.length < 6)
            digits = "0" + digits;
          result = "" + digits + result;
        }
      }
    };
    LongPrototype.getHighBits = function getHighBits() {
      return this.high;
    };
    LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
      return this.high >>> 0;
    };
    LongPrototype.getLowBits = function getLowBits() {
      return this.low;
    };
    LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
      return this.low >>> 0;
    };
    LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
      if (this.isNegative())
        return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
      var val = this.high != 0 ? this.high : this.low;
      for (var bit = 31; bit > 0; bit--)
        if ((val & 1 << bit) != 0)
          break;
      return this.high != 0 ? bit + 33 : bit + 1;
    };
    LongPrototype.isZero = function isZero() {
      return this.high === 0 && this.low === 0;
    };
    LongPrototype.eqz = LongPrototype.isZero;
    LongPrototype.isNegative = function isNegative() {
      return !this.unsigned && this.high < 0;
    };
    LongPrototype.isPositive = function isPositive() {
      return this.unsigned || this.high >= 0;
    };
    LongPrototype.isOdd = function isOdd() {
      return (this.low & 1) === 1;
    };
    LongPrototype.isEven = function isEven() {
      return (this.low & 1) === 0;
    };
    LongPrototype.equals = function equals(other) {
      if (!isLong(other))
        other = fromValue(other);
      if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
        return false;
      return this.high === other.high && this.low === other.low;
    };
    LongPrototype.eq = LongPrototype.equals;
    LongPrototype.notEquals = function notEquals(other) {
      return !this.eq(
        /* validates */
        other
      );
    };
    LongPrototype.neq = LongPrototype.notEquals;
    LongPrototype.ne = LongPrototype.notEquals;
    LongPrototype.lessThan = function lessThan(other) {
      return this.comp(
        /* validates */
        other
      ) < 0;
    };
    LongPrototype.lt = LongPrototype.lessThan;
    LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
      return this.comp(
        /* validates */
        other
      ) <= 0;
    };
    LongPrototype.lte = LongPrototype.lessThanOrEqual;
    LongPrototype.le = LongPrototype.lessThanOrEqual;
    LongPrototype.greaterThan = function greaterThan(other) {
      return this.comp(
        /* validates */
        other
      ) > 0;
    };
    LongPrototype.gt = LongPrototype.greaterThan;
    LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
      return this.comp(
        /* validates */
        other
      ) >= 0;
    };
    LongPrototype.gte = LongPrototype.greaterThanOrEqual;
    LongPrototype.ge = LongPrototype.greaterThanOrEqual;
    LongPrototype.compare = function compare(other) {
      if (!isLong(other))
        other = fromValue(other);
      if (this.eq(other))
        return 0;
      var thisNeg = this.isNegative(), otherNeg = other.isNegative();
      if (thisNeg && !otherNeg)
        return -1;
      if (!thisNeg && otherNeg)
        return 1;
      if (!this.unsigned)
        return this.sub(other).isNegative() ? -1 : 1;
      return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1;
    };
    LongPrototype.comp = LongPrototype.compare;
    LongPrototype.negate = function negate() {
      if (!this.unsigned && this.eq(MIN_VALUE))
        return MIN_VALUE;
      return this.not().add(ONE);
    };
    LongPrototype.neg = LongPrototype.negate;
    LongPrototype.add = function add(addend) {
      if (!isLong(addend))
        addend = fromValue(addend);
      var a48 = this.high >>> 16;
      var a32 = this.high & 65535;
      var a16 = this.low >>> 16;
      var a00 = this.low & 65535;
      var b48 = addend.high >>> 16;
      var b32 = addend.high & 65535;
      var b16 = addend.low >>> 16;
      var b00 = addend.low & 65535;
      var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
      c00 += a00 + b00;
      c16 += c00 >>> 16;
      c00 &= 65535;
      c16 += a16 + b16;
      c32 += c16 >>> 16;
      c16 &= 65535;
      c32 += a32 + b32;
      c48 += c32 >>> 16;
      c32 &= 65535;
      c48 += a48 + b48;
      c48 &= 65535;
      return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
    };
    LongPrototype.subtract = function subtract(subtrahend) {
      if (!isLong(subtrahend))
        subtrahend = fromValue(subtrahend);
      return this.add(subtrahend.neg());
    };
    LongPrototype.sub = LongPrototype.subtract;
    LongPrototype.multiply = function multiply(multiplier) {
      if (this.isZero())
        return ZERO;
      if (!isLong(multiplier))
        multiplier = fromValue(multiplier);
      if (wasm) {
        var low = wasm.mul(
          this.low,
          this.high,
          multiplier.low,
          multiplier.high
        );
        return fromBits(low, wasm.get_high(), this.unsigned);
      }
      if (multiplier.isZero())
        return ZERO;
      if (this.eq(MIN_VALUE))
        return multiplier.isOdd() ? MIN_VALUE : ZERO;
      if (multiplier.eq(MIN_VALUE))
        return this.isOdd() ? MIN_VALUE : ZERO;
      if (this.isNegative()) {
        if (multiplier.isNegative())
          return this.neg().mul(multiplier.neg());
        else
          return this.neg().mul(multiplier).neg();
      } else if (multiplier.isNegative())
        return this.mul(multiplier.neg()).neg();
      if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
        return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
      var a48 = this.high >>> 16;
      var a32 = this.high & 65535;
      var a16 = this.low >>> 16;
      var a00 = this.low & 65535;
      var b48 = multiplier.high >>> 16;
      var b32 = multiplier.high & 65535;
      var b16 = multiplier.low >>> 16;
      var b00 = multiplier.low & 65535;
      var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
      c00 += a00 * b00;
      c16 += c00 >>> 16;
      c00 &= 65535;
      c16 += a16 * b00;
      c32 += c16 >>> 16;
      c16 &= 65535;
      c16 += a00 * b16;
      c32 += c16 >>> 16;
      c16 &= 65535;
      c32 += a32 * b00;
      c48 += c32 >>> 16;
      c32 &= 65535;
      c32 += a16 * b16;
      c48 += c32 >>> 16;
      c32 &= 65535;
      c32 += a00 * b32;
      c48 += c32 >>> 16;
      c32 &= 65535;
      c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
      c48 &= 65535;
      return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
    };
    LongPrototype.mul = LongPrototype.multiply;
    LongPrototype.divide = function divide(divisor) {
      if (!isLong(divisor))
        divisor = fromValue(divisor);
      if (divisor.isZero())
        throw Error("division by zero");
      if (wasm) {
        if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) {
          return this;
        }
        var low = (this.unsigned ? wasm.div_u : wasm.div_s)(
          this.low,
          this.high,
          divisor.low,
          divisor.high
        );
        return fromBits(low, wasm.get_high(), this.unsigned);
      }
      if (this.isZero())
        return this.unsigned ? UZERO : ZERO;
      var approx, rem, res;
      if (!this.unsigned) {
        if (this.eq(MIN_VALUE)) {
          if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
            return MIN_VALUE;
          else if (divisor.eq(MIN_VALUE))
            return ONE;
          else {
            var halfThis = this.shr(1);
            approx = halfThis.div(divisor).shl(1);
            if (approx.eq(ZERO)) {
              return divisor.isNegative() ? ONE : NEG_ONE;
            } else {
              rem = this.sub(divisor.mul(approx));
              res = approx.add(rem.div(divisor));
              return res;
            }
          }
        } else if (divisor.eq(MIN_VALUE))
          return this.unsigned ? UZERO : ZERO;
        if (this.isNegative()) {
          if (divisor.isNegative())
            return this.neg().div(divisor.neg());
          return this.neg().div(divisor).neg();
        } else if (divisor.isNegative())
          return this.div(divisor.neg()).neg();
        res = ZERO;
      } else {
        if (!divisor.unsigned)
          divisor = divisor.toUnsigned();
        if (divisor.gt(this))
          return UZERO;
        if (divisor.gt(this.shru(1)))
          return UONE;
        res = UZERO;
      }
      rem = this;
      while (rem.gte(divisor)) {
        approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
        var log2 = Math.ceil(Math.log(approx) / Math.LN2), delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48), approxRes = fromNumber(approx), approxRem = approxRes.mul(divisor);
        while (approxRem.isNegative() || approxRem.gt(rem)) {
          approx -= delta;
          approxRes = fromNumber(approx, this.unsigned);
          approxRem = approxRes.mul(divisor);
        }
        if (approxRes.isZero())
          approxRes = ONE;
        res = res.add(approxRes);
        rem = rem.sub(approxRem);
      }
      return res;
    };
    LongPrototype.div = LongPrototype.divide;
    LongPrototype.modulo = function modulo(divisor) {
      if (!isLong(divisor))
        divisor = fromValue(divisor);
      if (wasm) {
        var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(
          this.low,
          this.high,
          divisor.low,
          divisor.high
        );
        return fromBits(low, wasm.get_high(), this.unsigned);
      }
      return this.sub(this.div(divisor).mul(divisor));
    };
    LongPrototype.mod = LongPrototype.modulo;
    LongPrototype.rem = LongPrototype.modulo;
    LongPrototype.not = function not() {
      return fromBits(~this.low, ~this.high, this.unsigned);
    };
    LongPrototype.and = function and(other) {
      if (!isLong(other))
        other = fromValue(other);
      return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
    };
    LongPrototype.or = function or(other) {
      if (!isLong(other))
        other = fromValue(other);
      return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
    };
    LongPrototype.xor = function xor(other) {
      if (!isLong(other))
        other = fromValue(other);
      return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
    };
    LongPrototype.shiftLeft = function shiftLeft(numBits) {
      if (isLong(numBits))
        numBits = numBits.toInt();
      if ((numBits &= 63) === 0)
        return this;
      else if (numBits < 32)
        return fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned);
      else
        return fromBits(0, this.low << numBits - 32, this.unsigned);
    };
    LongPrototype.shl = LongPrototype.shiftLeft;
    LongPrototype.shiftRight = function shiftRight(numBits) {
      if (isLong(numBits))
        numBits = numBits.toInt();
      if ((numBits &= 63) === 0)
        return this;
      else if (numBits < 32)
        return fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned);
      else
        return fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned);
    };
    LongPrototype.shr = LongPrototype.shiftRight;
    LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
      if (isLong(numBits))
        numBits = numBits.toInt();
      numBits &= 63;
      if (numBits === 0)
        return this;
      else {
        var high = this.high;
        if (numBits < 32) {
          var low = this.low;
          return fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits, this.unsigned);
        } else if (numBits === 32)
          return fromBits(high, 0, this.unsigned);
        else
          return fromBits(high >>> numBits - 32, 0, this.unsigned);
      }
    };
    LongPrototype.shru = LongPrototype.shiftRightUnsigned;
    LongPrototype.shr_u = LongPrototype.shiftRightUnsigned;
    LongPrototype.toSigned = function toSigned() {
      if (!this.unsigned)
        return this;
      return fromBits(this.low, this.high, false);
    };
    LongPrototype.toUnsigned = function toUnsigned() {
      if (this.unsigned)
        return this;
      return fromBits(this.low, this.high, true);
    };
    LongPrototype.toBytes = function toBytes(le) {
      return le ? this.toBytesLE() : this.toBytesBE();
    };
    LongPrototype.toBytesLE = function toBytesLE() {
      var hi = this.high, lo = this.low;
      return [
        lo & 255,
        lo >>> 8 & 255,
        lo >>> 16 & 255,
        lo >>> 24,
        hi & 255,
        hi >>> 8 & 255,
        hi >>> 16 & 255,
        hi >>> 24
      ];
    };
    LongPrototype.toBytesBE = function toBytesBE() {
      var hi = this.high, lo = this.low;
      return [
        hi >>> 24,
        hi >>> 16 & 255,
        hi >>> 8 & 255,
        hi & 255,
        lo >>> 24,
        lo >>> 16 & 255,
        lo >>> 8 & 255,
        lo & 255
      ];
    };
    Long.fromBytes = function fromBytes(bytes, unsigned, le) {
      return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
    };
    Long.fromBytesLE = function fromBytesLE(bytes, unsigned) {
      return new Long(
        bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24,
        bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24,
        unsigned
      );
    };
    Long.fromBytesBE = function fromBytesBE(bytes, unsigned) {
      return new Long(
        bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7],
        bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3],
        unsigned
      );
    };
  }
});

// node_modules/@tensorflow/tfjs-layers/dist/tf-layers.node.js
var require_tf_layers_node = __commonJS({
  "node_modules/@tensorflow/tfjs-layers/dist/tf-layers.node.js"(exports2) {
    "use strict";
    var tfc = require_tf_core_node();
    function _interopNamespaceDefault(e) {
      var n = /* @__PURE__ */ Object.create(null);
      if (e) {
        Object.keys(e).forEach(function(k) {
          if (k !== "default") {
            var d = Object.getOwnPropertyDescriptor(e, k);
            Object.defineProperty(n, k, d.get ? d : {
              enumerable: true,
              get: function() {
                return e[k];
              }
            });
          }
        });
      }
      n.default = e;
      return n;
    }
    function _mergeNamespaces(n, m) {
      m.forEach(function(e) {
        e && typeof e !== "string" && !Array.isArray(e) && Object.keys(e).forEach(function(k) {
          if (k !== "default" && !(k in n)) {
            var d = Object.getOwnPropertyDescriptor(e, k);
            Object.defineProperty(n, k, d.get ? d : {
              enumerable: true,
              get: function() {
                return e[k];
              }
            });
          }
        });
      });
      return n;
    }
    var tfc__namespace = /* @__PURE__ */ _interopNamespaceDefault(tfc);
    var extendStatics = function(d, b) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
        d2.__proto__ = b2;
      } || function(d2, b2) {
        for (var p in b2)
          if (Object.prototype.hasOwnProperty.call(b2, p))
            d2[p] = b2[p];
      };
      return extendStatics(d, b);
    };
    function __extends(d, b) {
      if (typeof b !== "function" && b !== null)
        throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
      extendStatics(d, b);
      function __() {
        this.constructor = d;
      }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }
    function __awaiter(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step2(generator.next(value));
          } catch (e) {
            reject(e);
          }
        }
        function rejected(value) {
          try {
            step2(generator["throw"](value));
          } catch (e) {
            reject(e);
          }
        }
        function step2(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step2((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    }
    function __generator(thisArg, body) {
      var _ = { label: 0, sent: function() {
        if (t[0] & 1)
          throw t[1];
        return t[1];
      }, trys: [], ops: [] }, f, y, t, g;
      return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
        return this;
      }), g;
      function verb(n) {
        return function(v) {
          return step2([n, v]);
        };
      }
      function step2(op2) {
        if (f)
          throw new TypeError("Generator is already executing.");
        while (_)
          try {
            if (f = 1, y && (t = op2[0] & 2 ? y["return"] : op2[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op2[1])).done)
              return t;
            if (y = 0, t)
              op2 = [op2[0] & 2, t.value];
            switch (op2[0]) {
              case 0:
              case 1:
                t = op2;
                break;
              case 4:
                _.label++;
                return { value: op2[1], done: false };
              case 5:
                _.label++;
                y = op2[1];
                op2 = [0];
                continue;
              case 7:
                op2 = _.ops.pop();
                _.trys.pop();
                continue;
              default:
                if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op2[0] === 6 || op2[0] === 2)) {
                  _ = 0;
                  continue;
                }
                if (op2[0] === 3 && (!t || op2[1] > t[0] && op2[1] < t[3])) {
                  _.label = op2[1];
                  break;
                }
                if (op2[0] === 6 && _.label < t[1]) {
                  _.label = t[1];
                  t = op2;
                  break;
                }
                if (t && _.label < t[2]) {
                  _.label = t[2];
                  _.ops.push(op2);
                  break;
                }
                if (t[2])
                  _.ops.pop();
                _.trys.pop();
                continue;
            }
            op2 = body.call(thisArg, _);
          } catch (e) {
            op2 = [6, e];
            y = 0;
          } finally {
            f = t = 0;
          }
        if (op2[0] & 5)
          throw op2[1];
        return { value: op2[0] ? op2[1] : void 0, done: true };
      }
    }
    function __values(o) {
      var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
      if (m)
        return m.call(o);
      if (o && typeof o.length === "number")
        return {
          next: function() {
            if (o && i >= o.length)
              o = void 0;
            return { value: o && o[i++], done: !o };
          }
        };
      throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    }
    function __read(o, n) {
      var m = typeof Symbol === "function" && o[Symbol.iterator];
      if (!m)
        return o;
      var i = m.call(o), r, ar = [], e;
      try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
          ar.push(r.value);
      } catch (error) {
        e = { error };
      } finally {
        try {
          if (r && !r.done && (m = i["return"]))
            m.call(i);
        } finally {
          if (e)
            throw e.error;
        }
      }
      return ar;
    }
    function __spreadArray(to, from, pack) {
      if (pack || arguments.length === 2)
        for (var i = 0, l = from.length, ar; i < l; i++) {
          if (ar || !(i in from)) {
            if (!ar)
              ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
          }
        }
      return to.concat(ar || Array.prototype.slice.call(from));
    }
    var AttributeError = (
      /** @class */
      function(_super) {
        __extends(AttributeError2, _super);
        function AttributeError2(message) {
          var _this = _super.call(this, message) || this;
          Object.setPrototypeOf(_this, AttributeError2.prototype);
          return _this;
        }
        return AttributeError2;
      }(Error)
    );
    var RuntimeError = (
      /** @class */
      function(_super) {
        __extends(RuntimeError2, _super);
        function RuntimeError2(message) {
          var _this = _super.call(this, message) || this;
          Object.setPrototypeOf(_this, RuntimeError2.prototype);
          return _this;
        }
        return RuntimeError2;
      }(Error)
    );
    var ValueError = (
      /** @class */
      function(_super) {
        __extends(ValueError2, _super);
        function ValueError2(message) {
          var _this = _super.call(this, message) || this;
          Object.setPrototypeOf(_this, ValueError2.prototype);
          return _this;
        }
        return ValueError2;
      }(Error)
    );
    var NotImplementedError = (
      /** @class */
      function(_super) {
        __extends(NotImplementedError2, _super);
        function NotImplementedError2(message) {
          var _this = _super.call(this, message) || this;
          Object.setPrototypeOf(_this, NotImplementedError2.prototype);
          return _this;
        }
        return NotImplementedError2;
      }(Error)
    );
    var AssertionError = (
      /** @class */
      function(_super) {
        __extends(AssertionError2, _super);
        function AssertionError2(message) {
          var _this = _super.call(this, message) || this;
          Object.setPrototypeOf(_this, AssertionError2.prototype);
          return _this;
        }
        return AssertionError2;
      }(Error)
    );
    (function(_super) {
      __extends(IndexError, _super);
      function IndexError(message) {
        var _this = _super.call(this, message) || this;
        Object.setPrototypeOf(_this, IndexError.prototype);
        return _this;
      }
      return IndexError;
    })(Error);
    var LruCache = (
      /** @class */
      function() {
        function LruCache2(maxEntries) {
          this.maxEntries = maxEntries || 100;
          this.cache = /* @__PURE__ */ new Map();
        }
        LruCache2.prototype.get = function(key) {
          var entry;
          if (this.cache.has(key)) {
            entry = this.cache.get(key);
            this.cache.delete(key);
            this.cache.set(key, entry);
          }
          return entry;
        };
        LruCache2.prototype.put = function(key, value) {
          if (this.cache.has(key)) {
            this.cache.delete(key);
          } else if (this.cache.size >= this.maxEntries) {
            var keyToDelete = this.cache.keys().next().value;
            this.cache.delete(keyToDelete);
          }
          this.cache.set(key, value);
        };
        LruCache2.prototype.getMaxEntries = function() {
          return this.maxEntries;
        };
        LruCache2.prototype.setMaxEntries = function(maxEntries) {
          if (maxEntries < 0) {
            throw new Error("The maxEntries of LRU caches must be at least 0, but got ".concat(maxEntries, "."));
          }
          if (this.maxEntries > maxEntries) {
            for (var i = 0; i < this.maxEntries - maxEntries; i++) {
              var keyToDelete = this.cache.keys().next().value;
              this.cache.delete(keyToDelete);
            }
          }
          this.maxEntries = maxEntries;
        };
        return LruCache2;
      }()
    );
    function pyListRepeat(value, numValues) {
      if (Array.isArray(value)) {
        var newArray = [];
        for (var i = 0; i < numValues; i++) {
          newArray = newArray.concat(value);
        }
        return newArray;
      } else {
        var newArray = new Array(numValues);
        newArray.fill(value);
        return newArray;
      }
    }
    function assert$1(val, message) {
      if (!val) {
        throw new AssertionError(message);
      }
    }
    function count(array, refernce) {
      var e_12, _a2;
      var counter = 0;
      try {
        for (var array_1 = __values(array), array_1_1 = array_1.next(); !array_1_1.done; array_1_1 = array_1.next()) {
          var item = array_1_1.value;
          if (item === refernce) {
            counter++;
          }
        }
      } catch (e_1_1) {
        e_12 = { error: e_1_1 };
      } finally {
        try {
          if (array_1_1 && !array_1_1.done && (_a2 = array_1.return)) _a2.call(array_1);
        } finally {
          if (e_12) throw e_12.error;
        }
      }
      return counter;
    }
    function singletonOrArray(xs) {
      if (xs.length === 1) {
        return xs[0];
      }
      return xs;
    }
    function toList(x) {
      if (Array.isArray(x)) {
        return x;
      }
      return [x];
    }
    function toSnakeCase(name) {
      var intermediate = name.replace(/(.)([A-Z][a-z0-9]+)/g, "$1_$2");
      var insecure = intermediate.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
      if (insecure[0] !== "_") {
        return insecure;
      }
      return "private" + insecure;
    }
    function toCamelCase(identifier) {
      if (identifier.length <= 1) {
        return identifier;
      }
      if (identifier.indexOf("_") === -1) {
        return identifier;
      }
      return identifier.replace(/[_]+(\w|$)/g, function(m, p1) {
        return p1.toUpperCase();
      });
    }
    var _GLOBAL_CUSTOM_OBJECTS = {};
    function serializeKerasObject(instance) {
      if (instance === null || instance === void 0) {
        return null;
      }
      var dict = {};
      dict["className"] = instance.getClassName();
      dict["config"] = instance.getConfig();
      return dict;
    }
    function convertNDArrayScalarsInConfig(config) {
      var e_3, _a2;
      if (config == null || typeof config !== "object") {
        return;
      } else if (Array.isArray(config)) {
        config.forEach(function(configItem) {
          return convertNDArrayScalarsInConfig(configItem);
        });
      } else {
        var fields = Object.keys(config);
        try {
          for (var fields_1 = __values(fields), fields_1_1 = fields_1.next(); !fields_1_1.done; fields_1_1 = fields_1.next()) {
            var field = fields_1_1.value;
            var value = config[field];
            if (value != null && typeof value === "object") {
              if (!Array.isArray(value) && value["type"] === "ndarray" && typeof value["value"] === "number") {
                config[field] = value["value"];
              } else {
                convertNDArrayScalarsInConfig(value);
              }
            }
          }
        } catch (e_3_1) {
          e_3 = { error: e_3_1 };
        } finally {
          try {
            if (fields_1_1 && !fields_1_1.done && (_a2 = fields_1.return)) _a2.call(fields_1);
          } finally {
            if (e_3) throw e_3.error;
          }
        }
      }
    }
    function deserializeKerasObject(identifier, moduleObjects, customObjects, printableModuleName, fastWeightInit) {
      var _a2, _b, _c, e_4, _d, e_5, _e, e_6, _f, e_7, _g;
      if (moduleObjects === void 0) {
        moduleObjects = {};
      }
      if (customObjects === void 0) {
        customObjects = {};
      }
      if (printableModuleName === void 0) {
        printableModuleName = "object";
      }
      if (fastWeightInit === void 0) {
        fastWeightInit = false;
      }
      if (typeof identifier === "string") {
        var functionName = identifier;
        var fn = void 0;
        if (functionName in customObjects) {
          fn = customObjects[functionName];
        } else if (functionName in _GLOBAL_CUSTOM_OBJECTS) {
          fn = _GLOBAL_CUSTOM_OBJECTS[functionName];
        } else {
          fn = moduleObjects[functionName];
          if (fn == null) {
            throw new ValueError("Unknown ".concat(printableModuleName, ": ").concat(identifier, ". ") + "This may be due to one of the following reasons:\n" + "1. The ".concat(printableModuleName, " is defined in Python, in which ") + "case it needs to be ported to TensorFlow.js or your JavaScript code.\n" + "2. The custom ".concat(printableModuleName, " is defined in JavaScript, ") + "but is not registered properly with tf.serialization.registerClass().");
          }
        }
        return fn;
      } else {
        var config = identifier;
        if (config["className"] == null || config["config"] == null) {
          throw new ValueError("".concat(printableModuleName, ": Improper config format: ") + "".concat(JSON.stringify(config), ".\n") + "'className' and 'config' must set.");
        }
        var className = config["className"];
        var cls = void 0, fromConfig = void 0;
        if (className in customObjects) {
          _a2 = __read(customObjects[className], 2), cls = _a2[0], fromConfig = _a2[1];
        } else if (className in _GLOBAL_CUSTOM_OBJECTS) {
          _b = __read(_GLOBAL_CUSTOM_OBJECTS["className"], 2), cls = _b[0], fromConfig = _b[1];
        } else if (className in moduleObjects) {
          _c = __read(moduleObjects[className], 2), cls = _c[0], fromConfig = _c[1];
        }
        if (cls == null) {
          throw new ValueError("Unknown ".concat(printableModuleName, ": ").concat(className, ". ") + "This may be due to one of the following reasons:\n" + "1. The ".concat(printableModuleName, " is defined in Python, in which ") + "case it needs to be ported to TensorFlow.js or your JavaScript code.\n" + "2. The custom ".concat(printableModuleName, " is defined in JavaScript, ") + "but is not registered properly with tf.serialization.registerClass().");
        }
        if (fromConfig != null) {
          var customObjectsCombined = {};
          try {
            for (var _h = __values(Object.keys(_GLOBAL_CUSTOM_OBJECTS)), _j = _h.next(); !_j.done; _j = _h.next()) {
              var key = _j.value;
              customObjectsCombined[key] = _GLOBAL_CUSTOM_OBJECTS[key];
            }
          } catch (e_4_1) {
            e_4 = { error: e_4_1 };
          } finally {
            try {
              if (_j && !_j.done && (_d = _h.return)) _d.call(_h);
            } finally {
              if (e_4) throw e_4.error;
            }
          }
          try {
            for (var _k = __values(Object.keys(customObjects)), _l = _k.next(); !_l.done; _l = _k.next()) {
              var key = _l.value;
              customObjectsCombined[key] = customObjects[key];
            }
          } catch (e_5_1) {
            e_5 = { error: e_5_1 };
          } finally {
            try {
              if (_l && !_l.done && (_e = _k.return)) _e.call(_k);
            } finally {
              if (e_5) throw e_5.error;
            }
          }
          var nestedConfig = config["config"];
          nestedConfig["customObjects"] = customObjectsCombined;
          var backupCustomObjects = Object.assign({}, _GLOBAL_CUSTOM_OBJECTS);
          try {
            for (var _m = __values(Object.keys(customObjects)), _o = _m.next(); !_o.done; _o = _m.next()) {
              var key = _o.value;
              _GLOBAL_CUSTOM_OBJECTS[key] = customObjects[key];
            }
          } catch (e_6_1) {
            e_6 = { error: e_6_1 };
          } finally {
            try {
              if (_o && !_o.done && (_f = _m.return)) _f.call(_m);
            } finally {
              if (e_6) throw e_6.error;
            }
          }
          convertNDArrayScalarsInConfig(config["config"]);
          var returnObj = fromConfig(cls, config["config"], customObjects, fastWeightInit);
          _GLOBAL_CUSTOM_OBJECTS = Object.assign({}, backupCustomObjects);
          return returnObj;
        } else {
          var backupCustomObjects = Object.assign({}, _GLOBAL_CUSTOM_OBJECTS);
          try {
            for (var _p = __values(Object.keys(customObjects)), _q = _p.next(); !_q.done; _q = _p.next()) {
              var key = _q.value;
              _GLOBAL_CUSTOM_OBJECTS[key] = customObjects[key];
            }
          } catch (e_7_1) {
            e_7 = { error: e_7_1 };
          } finally {
            try {
              if (_q && !_q.done && (_g = _p.return)) _g.call(_p);
            } finally {
              if (e_7) throw e_7.error;
            }
          }
          var returnObj = new cls(config["config"]);
          _GLOBAL_CUSTOM_OBJECTS = Object.assign({}, backupCustomObjects);
          return returnObj;
        }
      }
    }
    function numberCompare(a, b) {
      return a < b ? -1 : a > b ? 1 : 0;
    }
    function reverseNumberCompare(a, b) {
      return -1 * numberCompare(a, b);
    }
    function unique(xs) {
      var e_8, _a2;
      if (xs == null) {
        return xs;
      }
      var out = [];
      try {
        for (var xs_1 = __values(xs), xs_1_1 = xs_1.next(); !xs_1_1.done; xs_1_1 = xs_1.next()) {
          var x = xs_1_1.value;
          if (out.indexOf(x) === -1) {
            out.push(x);
          }
        }
      } catch (e_8_1) {
        e_8 = { error: e_8_1 };
      } finally {
        try {
          if (xs_1_1 && !xs_1_1.done && (_a2 = xs_1.return)) _a2.call(xs_1);
        } finally {
          if (e_8) throw e_8.error;
        }
      }
      return out;
    }
    function isObjectEmpty(obj) {
      if (obj == null) {
        throw new ValueError("Invalid value in obj: ".concat(JSON.stringify(obj)));
      }
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }
      return true;
    }
    function checkStringTypeUnionValue(values, label, value) {
      if (value == null) {
        return;
      }
      if (values.indexOf(value) < 0) {
        throw new ValueError("".concat(value, " is not a valid ").concat(label, ".  Valid values are ").concat(values, " or null/undefined."));
      }
    }
    function checkArrayTypeAndLength(x, expectedType, minLength, maxLength) {
      if (minLength === void 0) {
        minLength = 0;
      }
      if (maxLength === void 0) {
        maxLength = Infinity;
      }
      assert$1(minLength >= 0);
      assert$1(maxLength >= minLength);
      return Array.isArray(x) && x.length >= minLength && x.length <= maxLength && x.every(function(e) {
        return typeof e === expectedType;
      });
    }
    function assertPositiveInteger(value, name) {
      if (Array.isArray(value)) {
        tfc.util.assert(value.length > 0, function() {
          return "".concat(name, " is unexpectedly an empty array.");
        });
        value.forEach(function(v, i) {
          return assertPositiveInteger(v, "element ".concat(i + 1, " of ").concat(name));
        });
      } else {
        tfc.util.assert(Number.isInteger(value) && value > 0, function() {
          return "Expected ".concat(name, " to be a positive integer, but got ") + "".concat(formatAsFriendlyString(value), ".");
        });
      }
    }
    function formatAsFriendlyString(value) {
      if (value === null) {
        return "null";
      } else if (Array.isArray(value)) {
        return "[" + value.map(function(v) {
          return formatAsFriendlyString(v);
        }).join(",") + "]";
      } else if (typeof value === "string") {
        return '"'.concat(value, '"');
      } else {
        return "".concat(value);
      }
    }
    function debounce(f, waitMs, nowFunc) {
      var lastTime = nowFunc != null ? nowFunc() : tfc.util.now();
      var lastResult;
      var f2 = function() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        var now2 = nowFunc != null ? nowFunc() : tfc.util.now();
        if (now2 - lastTime < waitMs) {
          return lastResult;
        }
        lastTime = now2;
        lastResult = f.apply(void 0, __spreadArray([], __read(args), false));
        return lastResult;
      };
      return f2;
    }
    function mapActivationToFusedKernel(activationName) {
      if (activationName === "relu") {
        return "relu";
      }
      if (activationName === "linear") {
        return "linear";
      }
      if (activationName === "elu") {
        return "elu";
      }
      return null;
    }
    var _nextUniqueTensorId = 0;
    function getNextUniqueTensorId() {
      return _nextUniqueTensorId++;
    }
    var _uidPrefixes = {};
    function getUid(prefix) {
      if (prefix === void 0) {
        prefix = "";
      }
      if (!(prefix in _uidPrefixes)) {
        _uidPrefixes[prefix] = 0;
      }
      _uidPrefixes[prefix] += 1;
      return prefix + _uidPrefixes[prefix].toString();
    }
    var VALID_DATA_FORMAT_VALUES = ["channelsFirst", "channelsLast"];
    var VALID_INTERPOLATION_FORMAT_VALUES = ["nearest", "bilinear"];
    var VALID_PADDING_MODE_VALUES = ["valid", "same", "causal"];
    var VALID_POOL_MODE_VALUES = ["max", "avg"];
    var VALID_BIDIRECTIONAL_MERGE_MODES = ["sum", "mul", "concat", "ave"];
    var nameMap = /* @__PURE__ */ new Map();
    function checkDataFormat(value) {
      checkStringTypeUnionValue(VALID_DATA_FORMAT_VALUES, "DataFormat", value);
    }
    function checkInterpolationFormat(value) {
      checkStringTypeUnionValue(VALID_INTERPOLATION_FORMAT_VALUES, "InterpolationFormat", value);
    }
    function checkPaddingMode(value) {
      checkStringTypeUnionValue(VALID_PADDING_MODE_VALUES, "PaddingMode", value);
    }
    function checkPoolMode(value) {
      checkStringTypeUnionValue(VALID_POOL_MODE_VALUES, "PoolMode", value);
    }
    var _nameScopeStack = [];
    var _nameScopeDivider = "/";
    function nameScope(name, fn) {
      _nameScopeStack.push(name);
      try {
        var val = fn();
        _nameScopeStack.pop();
        return val;
      } catch (e) {
        _nameScopeStack.pop();
        throw e;
      }
    }
    function currentNameScopePrefix() {
      if (_nameScopeStack.length === 0) {
        return "";
      } else {
        return _nameScopeStack.join(_nameScopeDivider) + _nameScopeDivider;
      }
    }
    function getScopedTensorName(tensorName) {
      if (!isValidTensorName(tensorName)) {
        throw new Error("Not a valid tensor name: '" + tensorName + "'");
      }
      return currentNameScopePrefix() + tensorName;
    }
    function getUniqueTensorName(scopedName) {
      if (!isValidTensorName(scopedName)) {
        throw new Error("Not a valid tensor name: '" + scopedName + "'");
      }
      if (!nameMap.has(scopedName)) {
        nameMap.set(scopedName, 0);
      }
      var index = nameMap.get(scopedName);
      nameMap.set(scopedName, nameMap.get(scopedName) + 1);
      if (index > 0) {
        var result = "".concat(scopedName, "_").concat(index);
        nameMap.set(result, 1);
        return result;
      } else {
        return scopedName;
      }
    }
    var tensorNameRegex = new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);
    function isValidTensorName(name) {
      return !!name.match(tensorNameRegex);
    }
    function isInteger(x) {
      return x === parseInt(x.toString(), 10);
    }
    function arrayProd(array, begin, end) {
      if (begin == null) {
        begin = 0;
      }
      if (end == null) {
        end = array.length;
      }
      var prod = 1;
      for (var i = begin; i < end; ++i) {
        prod *= array[i];
      }
      return prod;
    }
    function min(array) {
      if (array.length === 0) {
        return Number.NaN;
      }
      var min2 = Number.POSITIVE_INFINITY;
      for (var i = 0; i < array.length; i++) {
        var value = array[i];
        if (value < min2) {
          min2 = value;
        }
      }
      return min2;
    }
    function max(array) {
      if (array.length === 0) {
        return Number.NaN;
      }
      var max2 = Number.NEGATIVE_INFINITY;
      for (var i = 0; i < array.length; i++) {
        var value = array[i];
        if (value > max2) {
          max2 = value;
        }
      }
      return max2;
    }
    function range(begin, end) {
      if (end < begin) {
        throw new ValueError("end (".concat(end, ") < begin (").concat(begin, ") is forbidden."));
      }
      var out = [];
      for (var i = begin; i < end; ++i) {
        out.push(i);
      }
      return out;
    }
    var _epsilon;
    function epsilon() {
      if (_epsilon == null) {
        _epsilon = tfc.backend().epsilon();
      }
      return _epsilon;
    }
    function imageDataFormat() {
      return "channelsLast";
    }
    function cast$1(x, dtype) {
      return tfc__namespace.cast(x, dtype);
    }
    function expandDims$1(x, axis) {
      if (axis === void 0) {
        axis = -1;
      }
      var outShape = x.shape.slice();
      if (axis < 0) {
        axis = outShape.length + axis + 1;
      }
      outShape.splice(axis, 0, 1);
      return tfc__namespace.reshape(x, outShape);
    }
    function repeat(x, n) {
      return tfc.tidy(function() {
        if (x.shape.length !== 2) {
          throw new ValueError("repeat() expects a rank-2 tensor, but received a " + "rank-".concat(x.shape.length, " tensor."));
        }
        var y = expandDims$1(x, 1);
        return tile$1(y, [1, n, 1]);
      });
    }
    function flatten$2(x) {
      var newShape = [arrayProd(x.shape)];
      return tfc__namespace.reshape(x, newShape);
    }
    function batchFlatten(x) {
      if (x.rank <= 1) {
        throw new ValueError("batchFlatten requires a minimum rank of 2. Got rank: ".concat(x.rank, "."));
      }
      var newShape = [x.shape[0], arrayProd(x.shape, 1)];
      return tfc__namespace.reshape(x, newShape);
    }
    function sliceAlongFirstAxis(array, start, size) {
      return tfc.tidy(function() {
        switch (array.rank) {
          case 1:
            return tfc__namespace.slice1d(array, start, size);
          case 2:
            return tfc__namespace.slice2d(array, [start, 0], [size, array.shape[1]]);
          case 3:
            return tfc__namespace.slice3d(array, [start, 0, 0], [size, array.shape[1], array.shape[2]]);
          case 4:
            return tfc__namespace.slice4d(array, [start, 0, 0, 0], [size, array.shape[1], array.shape[2], array.shape[3]]);
          case 5:
            return tfc__namespace.slice(array, [start, 0, 0, 0, 0], [
              size,
              array.shape[1],
              array.shape[2],
              array.shape[3],
              array.shape[4]
            ]);
          case 6:
            return tfc__namespace.slice(array, [start, 0, 0, 0, 0, 0], [
              size,
              array.shape[1],
              array.shape[2],
              array.shape[3],
              array.shape[4],
              array.shape[5]
            ]);
          default:
            throw new ValueError("sliceAlongFirstAxis() received an unsupported tensor rank: " + "".concat(array.rank));
        }
      });
    }
    function sliceAlongLastAxis(array, start, size) {
      return tfc.tidy(function() {
        switch (array.rank) {
          case 1:
            return tfc__namespace.slice1d(array, start, size);
          case 2:
            return tfc__namespace.slice2d(array, [0, start], [array.shape[0], size]);
          case 3:
            return tfc__namespace.slice3d(array, [0, 0, start], [array.shape[0], array.shape[1], size]);
          case 4:
            return tfc__namespace.slice4d(array, [0, 0, 0, start], [array.shape[0], array.shape[1], array.shape[2], size]);
          default:
            throw new ValueError("sliceAlongLastAxis() received an unsupported tensor rank: " + "".concat(array.rank));
        }
      });
    }
    function sliceAlongAxis(array, start, size, axis) {
      return tfc.tidy(function() {
        switch (array.rank) {
          case 1:
            return tfc__namespace.slice1d(array, start, size);
          case 2:
            switch (axis) {
              case 1:
                return sliceAlongFirstAxis(array, start, size);
              case 2:
                return sliceAlongLastAxis(array, start, size);
              default:
                throw new ValueError("The axis is not within the rank of the tensor " + "".concat(axis));
            }
          case 3:
            switch (axis) {
              case 1:
                return sliceAlongFirstAxis(array, start, size);
              case 2:
                return tfc__namespace.slice3d(array, [0, start, 0], [array.shape[0], size, array.shape[2]]);
              case 3:
                return sliceAlongLastAxis(array, start, size);
              default:
                throw new ValueError("The axis is not within the rank of the tensor " + "".concat(axis));
            }
          case 4:
            switch (axis) {
              case 1:
                return sliceAlongFirstAxis(array, start, size);
              case 2:
                return tfc__namespace.slice4d(array, [0, start, 0, 0], [array.shape[0], size, array.shape[2], array.shape[3]]);
              case 3:
                return tfc__namespace.slice4d(array, [0, 0, start, 0], [array.shape[0], array.shape[1], size, array.shape[3]]);
              case 4:
                return sliceAlongLastAxis(array, start, size);
              default:
                throw new ValueError("The axis is not within the rank of the tensor " + "".concat(axis));
            }
          default:
            throw new ValueError("sliceAlongLastAxis() received an unsupported tensor rank: " + "".concat(array.rank));
        }
      });
    }
    function concatenate$1(tensors, axis) {
      if (axis === void 0) {
        axis = -1;
      }
      var rank;
      if (axis < 0) {
        rank = tensors[0].rank;
        if (rank !== 0) {
          axis = rank;
        } else {
          axis = 0;
        }
      }
      if (axis === tensors[0].rank) {
        axis = -1;
      }
      return tfc__namespace.concat(tensors, axis);
    }
    function concatAlongFirstAxis(a, b) {
      switch (a.rank) {
        case 1:
          return tfc__namespace.concat1d([a, b]);
        case 2:
          return tfc__namespace.concat2d([a, b], 0);
        case 3:
          return tfc__namespace.concat3d([a, b], 0);
        case 4:
          return tfc__namespace.concat4d([a, b], 0);
        default:
          throw new ValueError("concatAlongFirstAxis() received an unsupported " + "tensor rank: ".concat(a.rank));
      }
    }
    function tile$1(x, n) {
      if (!Array.isArray(n)) {
        n = [n];
      }
      if (x.rank !== n.length) {
        throw new ValueError("The length of input n (".concat(n.length, ") does not match ") + "the number of dimensions in input x (".concat(x.rank, ")"));
      }
      return tfc__namespace.tile(x, n);
    }
    function randomNormal$1(shape, mean, stddev, dtype, seed) {
      if (mean === void 0) {
        mean = 0;
      }
      if (stddev === void 0) {
        stddev = 1;
      }
      return tfc__namespace.randomNormal(shape, mean, stddev, dtype, seed);
    }
    function dot$1(a, b, activation2, bias) {
      if (a.rank < 2 || b.rank < 2) {
        throw new NotImplementedError("dot requires both inputs to be rank >= 2" + " but got x shape = ".concat(a.shape, " and y shape = ").concat(b.shape));
      }
      if (b.rank >= 3) {
        var xLastDim = a.shape.slice(-1)[0];
        var ySecondLastDim = b.shape.slice(-2)[0];
        if (xLastDim !== ySecondLastDim) {
          throw new NotImplementedError("If rank y >= 3, then the second last dim" + " of y must equal the last dim of x but got x shape = ".concat(a.shape, " and ") + " y shape = ".concat(b.shape));
        }
      }
      if (a.rank === 2 && b.rank === 2) {
        var transposeA = false;
        var transposeB = false;
        return tfc__namespace.fused.matMul({
          a,
          b,
          transposeA,
          transposeB,
          bias: bias ? reshapeBias(a.rank, bias, imageDataFormat()) : null,
          activation: activation2
        });
      } else {
        var aFirstDims = a.shape.slice();
        var aLastDim = aFirstDims.pop();
        a = tfc__namespace.reshape(a, [-1, aLastDim]);
        var bShape = b.shape.slice();
        var bLastDim = bShape.pop();
        var ySecondLastDim = bShape.pop();
        var yOtherDims = __spreadArray(__spreadArray([], __read(bShape), false), [bLastDim], false);
        var perm = Array.from({ length: b.rank }, function(_, i) {
          if (i === 0) {
            return b.rank - 2;
          } else if (i <= b.rank - 2) {
            return i - 1;
          }
          return i;
        });
        b = tfc__namespace.reshape(tfc__namespace.transpose(b, perm), [ySecondLastDim, -1]);
        var outputShape = __spreadArray(__spreadArray([], __read(aFirstDims), false), __read(yOtherDims), false);
        var transposeA = false;
        var transposeB = false;
        return tfc__namespace.reshape(tfc__namespace.fused.matMul({
          a,
          b,
          transposeA,
          transposeB,
          bias: bias ? reshapeBias(a.rank, bias, imageDataFormat()) : null,
          activation: activation2
        }), outputShape);
      }
    }
    function gather$1(reference, indices, axis) {
      return tfc.tidy(function() {
        if (Array.isArray(indices)) {
          indices = tfc.tensor1d(indices, "int32");
        } else {
          indices = tfc__namespace.cast(indices, "int32");
        }
        return tfc__namespace.gather(reference, indices, axis);
      });
    }
    function square$1(x) {
      return tfc__namespace.mul(x, x);
    }
    function reshapeBias(xRank, bias, dataFormat) {
      var biasShape = bias.shape;
      if (bias.rank !== 1 && bias.rank !== xRank) {
        throw new ValueError("Unexpected bias dimensions: ".concat(bias.rank) + "; expected it to be 1 or ".concat(xRank));
      }
      if (xRank === 5) {
        if (dataFormat === "channelsFirst") {
          if (biasShape.length === 1) {
            return tfc__namespace.reshape(bias, [1, biasShape[0], 1, 1, 1]);
          } else {
            return tfc__namespace.reshape(bias, [1, biasShape[3], biasShape[0], biasShape[1], biasShape[2]]);
          }
        } else if (dataFormat === "channelsLast") {
          if (biasShape.length === 1) {
            return tfc__namespace.reshape(bias, [1, 1, 1, 1, biasShape[0]]);
          } else {
            return tfc__namespace.reshape(bias, [1].concat(biasShape));
          }
        }
      } else if (xRank === 4) {
        if (dataFormat === "channelsFirst") {
          if (biasShape.length === 1) {
            return tfc__namespace.reshape(bias, [1, biasShape[0], 1, 1]);
          } else {
            return tfc__namespace.reshape(bias, [1, biasShape[2], biasShape[0], biasShape[1]]);
          }
        } else if (dataFormat === "channelsLast") {
          if (biasShape.length === 1) {
            return tfc__namespace.reshape(bias, [1, 1, 1, biasShape[0]]);
          } else {
            return tfc__namespace.reshape(bias, [1].concat(biasShape));
          }
        }
      } else if (xRank === 3) {
        if (dataFormat === "channelsFirst") {
          if (biasShape.length === 1) {
            return tfc__namespace.reshape(bias, [1, biasShape[0], 1]);
          } else {
            return tfc__namespace.reshape(bias, [1, biasShape[1], biasShape[0]]);
          }
        } else if (dataFormat === "channelsLast") {
          if (biasShape.length === 1) {
            return tfc__namespace.reshape(bias, [1, 1, biasShape[0]]);
          } else {
            return tfc__namespace.reshape(bias, [1].concat(biasShape));
          }
        }
      } else if (xRank < 3) {
        return bias;
      }
      throw new ValueError("Unsupported input rank by biasAdd: ".concat(bias.rank));
    }
    function biasAdd(x, bias, dataFormat) {
      return tfc.tidy(function() {
        if (dataFormat == null) {
          dataFormat = imageDataFormat();
        }
        checkDataFormat(dataFormat);
        return tfc__namespace.add(x, reshapeBias(x.rank, bias, dataFormat));
      });
    }
    function elu$1(x, alpha) {
      if (alpha === void 0) {
        alpha = 1;
      }
      if (alpha !== 1) {
        throw new NotImplementedError("Support for alpha values other than 1 (".concat(alpha, ") is not implemented ") + "yet.");
      }
      return tfc__namespace.elu(x);
    }
    function softsign(x) {
      return tfc.tidy(function() {
        return tfc__namespace.div(x, tfc__namespace.add(tfc__namespace.abs(x), 1));
      });
    }
    function dropout$1(x, level, noiseShape, seed) {
      return tfc.tidy(function() {
        return tfc__namespace.dropout(x, level, noiseShape, seed);
      });
    }
    function hardSigmoid(x) {
      return tfc.tidy(function() {
        var y = tfc__namespace.add(0.5, tfc__namespace.mul(0.2, x));
        return tfc__namespace.clipByValue(y, 0, 1);
      });
    }
    function inTrainPhase(x, alt, training) {
      if (training === void 0) {
        training = false;
      }
      return training ? x() : alt();
    }
    var VALID_FAN_MODE_VALUES = ["fanIn", "fanOut", "fanAvg"];
    var VALID_DISTRIBUTION_VALUES = ["normal", "uniform", "truncatedNormal"];
    function checkFanMode(value) {
      checkStringTypeUnionValue(VALID_FAN_MODE_VALUES, "FanMode", value);
    }
    function checkDistribution(value) {
      checkStringTypeUnionValue(VALID_DISTRIBUTION_VALUES, "Distribution", value);
    }
    var Initializer = (
      /** @class */
      function(_super) {
        __extends(Initializer2, _super);
        function Initializer2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Initializer2.prototype.fromConfigUsesCustomObjects = function() {
          return false;
        };
        Initializer2.prototype.getConfig = function() {
          return {};
        };
        return Initializer2;
      }(tfc.serialization.Serializable)
    );
    var Zeros = (
      /** @class */
      function(_super) {
        __extends(Zeros2, _super);
        function Zeros2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Zeros2.prototype.apply = function(shape, dtype) {
          return tfc.zeros(shape, dtype);
        };
        return Zeros2;
      }(Initializer)
    );
    Zeros.className = "Zeros";
    tfc.serialization.registerClass(Zeros);
    var Ones = (
      /** @class */
      function(_super) {
        __extends(Ones2, _super);
        function Ones2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Ones2.prototype.apply = function(shape, dtype) {
          return tfc.ones(shape, dtype);
        };
        return Ones2;
      }(Initializer)
    );
    Ones.className = "Ones";
    tfc.serialization.registerClass(Ones);
    var Constant = (
      /** @class */
      function(_super) {
        __extends(Constant2, _super);
        function Constant2(args) {
          var _this = _super.call(this) || this;
          if (typeof args !== "object") {
            throw new ValueError("Expected argument of type ConstantConfig but got ".concat(args));
          }
          if (args.value === void 0) {
            throw new ValueError("config must have value set but got ".concat(args));
          }
          _this.value = args.value;
          return _this;
        }
        Constant2.prototype.apply = function(shape, dtype) {
          var _this = this;
          return tfc.tidy(function() {
            return tfc.mul(tfc.scalar(_this.value), tfc.ones(shape, dtype));
          });
        };
        Constant2.prototype.getConfig = function() {
          return {
            value: this.value
          };
        };
        return Constant2;
      }(Initializer)
    );
    Constant.className = "Constant";
    tfc.serialization.registerClass(Constant);
    var RandomUniform = (
      /** @class */
      function(_super) {
        __extends(RandomUniform2, _super);
        function RandomUniform2(args) {
          var _this = _super.call(this) || this;
          _this.DEFAULT_MINVAL = -0.05;
          _this.DEFAULT_MAXVAL = 0.05;
          _this.minval = args.minval || _this.DEFAULT_MINVAL;
          _this.maxval = args.maxval || _this.DEFAULT_MAXVAL;
          _this.seed = args.seed;
          return _this;
        }
        RandomUniform2.prototype.apply = function(shape, dtype) {
          return tfc.randomUniform(shape, this.minval, this.maxval, dtype, this.seed);
        };
        RandomUniform2.prototype.getConfig = function() {
          return { minval: this.minval, maxval: this.maxval, seed: this.seed };
        };
        return RandomUniform2;
      }(Initializer)
    );
    RandomUniform.className = "RandomUniform";
    tfc.serialization.registerClass(RandomUniform);
    var RandomNormal = (
      /** @class */
      function(_super) {
        __extends(RandomNormal2, _super);
        function RandomNormal2(args) {
          var _this = _super.call(this) || this;
          _this.DEFAULT_MEAN = 0;
          _this.DEFAULT_STDDEV = 0.05;
          _this.mean = args.mean || _this.DEFAULT_MEAN;
          _this.stddev = args.stddev || _this.DEFAULT_STDDEV;
          _this.seed = args.seed;
          return _this;
        }
        RandomNormal2.prototype.apply = function(shape, dtype) {
          dtype = dtype || "float32";
          if (dtype !== "float32" && dtype !== "int32") {
            throw new NotImplementedError("randomNormal does not support dType ".concat(dtype, "."));
          }
          return randomNormal$1(shape, this.mean, this.stddev, dtype, this.seed);
        };
        RandomNormal2.prototype.getConfig = function() {
          return { mean: this.mean, stddev: this.stddev, seed: this.seed };
        };
        return RandomNormal2;
      }(Initializer)
    );
    RandomNormal.className = "RandomNormal";
    tfc.serialization.registerClass(RandomNormal);
    var TruncatedNormal = (
      /** @class */
      function(_super) {
        __extends(TruncatedNormal2, _super);
        function TruncatedNormal2(args) {
          var _this = _super.call(this) || this;
          _this.DEFAULT_MEAN = 0;
          _this.DEFAULT_STDDEV = 0.05;
          _this.mean = args.mean || _this.DEFAULT_MEAN;
          _this.stddev = args.stddev || _this.DEFAULT_STDDEV;
          _this.seed = args.seed;
          return _this;
        }
        TruncatedNormal2.prototype.apply = function(shape, dtype) {
          dtype = dtype || "float32";
          if (dtype !== "float32" && dtype !== "int32") {
            throw new NotImplementedError("truncatedNormal does not support dType ".concat(dtype, "."));
          }
          return tfc.truncatedNormal(shape, this.mean, this.stddev, dtype, this.seed);
        };
        TruncatedNormal2.prototype.getConfig = function() {
          return { mean: this.mean, stddev: this.stddev, seed: this.seed };
        };
        return TruncatedNormal2;
      }(Initializer)
    );
    TruncatedNormal.className = "TruncatedNormal";
    tfc.serialization.registerClass(TruncatedNormal);
    var Identity$1 = (
      /** @class */
      function(_super) {
        __extends(Identity2, _super);
        function Identity2(args) {
          var _this = _super.call(this) || this;
          _this.gain = args.gain != null ? args.gain : 1;
          return _this;
        }
        Identity2.prototype.apply = function(shape, dtype) {
          var _this = this;
          return tfc.tidy(function() {
            if (shape.length !== 2 || shape[0] !== shape[1]) {
              throw new ValueError("Identity matrix initializer can only be used for 2D square matrices.");
            } else {
              return tfc.mul(_this.gain, tfc.eye(shape[0]));
            }
          });
        };
        Identity2.prototype.getConfig = function() {
          return { gain: this.gain };
        };
        return Identity2;
      }(Initializer)
    );
    Identity$1.className = "Identity";
    tfc.serialization.registerClass(Identity$1);
    function computeFans(shape, dataFormat) {
      if (dataFormat === void 0) {
        dataFormat = "channelsLast";
      }
      var fanIn;
      var fanOut;
      checkDataFormat(dataFormat);
      if (shape.length === 2) {
        fanIn = shape[0];
        fanOut = shape[1];
      } else if ([3, 4, 5].indexOf(shape.length) !== -1) {
        if (dataFormat === "channelsFirst") {
          var receptiveFieldSize = arrayProd(shape, 2);
          fanIn = shape[1] * receptiveFieldSize;
          fanOut = shape[0] * receptiveFieldSize;
        } else if (dataFormat === "channelsLast") {
          var receptiveFieldSize = arrayProd(shape, 0, shape.length - 2);
          fanIn = shape[shape.length - 2] * receptiveFieldSize;
          fanOut = shape[shape.length - 1] * receptiveFieldSize;
        }
      } else {
        var shapeProd = arrayProd(shape);
        fanIn = Math.sqrt(shapeProd);
        fanOut = Math.sqrt(shapeProd);
      }
      return [fanIn, fanOut];
    }
    var VarianceScaling = (
      /** @class */
      function(_super) {
        __extends(VarianceScaling2, _super);
        function VarianceScaling2(args) {
          var _this = _super.call(this) || this;
          if (args.scale < 0) {
            throw new ValueError("scale must be a positive float. Got: ".concat(args.scale));
          }
          _this.scale = args.scale == null ? 1 : args.scale;
          _this.mode = args.mode == null ? "fanIn" : args.mode;
          checkFanMode(_this.mode);
          _this.distribution = args.distribution == null ? "normal" : args.distribution;
          checkDistribution(_this.distribution);
          _this.seed = args.seed;
          return _this;
        }
        VarianceScaling2.prototype.apply = function(shape, dtype) {
          var fans = computeFans(shape);
          var fanIn = fans[0];
          var fanOut = fans[1];
          var scale = this.scale;
          if (this.mode === "fanIn") {
            scale /= Math.max(1, fanIn);
          } else if (this.mode === "fanOut") {
            scale /= Math.max(1, fanOut);
          } else {
            scale /= Math.max(1, (fanIn + fanOut) / 2);
          }
          if (this.distribution === "normal") {
            var stddev = Math.sqrt(scale);
            dtype = dtype || "float32";
            if (dtype !== "float32" && dtype !== "int32") {
              throw new NotImplementedError("".concat(this.getClassName(), " does not support dType ").concat(dtype, "."));
            }
            return tfc.truncatedNormal(shape, 0, stddev, dtype, this.seed);
          } else {
            var limit = Math.sqrt(3 * scale);
            return tfc.randomUniform(shape, -limit, limit, dtype, this.seed);
          }
        };
        VarianceScaling2.prototype.getConfig = function() {
          return {
            scale: this.scale,
            mode: this.mode,
            distribution: this.distribution,
            seed: this.seed
          };
        };
        return VarianceScaling2;
      }(Initializer)
    );
    VarianceScaling.className = "VarianceScaling";
    tfc.serialization.registerClass(VarianceScaling);
    var GlorotUniform = (
      /** @class */
      function(_super) {
        __extends(GlorotUniform2, _super);
        function GlorotUniform2(args) {
          return _super.call(this, {
            scale: 1,
            mode: "fanAvg",
            distribution: "uniform",
            seed: args == null ? null : args.seed
          }) || this;
        }
        GlorotUniform2.prototype.getClassName = function() {
          return VarianceScaling.className;
        };
        return GlorotUniform2;
      }(VarianceScaling)
    );
    GlorotUniform.className = "GlorotUniform";
    tfc.serialization.registerClass(GlorotUniform);
    var GlorotNormal = (
      /** @class */
      function(_super) {
        __extends(GlorotNormal2, _super);
        function GlorotNormal2(args) {
          return _super.call(this, {
            scale: 1,
            mode: "fanAvg",
            distribution: "normal",
            seed: args == null ? null : args.seed
          }) || this;
        }
        GlorotNormal2.prototype.getClassName = function() {
          return VarianceScaling.className;
        };
        return GlorotNormal2;
      }(VarianceScaling)
    );
    GlorotNormal.className = "GlorotNormal";
    tfc.serialization.registerClass(GlorotNormal);
    var HeNormal = (
      /** @class */
      function(_super) {
        __extends(HeNormal2, _super);
        function HeNormal2(args) {
          return _super.call(this, {
            scale: 2,
            mode: "fanIn",
            distribution: "normal",
            seed: args == null ? null : args.seed
          }) || this;
        }
        HeNormal2.prototype.getClassName = function() {
          return VarianceScaling.className;
        };
        return HeNormal2;
      }(VarianceScaling)
    );
    HeNormal.className = "HeNormal";
    tfc.serialization.registerClass(HeNormal);
    var HeUniform = (
      /** @class */
      function(_super) {
        __extends(HeUniform2, _super);
        function HeUniform2(args) {
          return _super.call(this, {
            scale: 2,
            mode: "fanIn",
            distribution: "uniform",
            seed: args == null ? null : args.seed
          }) || this;
        }
        HeUniform2.prototype.getClassName = function() {
          return VarianceScaling.className;
        };
        return HeUniform2;
      }(VarianceScaling)
    );
    HeUniform.className = "HeUniform";
    tfc.serialization.registerClass(HeUniform);
    var LeCunNormal = (
      /** @class */
      function(_super) {
        __extends(LeCunNormal2, _super);
        function LeCunNormal2(args) {
          return _super.call(this, {
            scale: 1,
            mode: "fanIn",
            distribution: "normal",
            seed: args == null ? null : args.seed
          }) || this;
        }
        LeCunNormal2.prototype.getClassName = function() {
          return VarianceScaling.className;
        };
        return LeCunNormal2;
      }(VarianceScaling)
    );
    LeCunNormal.className = "LeCunNormal";
    tfc.serialization.registerClass(LeCunNormal);
    var LeCunUniform = (
      /** @class */
      function(_super) {
        __extends(LeCunUniform2, _super);
        function LeCunUniform2(args) {
          return _super.call(this, {
            scale: 1,
            mode: "fanIn",
            distribution: "uniform",
            seed: args == null ? null : args.seed
          }) || this;
        }
        LeCunUniform2.prototype.getClassName = function() {
          return VarianceScaling.className;
        };
        return LeCunUniform2;
      }(VarianceScaling)
    );
    LeCunUniform.className = "LeCunUniform";
    tfc.serialization.registerClass(LeCunUniform);
    var Orthogonal = (
      /** @class */
      function(_super) {
        __extends(Orthogonal2, _super);
        function Orthogonal2(args) {
          var _this = _super.call(this) || this;
          _this.DEFAULT_GAIN = 1;
          _this.ELEMENTS_WARN_SLOW = 2e3;
          _this.gain = args.gain == null ? _this.DEFAULT_GAIN : args.gain;
          _this.seed = args.seed;
          return _this;
        }
        Orthogonal2.prototype.apply = function(shape, dtype) {
          var _this = this;
          return tfc.tidy(function() {
            if (shape.length < 2) {
              throw new NotImplementedError("Shape must be at least 2D.");
            }
            if (dtype !== "int32" && dtype !== "float32" && dtype !== void 0) {
              throw new TypeError("Unsupported data type ".concat(dtype, "."));
            }
            dtype = dtype;
            var numRows = tfc.util.sizeFromShape(shape.slice(0, -1));
            var numCols = shape[shape.length - 1];
            var numElements = numRows * numCols;
            if (numElements > _this.ELEMENTS_WARN_SLOW) {
              console.warn("Orthogonal initializer is being called on a matrix with more " + "than ".concat(_this.ELEMENTS_WARN_SLOW, " (").concat(numElements, ") elements: ") + "Slowness may result.");
            }
            var flatShape = [Math.max(numCols, numRows), Math.min(numCols, numRows)];
            var randNormalMat = randomNormal$1(flatShape, 0, 1, dtype, _this.seed);
            var qr = tfc.linalg.qr(randNormalMat, false);
            var qMat = qr[0];
            var rMat = qr[1];
            var diag = rMat.flatten().stridedSlice([0], [Math.min(numCols, numRows) * Math.min(numCols, numRows)], [Math.min(numCols, numRows) + 1]);
            qMat = tfc.mul(qMat, diag.sign());
            if (numRows < numCols) {
              qMat = qMat.transpose();
            }
            return tfc.mul(tfc.scalar(_this.gain), qMat.reshape(shape));
          });
        };
        Orthogonal2.prototype.getConfig = function() {
          return {
            gain: this.gain,
            seed: this.seed
          };
        };
        return Orthogonal2;
      }(Initializer)
    );
    Orthogonal.className = "Orthogonal";
    tfc.serialization.registerClass(Orthogonal);
    var INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP = {
      "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 deserializeInitializer(config, customObjects) {
      if (customObjects === void 0) {
        customObjects = {};
      }
      return deserializeKerasObject(config, tfc.serialization.SerializationMap.getMap().classNameMap, customObjects, "initializer");
    }
    function serializeInitializer(initializer) {
      return serializeKerasObject(initializer);
    }
    function getInitializer(identifier) {
      if (typeof identifier === "string") {
        var className = identifier in INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP ? INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[identifier] : identifier;
        if (className === "GlorotNormal") {
          return new GlorotNormal();
        } else if (className === "GlorotUniform") {
          return new GlorotUniform();
        } else if (className === "HeNormal") {
          return new HeNormal();
        } else if (className === "HeUniform") {
          return new HeUniform();
        } else if (className === "LeCunNormal") {
          return new LeCunNormal();
        } else if (className === "LeCunUniform") {
          return new LeCunUniform();
        } else {
          var config = {};
          config["className"] = className;
          config["config"] = {};
          return deserializeInitializer(config);
        }
      } else if (identifier instanceof Initializer) {
        return identifier;
      } else {
        return deserializeInitializer(identifier);
      }
    }
    function isArrayOfShapes(x) {
      return Array.isArray(x) && Array.isArray(x[0]);
    }
    function normalizeShapeList(x) {
      if (x.length === 0) {
        return [];
      }
      if (!Array.isArray(x[0])) {
        return [x];
      }
      return x;
    }
    function getExactlyOneTensor(xs) {
      var x;
      if (Array.isArray(xs)) {
        if (xs.length !== 1) {
          throw new ValueError("Expected Tensor length to be 1; got ".concat(xs.length));
        }
        x = xs[0];
      } else {
        x = xs;
      }
      return x;
    }
    function getExactlyOneShape(shapes) {
      if (Array.isArray(shapes) && Array.isArray(shapes[0])) {
        if (shapes.length === 1) {
          shapes = shapes;
          return shapes[0];
        } else {
          throw new ValueError("Expected exactly 1 Shape; got ".concat(shapes.length));
        }
      } else {
        return shapes;
      }
    }
    function countParamsInWeights(weights) {
      var e_12, _a2;
      var count2 = 0;
      try {
        for (var weights_1 = __values(weights), weights_1_1 = weights_1.next(); !weights_1_1.done; weights_1_1 = weights_1.next()) {
          var weight = weights_1_1.value;
          if (weight.shape.length === 0) {
            count2 += 1;
          } else {
            count2 += weight.shape.reduce(function(a, b) {
              return a * b;
            });
          }
        }
      } catch (e_1_1) {
        e_12 = { error: e_1_1 };
      } finally {
        try {
          if (weights_1_1 && !weights_1_1.done && (_a2 = weights_1.return)) _a2.call(weights_1);
        } finally {
          if (e_12) throw e_12.error;
        }
      }
      return count2;
    }
    var DEFAULT_VARIABLE_NAME_PREFIX = "Variable";
    var LayerVariable = (
      /** @class */
      function() {
        function LayerVariable2(val, dtype, name, trainable, constraint) {
          if (dtype === void 0) {
            dtype = "float32";
          }
          if (name === void 0) {
            name = DEFAULT_VARIABLE_NAME_PREFIX;
          }
          if (trainable === void 0) {
            trainable = true;
          }
          if (constraint === void 0) {
            constraint = null;
          }
          this.dtype = dtype == null ? "float32" : dtype;
          this.shape = val.shape;
          this.id = getNextUniqueTensorId();
          name = name == null ? DEFAULT_VARIABLE_NAME_PREFIX : name;
          this.originalName = getScopedTensorName(name);
          this.name = getUniqueTensorName(this.originalName);
          this.trainable_ = trainable;
          this.constraint = constraint;
          this.val = tfc__namespace.variable(val, this.trainable_, this.name, this.dtype);
        }
        LayerVariable2.prototype.read = function() {
          this.assertNotDisposed();
          return this.val;
        };
        LayerVariable2.prototype.write = function(newVal) {
          this.assertNotDisposed();
          checkShapesMatch(this.val, newVal);
          if (this.val.id !== newVal.id) {
            this.val.assign(newVal);
            if (this.constraint != null) {
              this.val.assign(this.constraint.apply(this.val));
            }
          }
          return this;
        };
        LayerVariable2.prototype.dispose = function() {
          this.assertNotDisposed();
          this.val.dispose();
        };
        LayerVariable2.prototype.assertNotDisposed = function() {
          if (this.val.isDisposed) {
            throw new Error("LayersVariable ".concat(this.name, " is already disposed."));
          }
        };
        Object.defineProperty(LayerVariable2.prototype, "trainable", {
          get: function() {
            return this.trainable_;
          },
          set: function(trainable) {
            this.trainable_ = trainable;
            this.val.trainable = trainable;
          },
          enumerable: false,
          configurable: true
        });
        return LayerVariable2;
      }()
    );
    function checkShapesMatch(x, y) {
      if (x.shape.toString() !== y.shape.toString()) {
        throw new Error("Shape mismatch: " + JSON.stringify(x.shape) + " vs. " + JSON.stringify(y.shape));
      }
    }
    function batchGetValue(xs) {
      return xs.map(function(x) {
        return x.read();
      });
    }
    function batchSetValue(variablesAndValues) {
      variablesAndValues.forEach(function(variableAndValue) {
        var variable = variableAndValue[0];
        variable.write(variableAndValue[1]);
      });
    }
    var InputSpec = (
      /** @class */
      /* @__PURE__ */ function() {
        function InputSpec2(args) {
          this.dtype = args.dtype;
          this.shape = args.shape;
          if (args.shape != null) {
            this.ndim = args.shape.length;
          } else {
            this.ndim = args.ndim;
          }
          this.maxNDim = args.maxNDim;
          this.minNDim = args.minNDim;
          this.axes = args.axes || {};
        }
        return InputSpec2;
      }()
    );
    var SymbolicTensor = (
      /** @class */
      /* @__PURE__ */ function() {
        function SymbolicTensor2(dtype, shape, sourceLayer, inputs, callArgs, name, outputTensorIndex) {
          this.dtype = dtype;
          this.shape = shape;
          this.sourceLayer = sourceLayer;
          this.inputs = inputs;
          this.callArgs = callArgs;
          this.outputTensorIndex = outputTensorIndex;
          this.id = getNextUniqueTensorId();
          if (name != null) {
            this.originalName = getScopedTensorName(name);
            this.name = getUniqueTensorName(this.originalName);
          }
          this.rank = shape.length;
        }
        return SymbolicTensor2;
      }()
    );
    var _nextNodeID = 0;
    var Node = (
      /** @class */
      function() {
        function Node2(args, callArgs) {
          var e_12, _a2;
          this.callArgs = callArgs;
          this.id = _nextNodeID++;
          this.outboundLayer = args.outboundLayer;
          this.inboundLayers = args.inboundLayers;
          this.nodeIndices = args.nodeIndices;
          this.tensorIndices = args.tensorIndices;
          this.inputTensors = args.inputTensors;
          this.outputTensors = args.outputTensors;
          this.inputMasks = args.inputMasks;
          this.outputMasks = args.outputMasks;
          this.inputShapes = args.inputShapes;
          this.outputShapes = args.outputShapes;
          try {
            for (var _b = __values(args.inboundLayers), _c = _b.next(); !_c.done; _c = _b.next()) {
              var layer = _c.value;
              if (layer != null) {
                layer.outboundNodes.push(this);
              }
            }
          } catch (e_1_1) {
            e_12 = { error: e_1_1 };
          } finally {
            try {
              if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
            } finally {
              if (e_12) throw e_12.error;
            }
          }
          args.outboundLayer.inboundNodes.push(this);
        }
        Node2.prototype.getConfig = function() {
          var e_2, _a2;
          var inboundNames = [];
          try {
            for (var _b = __values(this.inboundLayers), _c = _b.next(); !_c.done; _c = _b.next()) {
              var layer = _c.value;
              if (layer != null) {
                inboundNames.push(layer.name);
              } else {
                inboundNames.push(null);
              }
            }
          } catch (e_2_1) {
            e_2 = { error: e_2_1 };
          } finally {
            try {
              if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
            } finally {
              if (e_2) throw e_2.error;
            }
          }
          return {
            outboundLayer: this.outboundLayer ? this.outboundLayer.name : null,
            inboundLayers: inboundNames,
            nodeIndices: this.nodeIndices,
            tensorIndices: this.tensorIndices
          };
        };
        return Node2;
      }()
    );
    var _nextLayerID = 0;
    var Layer = (
      /** @class */
      function(_super) {
        __extends(Layer2, _super);
        function Layer2(args) {
          if (args === void 0) {
            args = {};
          }
          var _this = _super.call(this) || this;
          _this._callHook = null;
          _this._addedWeightNames = [];
          _this._stateful = false;
          _this.id = _nextLayerID++;
          _this.activityRegularizer = null;
          _this.inputSpec = null;
          _this.supportsMasking = false;
          _this._trainableWeights = [];
          _this._nonTrainableWeights = [];
          _this._losses = [];
          _this._updates = [];
          _this._built = false;
          _this.inboundNodes = [];
          _this.outboundNodes = [];
          var name = args.name;
          if (!name) {
            var prefix = _this.getClassName();
            name = toSnakeCase(prefix) + "_" + getUid(prefix);
          }
          _this.name = name;
          _this.trainable_ = args.trainable == null ? true : args.trainable;
          if (args.inputShape != null || args.batchInputShape != null) {
            var batchInputShape = void 0;
            if (args.batchInputShape != null) {
              batchInputShape = args.batchInputShape;
            } else if (args.inputShape != null) {
              var batchSize = null;
              if (args.batchSize != null) {
                batchSize = args.batchSize;
              }
              batchInputShape = [batchSize].concat(args.inputShape);
            }
            _this.batchInputShape = batchInputShape;
            var dtype = args.dtype;
            if (dtype == null) {
              dtype = args.inputDType;
            }
            if (dtype == null) {
              dtype = "float32";
            }
            _this.dtype = dtype;
          }
          if (args.weights != null) {
            _this.initialWeights = args.weights;
          } else {
            _this.initialWeights = null;
          }
          _this._refCount = null;
          _this.fastWeightInitDuringBuild = false;
          return _this;
        }
        Layer2.nodeKey = function(layer, nodeIndex) {
          return layer.name + "_ib-" + nodeIndex.toString();
        };
        Layer2.prototype.getNodeAtIndex = function(nodeIndex, attrName) {
          if (this.inboundNodes.length === 0) {
            throw new RuntimeError("The layer has never been called " + "and thus has no defined ".concat(attrName, "."));
          }
          if (this.inboundNodes.length <= nodeIndex) {
            throw new ValueError("Asked to get ".concat(attrName, " at node ").concat(nodeIndex, ", ") + "but the layer has only ".concat(this.inboundNodes.length, " inbound nodes."));
          }
          return this.inboundNodes[nodeIndex];
        };
        Layer2.prototype.getInputAt = function(nodeIndex) {
          return singletonOrArray(this.getNodeAtIndex(nodeIndex, "input").inputTensors);
        };
        Layer2.prototype.getOutputAt = function(nodeIndex) {
          return singletonOrArray(this.getNodeAtIndex(nodeIndex, "output").outputTensors);
        };
        Object.defineProperty(Layer2.prototype, "input", {
          // Properties
          /**
           * Retrieves the input tensor(s) of a layer.
           *
           * Only applicable if the layer has exactly one inbound node,
           * i.e. if it is connected to one incoming layer.
           *
           * @return Input tensor or list of input tensors.
           *
           * @exception AttributeError if the layer is connected to more than one
           *   incoming layers.
           */
          get: function() {
            if (this.inboundNodes.length > 1) {
              throw new AttributeError("Layer ".concat(this.name) + ' has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use `getInputAt(nodeIndex)` instead.');
            } else if (this.inboundNodes.length === 0) {
              throw new AttributeError("Layer ".concat(this.name) + " is not connected, no input to return.");
            }
            return singletonOrArray(this.getNodeAtIndex(0, "input").inputTensors);
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(Layer2.prototype, "output", {
          /**
           * Retrieves the output tensor(s) of a layer.
           *
           * Only applicable if the layer has exactly one inbound node,
           * i.e. if it is connected to one incoming layer.
           *
           * @return Output tensor or list of output tensors.
           *
           * @exception AttributeError if the layer is connected to more than one
           *   incoming layers.
           */
          get: function() {
            if (this.inboundNodes.length === 0) {
              throw new AttributeError("Layer ".concat(this.name) + " has no inbound nodes.");
            }
            if (this.inboundNodes.length > 1) {
              throw new AttributeError("Layer ".concat(this.name) + ' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');
            }
            return singletonOrArray(this.getNodeAtIndex(0, "output").outputTensors);
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(Layer2.prototype, "losses", {
          get: function() {
            return this._losses;
          },
          enumerable: false,
          configurable: true
        });
        Layer2.prototype.calculateLosses = function() {
          return this.losses.map(function(lossFn) {
            return lossFn();
          });
        };
        Object.defineProperty(Layer2.prototype, "updates", {
          get: function() {
            return this._updates;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(Layer2.prototype, "built", {
          get: function() {
            return this._built;
          },
          set: function(built) {
            this._built = built;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(Layer2.prototype, "trainable", {
          get: function() {
            return this.trainable_;
          },
          set: function(trainable) {
            this._trainableWeights.forEach(function(w) {
              return w.trainable = trainable;
            });
            this.trainable_ = trainable;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(Layer2.prototype, "trainableWeights", {
          get: function() {
            if (this.trainable_) {
              return this._trainableWeights.filter(function(w) {
                return w.trainable;
              });
            } else {
              return [];
            }
          },
          set: function(weights) {
            this._trainableWeights = weights;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(Layer2.prototype, "nonTrainableWeights", {
          get: function() {
            if (this.trainable) {
              return this._trainableWeights.filter(function(w) {
                return !w.trainable;
              }).concat(this._nonTrainableWeights);
            } else {
              return this._trainableWeights.concat(this._nonTrainableWeights);
            }
          },
          set: function(weights) {
            this._nonTrainableWeights = weights;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(Layer2.prototype, "weights", {
          /**
           * The concatenation of the lists trainableWeights and nonTrainableWeights
           * (in this order).
           */
          get: function() {
            return this.trainableWeights.concat(this.nonTrainableWeights);
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(Layer2.prototype, "stateful", {
          get: function() {
            return this._stateful;
          },
          enumerable: false,
          configurable: true
        });
        Layer2.prototype.resetStates = function() {
          if (!this.stateful) {
            throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.");
          }
        };
        Layer2.prototype.assertInputCompatibility = function(inputs) {
          var inputsList = toList(inputs);
          if (this.inputSpec == null || this.inputSpec.length === 0) {
            return;
          }
          var inputSpec = toList(this.inputSpec);
          if (inputsList.length !== inputSpec.length) {
            throw new ValueError("Layer ".concat(this.name, " expects ").concat(inputSpec.length, " inputs, ") + "but it received ".concat(inputsList.length, " input tensors. ") + "Input received: ".concat(inputs));
          }
          for (var inputIndex = 0; inputIndex < inputsList.length; inputIndex++) {
            var x = inputsList[inputIndex];
            var spec = inputSpec[inputIndex];
            if (spec == null) {
              continue;
            }
            var ndim = x.rank;
            if (spec.ndim != null) {
              if (ndim !== spec.ndim) {
                throw new ValueError("Input ".concat(inputIndex, " is incompatible with layer ").concat(this.name, ": ") + "expected ndim=".concat(spec.ndim, ", found ndim=").concat(ndim));
              }
            }
            if (spec.maxNDim != null) {
              if (ndim > spec.maxNDim) {
                throw new ValueError("Input ".concat(inputIndex, " is incompatible with layer ").concat(this.name) + ": expected max_ndim=".concat(spec.maxNDim, ", found ndim=").concat(ndim));
              }
            }
            if (spec.minNDim != null) {
              if (ndim < spec.minNDim) {
                throw new ValueError("Input ".concat(inputIndex, " is incompatible with layer ").concat(this.name) + ": expected min_ndim=".concat(spec.minNDim, ", found ndim=").concat(ndim, "."));
              }
            }
            if (spec.dtype != null) {
              if (x.dtype !== spec.dtype) {
                throw new ValueError("Input ".concat(inputIndex, " is incompatible with layer ").concat(this.name, " ") + ": expected dtype=".concat(spec.dtype, ", found dtype=").concat(x.dtype, "."));
              }
            }
            if (spec.axes) {
              var xShape = x.shape;
              for (var key in spec.axes) {
                var axis = Number(key);
                var value = spec.axes[key];
                var xShapeAtAxis = axis >= 0 ? xShape[axis] : xShape[xShape.length + axis];
                if (value != null && [value, null].indexOf(xShapeAtAxis) === -1) {
                  throw new ValueError("Input ".concat(inputIndex, " is incompatible with layer ") + "".concat(this.name, ": expected axis ").concat(axis, " of input shape to ") + "have value ".concat(value, " but got shape ").concat(xShape, "."));
                }
              }
            }
            if (spec.shape != null) {
              for (var i = 0; i < spec.shape.length; ++i) {
                var specDim = spec.shape[i];
                var dim = x.shape[i];
                if (specDim != null && dim != null) {
                  if (specDim !== dim) {
                    throw new ValueError("Input ".concat(inputIndex, " is incompatible with layer ") + "".concat(this.name, ": expected shape=").concat(spec.shape, ", ") + "found shape=".concat(x.shape, "."));
                  }
                }
              }
            }
          }
        };
        Layer2.prototype.call = function(inputs, kwargs) {
          return inputs;
        };
        Layer2.prototype.invokeCallHook = function(inputs, kwargs) {
          if (this._callHook != null) {
            this._callHook(inputs, kwargs);
          }
        };
        Layer2.prototype.setCallHook = function(callHook) {
          this._callHook = callHook;
        };
        Layer2.prototype.clearCallHook = function() {
          this._callHook = null;
        };
        Layer2.prototype.apply = function(inputs, kwargs) {
          var _this = this;
          kwargs = kwargs || {};
          this.assertNotDisposed();
          var inputsList = toList(inputs);
          var allAreSymbolic = checkAllSymbolic(inputs);
          var noneAreSymbolic = checkNoneSymbolic(inputs);
          if (allAreSymbolic === noneAreSymbolic) {
            throw new ValueError("Arguments to apply() must be all SymbolicTensors or all Tensors");
          }
          return nameScope(this.name, function() {
            var e_3, _a2, e_4, _b;
            if (!_this.built) {
              _this.assertInputCompatibility(inputs);
              var inputShapes = [];
              try {
                for (var _c = __values(toList(inputs)), _d = _c.next(); !_d.done; _d = _c.next()) {
                  var xElem = _d.value;
                  inputShapes.push(xElem.shape);
                }
              } catch (e_3_1) {
                e_3 = { error: e_3_1 };
              } finally {
                try {
                  if (_d && !_d.done && (_a2 = _c.return)) _a2.call(_c);
                } finally {
                  if (e_3) throw e_3.error;
                }
              }
              _this.build(singletonOrArray(inputShapes));
              _this.built = true;
              if (_this.initialWeights) {
                _this.setWeights(_this.initialWeights);
              }
              if (_this._refCount === null && noneAreSymbolic) {
                _this._refCount = 1;
              }
            }
            _this.assertInputCompatibility(inputs);
            if (noneAreSymbolic) {
              var output = _this.call(inputs, kwargs);
              if (_this.supportsMasking) {
                _this.setMaskMetadata(inputs, output);
              }
              var outputList = toList(output);
              var outputListCopy = [];
              try {
                for (var outputList_1 = __values(outputList), outputList_1_1 = outputList_1.next(); !outputList_1_1.done; outputList_1_1 = outputList_1.next()) {
                  var x = outputList_1_1.value;
                  if (inputsList.indexOf(x) !== -1) {
                    x = x.clone();
                  }
                  outputListCopy.push(x);
                }
              } catch (e_4_1) {
                e_4 = { error: e_4_1 };
              } finally {
                try {
                  if (outputList_1_1 && !outputList_1_1.done && (_b = outputList_1.return)) _b.call(outputList_1);
                } finally {
                  if (e_4) throw e_4.error;
                }
              }
              output = singletonOrArray(outputListCopy);
              if (_this.activityRegularizer != null) {
                throw new NotImplementedError("Layer invocation in the presence of activity regularizer(s) is not supported yet.");
              }
              return output;
            } else {
              var inputShape = collectInputShape(inputs);
              var outputShape = _this.computeOutputShape(inputShape);
              var output = void 0;
              var outputDType_1 = guessOutputDType(inputs);
              _this.warnOnIncompatibleInputShape(Array.isArray(inputs) ? inputShape[0] : inputShape);
              if (outputShape != null && outputShape.length > 0 && Array.isArray(outputShape[0])) {
                output = outputShape.map(function(shape, index) {
                  return new SymbolicTensor(outputDType_1, shape, _this, toList(inputs), kwargs, _this.name, index);
                });
              } else {
                output = new SymbolicTensor(outputDType_1, outputShape, _this, toList(inputs), kwargs, _this.name);
              }
              _this.addInboundNode(inputs, output, null, null, inputShape, outputShape, kwargs);
              _this._refCount++;
              if (_this.activityRegularizer != null) {
                throw new NotImplementedError("Layer invocation in the presence of activity regularizer(s) is not supported yet.");
              }
              return output;
            }
          });
        };
        Layer2.prototype.warnOnIncompatibleInputShape = function(inputShape) {
          if (this.batchInputShape == null) {
            return;
          } else if (inputShape.length !== this.batchInputShape.length) {
            console.warn("The rank of the input tensor provided (shape: " + "".concat(JSON.stringify(inputShape), ") does not match that of the ") + "batchInputShape (".concat(JSON.stringify(this.batchInputShape), ") ") + "of the layer ".concat(this.name));
          } else {
            var dimMismatch_1 = false;
            this.batchInputShape.forEach(function(dimension, i) {
              if (dimension != null && inputShape[i] != null && inputShape[i] !== dimension) {
                dimMismatch_1 = true;
              }
            });
            if (dimMismatch_1) {
              console.warn("The shape of the input tensor " + "(".concat(JSON.stringify(inputShape), ") does not ") + "match the expectation of layer ".concat(this.name, ": ") + "".concat(JSON.stringify(this.batchInputShape)));
            }
          }
        };
        Object.defineProperty(Layer2.prototype, "outputShape", {
          /**
           * Retrieves the output shape(s) of a layer.
           *
           * Only applicable if the layer has only one inbound node, or if all inbound
           * nodes have the same output shape.
           *
           * @returns Output shape or shapes.
           * @throws AttributeError: if the layer is connected to more than one incoming
           *   nodes.
           *
           * @doc {heading: 'Models', 'subheading': 'Classes'}
           */
          get: function() {
            var e_5, _a2;
            if (this.inboundNodes == null || this.inboundNodes.length === 0) {
              throw new AttributeError("The layer ".concat(this.name, " has never been called and thus has no ") + "defined output shape.");
            }
            var allOutputShapes = [];
            try {
              for (var _b = __values(this.inboundNodes), _c = _b.next(); !_c.done; _c = _b.next()) {
                var node = _c.value;
                var shapeString = JSON.stringify(node.outputShapes);
                if (allOutputShapes.indexOf(shapeString) === -1) {
                  allOutputShapes.push(shapeString);
                }
              }
            } catch (e_5_1) {
              e_5 = { error: e_5_1 };
            } finally {
              try {
                if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
              } finally {
                if (e_5) throw e_5.error;
              }
            }
            if (allOutputShapes.length === 1) {
              var outputShapes = this.inboundNodes[0].outputShapes;
              if (Array.isArray(outputShapes) && Array.isArray(outputShapes[0]) && outputShapes.length === 1) {
                return outputShapes[0];
              } else {
                return outputShapes;
              }
            } else {
              throw new AttributeError("The layer ".concat(this.name, " has multiple inbound nodes with different ") + 'output shapes. Hence the notion of "output shape" is ill-defined for the layer.');
            }
          },
          enumerable: false,
          configurable: true
        });
        Layer2.prototype.countParams = function() {
          if (!this.built) {
            throw new RuntimeError("You tried to call countParams() on ".concat(this.name, ", ") + "but the layer is not built yet. Build it first by calling build(batchInputShape).");
          }
          return countParamsInWeights(this.weights);
        };
        Layer2.prototype.build = function(inputShape) {
          this.built = true;
        };
        Layer2.prototype.getWeights = function(trainableOnly) {
          if (trainableOnly === void 0) {
            trainableOnly = false;
          }
          return batchGetValue(trainableOnly ? this.trainableWeights : this.weights);
        };
        Layer2.prototype.setWeights = function(weights) {
          var _this = this;
          tfc.tidy(function() {
            var params = _this.weights;
            if (params.length !== weights.length) {
              throw new ValueError('You called setWeights(weights) on layer "'.concat(_this.name, '" ') + "with a weight list of length ".concat(weights.length, ", ") + "but the layer was expecting ".concat(params.length, " weights. ") + "Provided weights: ".concat(weights, "..."));
            }
            if (params.length === 0) {
              return;
            }
            var weightValueTuples = [];
            var paramValues = batchGetValue(params);
            for (var i = 0; i < paramValues.length; ++i) {
              var pv = paramValues[i];
              var p = params[i];
              var w = weights[i];
              if (!tfc.util.arraysEqual(pv.shape, w.shape)) {
                throw new ValueError("Layer weight shape ".concat(pv.shape, " ") + "not compatible with provided weight shape ".concat(w.shape));
              }
              weightValueTuples.push([p, w]);
            }
            batchSetValue(weightValueTuples);
          });
        };
        Layer2.prototype.addWeight = function(name, shape, dtype, initializer, regularizer, trainable, constraint, getInitializerFunc) {
          if (this._addedWeightNames.indexOf(name) !== -1) {
            throw new ValueError("Duplicate weight name ".concat(name, " for layer ").concat(this.name));
          }
          this._addedWeightNames.push(name);
          if (dtype == null) {
            dtype = "float32";
          }
          if (this.fastWeightInitDuringBuild) {
            initializer = getInitializerFunc != null ? getInitializerFunc() : getInitializer("zeros");
          }
          var initValue = initializer.apply(shape, dtype);
          var weight = new LayerVariable(initValue, dtype, name, trainable, constraint);
          initValue.dispose();
          if (regularizer != null) {
            this.addLoss(function() {
              return regularizer.apply(weight.read());
            });
          }
          if (trainable == null) {
            trainable = true;
          }
          if (trainable) {
            this._trainableWeights.push(weight);
          } else {
            this._nonTrainableWeights.push(weight);
          }
          return weight;
        };
        Layer2.prototype.setFastWeightInitDuringBuild = function(value) {
          this.fastWeightInitDuringBuild = value;
        };
        Layer2.prototype.addLoss = function(losses) {
          var _a2;
          if (losses == null || Array.isArray(losses) && losses.length === 0) {
            return;
          }
          losses = toList(losses);
          if (this._losses !== void 0 && this._losses !== null) {
            (_a2 = this.losses).push.apply(_a2, __spreadArray([], __read(losses), false));
          }
        };
        Layer2.prototype.computeOutputShape = function(inputShape) {
          return inputShape;
        };
        Layer2.prototype.computeMask = function(inputs, mask) {
          var _this = this;
          if (!this.supportsMasking) {
            if (mask != null) {
              if (Array.isArray(mask)) {
                mask.forEach(function(maskElement) {
                  if (maskElement != null) {
                    throw new TypeError("Layer ".concat(_this.name, " does not support masking, ") + "but was passed an inputMask.");
                  }
                });
              } else {
                throw new TypeError("Layer ".concat(this.name, " does not support masking, ") + "but was passed an inputMask.");
              }
            }
            return null;
          }
          return mask;
        };
        Layer2.prototype.setMaskMetadata = function(inputs, outputs, previousMask) {
          if (!this.supportsMasking) {
            return;
          }
          var outputMasks = this.computeMask(inputs, previousMask);
          var outputsList = toList(outputs);
          var outputMasksList = toList(outputMasks);
          if (outputsList.length !== outputMasksList.length) {
            throw new Error("".concat(this.name, " outputs ").concat(outputsList.length, " tensors ") + "but ".concat(outputsList.length, " masks for those tensors"));
          }
          for (var i = 0; i < outputsList.length; i++) {
            outputsList[i].kerasMask = outputMasksList[i];
          }
        };
        Layer2.prototype.addInboundNode = function(inputTensors, outputTensors, inputMasks, outputMasks, inputShapes, outputShapes, kwargs) {
          var e_6, _a2;
          if (kwargs === void 0) {
            kwargs = null;
          }
          var inputTensorList = toList(inputTensors);
          outputTensors = toList(outputTensors);
          inputMasks = toList(inputMasks);
          outputMasks = toList(outputMasks);
          inputShapes = normalizeShapeList(inputShapes);
          outputShapes = normalizeShapeList(outputShapes);
          var inboundLayers = [];
          var nodeIndices = [];
          var tensorIndices = [];
          try {
            for (var inputTensorList_1 = __values(inputTensorList), inputTensorList_1_1 = inputTensorList_1.next(); !inputTensorList_1_1.done; inputTensorList_1_1 = inputTensorList_1.next()) {
              var x = inputTensorList_1_1.value;
              inboundLayers.push(x.sourceLayer);
              nodeIndices.push(x.nodeIndex);
              tensorIndices.push(x.tensorIndex);
            }
          } catch (e_6_1) {
            e_6 = { error: e_6_1 };
          } finally {
            try {
              if (inputTensorList_1_1 && !inputTensorList_1_1.done && (_a2 = inputTensorList_1.return)) _a2.call(inputTensorList_1);
            } finally {
              if (e_6) throw e_6.error;
            }
          }
          new Node({
            outboundLayer: this,
            inboundLayers,
            nodeIndices,
            tensorIndices,
            inputTensors: inputTensorList,
            outputTensors,
            inputMasks,
            outputMasks,
            inputShapes,
            outputShapes
          }, kwargs);
          for (var i = 0; i < outputTensors.length; i++) {
            outputTensors[i].sourceLayer = this;
            outputTensors[i].nodeIndex = this.inboundNodes.length - 1;
            outputTensors[i].tensorIndex = i;
          }
        };
        Layer2.prototype.getConfig = function() {
          var config = { name: this.name, trainable: this.trainable };
          if (this.batchInputShape != null) {
            config["batchInputShape"] = this.batchInputShape;
          }
          if (this.dtype != null) {
            config["dtype"] = this.dtype;
          }
          return config;
        };
        Layer2.prototype.disposeWeights = function() {
          this.weights.forEach(function(weight) {
            return weight.dispose();
          });
          return this.weights.length;
        };
        Layer2.prototype.assertNotDisposed = function() {
          if (this._refCount === 0) {
            throw new Error("Layer '".concat(this.name, "' is already disposed."));
          }
        };
        Layer2.prototype.dispose = function() {
          if (!this.built) {
            throw new Error("Cannot dispose Layer ".concat(this.name, " because it has not been ") + "built yet.");
          }
          if (this._refCount === null) {
            throw new Error("Cannot dispose Layer ".concat(this.name, " because it has not been used ") + "yet.");
          }
          this.assertNotDisposed();
          var numDisposedVariables = 0;
          if (--this._refCount === 0) {
            numDisposedVariables = this.disposeWeights();
          }
          return { refCountAfterDispose: this._refCount, numDisposedVariables };
        };
        return Layer2;
      }(tfc.serialization.Serializable)
    );
    function collectInputShape(inputTensors) {
      var e_7, _a2;
      inputTensors = toList(inputTensors);
      var shapes = [];
      try {
        for (var inputTensors_1 = __values(inputTensors), inputTensors_1_1 = inputTensors_1.next(); !inputTensors_1_1.done; inputTensors_1_1 = inputTensors_1.next()) {
          var x = inputTensors_1_1.value;
          shapes.push(x.shape);
        }
      } catch (e_7_1) {
        e_7 = { error: e_7_1 };
      } finally {
        try {
          if (inputTensors_1_1 && !inputTensors_1_1.done && (_a2 = inputTensors_1.return)) _a2.call(inputTensors_1);
        } finally {
          if (e_7) throw e_7.error;
        }
      }
      return singletonOrArray(shapes);
    }
    function guessOutputDType(inputTensors) {
      return "float32";
    }
    function getSourceInputs(tensor, layer, nodeIndex) {
      var e_8, _a2;
      if (layer == null || nodeIndex != null && nodeIndex > 0) {
        layer = tensor.sourceLayer;
        nodeIndex = tensor.nodeIndex;
      }
      if (layer.inboundNodes.length === 0) {
        return [tensor];
      } else {
        var node = layer.inboundNodes[nodeIndex];
        if (node.inboundLayers.length === 0) {
          return node.inputTensors;
        } else {
          var sourceTensors = [];
          for (var i = 0; i < node.inboundLayers.length; i++) {
            var x = node.inputTensors[i];
            var layer_1 = node.inboundLayers[i];
            var nodeIndex_1 = node.nodeIndices[i];
            var previousSources = getSourceInputs(x, layer_1, nodeIndex_1);
            try {
              for (var previousSources_1 = (e_8 = void 0, __values(previousSources)), previousSources_1_1 = previousSources_1.next(); !previousSources_1_1.done; previousSources_1_1 = previousSources_1.next()) {
                var x_1 = previousSources_1_1.value;
                if (sourceTensors.indexOf(x_1) === -1) {
                  sourceTensors.push(x_1);
                }
              }
            } catch (e_8_1) {
              e_8 = { error: e_8_1 };
            } finally {
              try {
                if (previousSources_1_1 && !previousSources_1_1.done && (_a2 = previousSources_1.return)) _a2.call(previousSources_1);
              } finally {
                if (e_8) throw e_8.error;
              }
            }
          }
          return sourceTensors;
        }
      }
    }
    function checkAllSymbolic(tensors) {
      var e_9, _a2;
      var allAreSymbolic = true;
      try {
        for (var _b = __values(toList(tensors)), _c = _b.next(); !_c.done; _c = _b.next()) {
          var tensor = _c.value;
          if (!(tensor instanceof SymbolicTensor)) {
            allAreSymbolic = false;
            break;
          }
        }
      } catch (e_9_1) {
        e_9 = { error: e_9_1 };
      } finally {
        try {
          if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
        } finally {
          if (e_9) throw e_9.error;
        }
      }
      return allAreSymbolic;
    }
    function checkNoneSymbolic(tensors) {
      var e_10, _a2;
      var noneAreSymbolic = true;
      try {
        for (var _b = __values(toList(tensors)), _c = _b.next(); !_c.done; _c = _b.next()) {
          var tensor = _c.value;
          if (tensor instanceof SymbolicTensor) {
            noneAreSymbolic = false;
            break;
          }
        }
      } catch (e_10_1) {
        e_10 = { error: e_10_1 };
      } finally {
        try {
          if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
        } finally {
          if (e_10) throw e_10.error;
        }
      }
      return noneAreSymbolic;
    }
    var InputLayer = (
      /** @class */
      function(_super) {
        __extends(InputLayer2, _super);
        function InputLayer2(args) {
          var _this = _super.call(this, {
            dtype: args.dtype,
            name: args.name != null ? args.name : getUid("input").toString()
          }) || this;
          if (args.batchSize == null) {
            args.batchSize = null;
          }
          if (args.sparse == null) {
            args.sparse = false;
          }
          _this.trainable = false;
          _this.built = true;
          _this.sparse = args.sparse;
          if (args.inputShape != null && args.batchInputShape != null) {
            throw new ValueError("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");
          }
          var batchInputShape = args.batchInputShape;
          if (batchInputShape == null) {
            if (args.inputShape == null) {
              throw new ValueError("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");
            } else {
              batchInputShape = [args.batchSize].concat(args.inputShape);
            }
          } else {
            if (args.batchSize != null) {
              throw new ValueError("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");
            }
          }
          var dtype = args.dtype || "float32";
          _this.batchInputShape = batchInputShape;
          _this.dtype = dtype;
          _this.inputSpec = [{ shape: batchInputShape }];
          var inputTensor = new SymbolicTensor(_this.dtype, _this.batchInputShape, _this, [], {}, _this.name);
          inputTensor.nodeIndex = 0;
          inputTensor.tensorIndex = 0;
          new Node({
            outboundLayer: _this,
            inboundLayers: [],
            nodeIndices: [],
            tensorIndices: [],
            inputTensors: [inputTensor],
            outputTensors: [inputTensor],
            inputMasks: [null],
            outputMasks: [null],
            inputShapes: [batchInputShape],
            outputShapes: [batchInputShape]
          });
          return _this;
        }
        InputLayer2.prototype.apply = function(inputs, kwargs) {
          throw new ValueError("Cannot pass any input to an " + "InputLayer's apply() method. InputLayer name: ".concat(this.name));
        };
        InputLayer2.prototype.dispose = function() {
          return { refCountAfterDispose: this._refCount, numDisposedVariables: 0 };
        };
        InputLayer2.prototype.getConfig = function() {
          return {
            batchInputShape: this.batchInputShape,
            dtype: this.dtype,
            sparse: this.sparse,
            name: this.name
          };
        };
        return InputLayer2;
      }(Layer)
    );
    InputLayer.className = "InputLayer";
    tfc.serialization.registerClass(InputLayer);
    function Input(config) {
      if (config.batchShape == null && config.shape == null) {
        throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");
      }
      if (config.batchShape != null && config.shape != null) {
        throw new ValueError("Please provide either a `shape` or `batchShape` argument to Input, but not both.");
      }
      var batchShape = config.batchShape;
      if (config.shape != null && batchShape == null) {
        batchShape = [null].concat(config.shape);
      }
      var dtype = config.dtype;
      if (dtype == null) {
        dtype = "float32";
      }
      var inputLayer2 = new InputLayer({
        batchInputShape: batchShape,
        name: config.name,
        dtype,
        sparse: config.sparse
      });
      var outputs = inputLayer2.inboundNodes[0].outputTensors;
      return outputs[0];
    }
    function assertFeedCompatibility(key, val) {
      if (key.dtype == null || key.dtype === val.dtype) {
        return val;
      }
      try {
        return tfc.cast(val, key.dtype);
      } catch (err) {
        throw new ValueError("The dtype of the feed (".concat(val.dtype, ") can not be cast to the dtype ") + "of the key '".concat(key.name, "' (").concat(key.dtype, ")."));
      }
    }
    var FeedDict = (
      /** @class */
      function() {
        function FeedDict2(feeds) {
          var e_12, _a2;
          this.id2Value = {};
          this.id2Mask = {};
          this.name2Id = {};
          if (feeds instanceof FeedDict2) {
            for (var id in feeds.id2Value) {
              this.id2Value[id] = feeds.id2Value[id];
              if (id in feeds.id2Mask) {
                this.id2Mask[id] = feeds.id2Mask[id];
              }
            }
          } else {
            if (feeds == null) {
              return;
            }
            try {
              for (var feeds_1 = __values(feeds), feeds_1_1 = feeds_1.next(); !feeds_1_1.done; feeds_1_1 = feeds_1.next()) {
                var feed = feeds_1_1.value;
                this.add(feed.key, feed.value);
              }
            } catch (e_1_1) {
              e_12 = { error: e_1_1 };
            } finally {
              try {
                if (feeds_1_1 && !feeds_1_1.done && (_a2 = feeds_1.return)) _a2.call(feeds_1);
              } finally {
                if (e_12) throw e_12.error;
              }
            }
          }
        }
        FeedDict2.prototype.add = function(key, value, mask) {
          if (this.id2Value[key.id] == null) {
            this.id2Value[key.id] = assertFeedCompatibility(key, value);
            this.name2Id[key.name] = key.id;
            if (mask != null) {
              this.id2Mask[key.id] = mask;
            }
          } else {
            throw new ValueError("Duplicate key: name=".concat(key.name, ", id=").concat(key.id));
          }
          return this;
        };
        FeedDict2.prototype.addFeed = function(feed) {
          this.add(feed.key, feed.value);
        };
        FeedDict2.prototype.hasKey = function(key) {
          return this.id2Value[key.id] != null;
        };
        FeedDict2.prototype.names = function() {
          return Object.keys(this.name2Id);
        };
        FeedDict2.prototype.getValue = function(key) {
          if (key instanceof SymbolicTensor) {
            if (this.id2Value[key.id] == null) {
              throw new ValueError("Nonexistent key: ".concat(key.name));
            } else {
              return this.id2Value[key.id];
            }
          } else {
            var id = this.name2Id[key];
            if (id == null) {
              throw new ValueError("Feed dict has no SymbolicTensor name: ".concat(key));
            }
            return this.id2Value[id];
          }
        };
        FeedDict2.prototype.getMask = function(key) {
          if (key instanceof SymbolicTensor) {
            if (this.id2Value[key.id] == null) {
              throw new ValueError("Nonexistent key: ".concat(key.name));
            } else {
              return this.id2Mask[key.id];
            }
          } else {
            var id = this.name2Id[key];
            if (id == null) {
              throw new ValueError("Feed dict has no SymbolicTensor name: ".concat(key));
            }
            return this.id2Mask[id];
          }
        };
        FeedDict2.prototype.disposeMasks = function() {
          if (this.id2Mask != null) {
            tfc.dispose(this.id2Mask);
          }
        };
        return FeedDict2;
      }()
    );
    var cachedSorted = new LruCache();
    var cachedRecipientCounts = new LruCache();
    function updateCacheMaxEntries(maxEntries) {
      if (cachedSorted != null) {
        cachedSorted.setMaxEntries(maxEntries);
      }
      if (cachedRecipientCounts != null) {
        cachedRecipientCounts.setMaxEntries(maxEntries);
      }
    }
    function execute(fetches, feedDict, kwargs, probe) {
      var e_2, _a2, e_3, _b;
      var training = kwargs == null ? false : kwargs["training"];
      var arrayFetches = Array.isArray(fetches);
      var fetchArray = arrayFetches ? fetches : [fetches];
      var outputNames = fetchArray.map(function(t) {
        return t.name;
      });
      var finalOutputs = [];
      var feedNames = feedDict.names();
      try {
        for (var outputNames_1 = __values(outputNames), outputNames_1_1 = outputNames_1.next(); !outputNames_1_1.done; outputNames_1_1 = outputNames_1.next()) {
          var outputName = outputNames_1_1.value;
          if (feedNames.indexOf(outputName) !== -1) {
            finalOutputs.push(feedDict.getValue(outputName));
          } else {
            finalOutputs.push(null);
          }
        }
      } catch (e_2_1) {
        e_2 = { error: e_2_1 };
      } finally {
        try {
          if (outputNames_1_1 && !outputNames_1_1.done && (_a2 = outputNames_1.return)) _a2.call(outputNames_1);
        } finally {
          if (e_2) throw e_2.error;
        }
      }
      if (probe != null) {
        probe.maxNumTensors = -Infinity;
        probe.minNumTensors = Infinity;
      }
      var fetchAndFeedKey = outputNames.join(",") + "|" + feedDict.names().sort().join(",");
      var sorted = cachedSorted.get(fetchAndFeedKey);
      var recipientCounts;
      if (sorted == null) {
        var out = getTopologicalSortAndRecipientCounts(fetchArray, feedDict);
        sorted = out.sorted;
        recipientCounts = out.recipientCounts;
        cachedSorted.put(fetchAndFeedKey, sorted);
        cachedRecipientCounts.put(fetchAndFeedKey, recipientCounts);
      }
      recipientCounts = {};
      if (!training) {
        Object.assign(recipientCounts, cachedRecipientCounts.get(fetchAndFeedKey));
      }
      var internalFeedDict = new FeedDict(feedDict);
      for (var i = 0; i < sorted.length; ++i) {
        if (probe != null) {
          var numTensors = tfc.memory().numTensors;
          if (numTensors > probe.maxNumTensors) {
            probe.maxNumTensors = numTensors;
          }
          if (numTensors < probe.minNumTensors) {
            probe.minNumTensors = numTensors;
          }
        }
        var symbolic = sorted[i];
        var srcLayer = symbolic.sourceLayer;
        if (srcLayer instanceof InputLayer) {
          continue;
        }
        var inputValues = [];
        var inputMasks = [];
        var tensorsToDispose = [];
        var maskExists = false;
        try {
          for (var _c = (e_3 = void 0, __values(symbolic.inputs)), _d = _c.next(); !_d.done; _d = _c.next()) {
            var input2 = _d.value;
            var value = internalFeedDict.getValue(input2);
            var mask = internalFeedDict.getMask(input2);
            inputValues.push(value);
            inputMasks.push(mask);
            if (mask != null) {
              maskExists = true;
            }
            if (!training) {
              recipientCounts[input2.name]--;
              if (recipientCounts[input2.name] === 0 && !feedDict.hasKey(input2) && outputNames.indexOf(input2.name) === -1 && !value.isDisposed && input2.sourceLayer.stateful !== true) {
                tensorsToDispose.push(value);
              }
            }
          }
        } catch (e_3_1) {
          e_3 = { error: e_3_1 };
        } finally {
          try {
            if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
          } finally {
            if (e_3) throw e_3.error;
          }
        }
        if (maskExists) {
          kwargs = kwargs || {};
          kwargs["mask"] = inputMasks[0];
        }
        var outputTensors = toList(srcLayer.apply(inputValues, kwargs));
        var outputMask = null;
        if (srcLayer.supportsMasking) {
          outputMask = srcLayer.computeMask(inputValues, inputMasks);
        }
        var layerOutputs = getNodeOutputs(symbolic);
        var outputSymbolicTensors = Array.isArray(layerOutputs) ? layerOutputs : [layerOutputs];
        for (var i_1 = 0; i_1 < outputSymbolicTensors.length; ++i_1) {
          if (!internalFeedDict.hasKey(outputSymbolicTensors[i_1])) {
            internalFeedDict.add(outputSymbolicTensors[i_1], outputTensors[i_1], Array.isArray(outputMask) ? outputMask[0] : outputMask);
          }
          var index = outputNames.indexOf(outputSymbolicTensors[i_1].name);
          if (index !== -1) {
            finalOutputs[index] = outputTensors[i_1];
          }
        }
        if (!training) {
          tfc.dispose(tensorsToDispose);
        }
      }
      internalFeedDict.disposeMasks();
      return arrayFetches ? finalOutputs : finalOutputs[0];
    }
    function getTopologicalSortAndRecipientCounts(fetches, feedDict) {
      var e_4, _a2, e_5, _b;
      tfc.util.assert(fetches != null && fetches.length > 0, function() {
        return "Expected at least one fetch, got none";
      });
      var finalSorted = [];
      var finalRecipientMap = {};
      if (fetches.length === 1) {
        var out = getTopologicalSortAndRecipientCountsForOneFetch(fetches[0], feedDict);
        finalSorted = out.sorted;
        finalRecipientMap = out.recipientMap;
      } else {
        var visited = /* @__PURE__ */ new Set();
        try {
          for (var fetches_1 = __values(fetches), fetches_1_1 = fetches_1.next(); !fetches_1_1.done; fetches_1_1 = fetches_1.next()) {
            var fetch2 = fetches_1_1.value;
            var _c = getTopologicalSortAndRecipientCountsForOneFetch(fetch2, feedDict), sorted = _c.sorted, recipientMap = _c.recipientMap;
            try {
              for (var sorted_1 = (e_5 = void 0, __values(sorted)), sorted_1_1 = sorted_1.next(); !sorted_1_1.done; sorted_1_1 = sorted_1.next()) {
                var symbolicTensor = sorted_1_1.value;
                if (!visited.has(symbolicTensor.name)) {
                  finalSorted.push(symbolicTensor);
                  visited.add(symbolicTensor.name);
                }
              }
            } catch (e_5_1) {
              e_5 = { error: e_5_1 };
            } finally {
              try {
                if (sorted_1_1 && !sorted_1_1.done && (_b = sorted_1.return)) _b.call(sorted_1);
              } finally {
                if (e_5) throw e_5.error;
              }
            }
            var _loop_1 = function(name2) {
              if (finalRecipientMap[name2] == null) {
                finalRecipientMap[name2] = /* @__PURE__ */ new Set();
              }
              recipientMap[name2].forEach(function(recipient) {
                return finalRecipientMap[name2].add(recipient);
              });
            };
            for (var name in recipientMap) {
              _loop_1(name);
            }
          }
        } catch (e_4_1) {
          e_4 = { error: e_4_1 };
        } finally {
          try {
            if (fetches_1_1 && !fetches_1_1.done && (_a2 = fetches_1.return)) _a2.call(fetches_1);
          } finally {
            if (e_4) throw e_4.error;
          }
        }
      }
      return {
        sorted: finalSorted,
        recipientCounts: recipientMap2Counts(finalRecipientMap)
      };
    }
    function recipientMap2Counts(recipientMap) {
      var recipientCounts = {};
      for (var name in recipientMap) {
        recipientCounts[name] = recipientMap[name].size;
      }
      return recipientCounts;
    }
    function getTopologicalSortAndRecipientCountsForOneFetch(fetch2, feedDict) {
      var e_6, _a2, e_7, _b;
      var visited = /* @__PURE__ */ new Set();
      var sorted = [];
      var recipientMap = {};
      try {
        for (var _c = __values(feedDict.names()), _d = _c.next(); !_d.done; _d = _c.next()) {
          var key = _d.value;
          visited.add(key);
        }
      } catch (e_6_1) {
        e_6 = { error: e_6_1 };
      } finally {
        try {
          if (_d && !_d.done && (_a2 = _c.return)) _a2.call(_c);
        } finally {
          if (e_6) throw e_6.error;
        }
      }
      var stack2 = [];
      var marks = [];
      stack2.push(fetch2);
      while (stack2.length > 0) {
        var top = stack2[stack2.length - 1];
        if (visited.has(top.name)) {
          stack2.pop();
          continue;
        }
        var topIsMarked = marks[marks.length - 1] === stack2.length - 1;
        if (top.inputs.length === 0 || topIsMarked) {
          stack2.pop();
          sorted.push(top);
          visited.add(top.name);
          if (topIsMarked) {
            marks.pop();
          }
        } else {
          marks.push(stack2.length - 1);
          try {
            for (var _e = (e_7 = void 0, __values(top.inputs)), _f = _e.next(); !_f.done; _f = _e.next()) {
              var input2 = _f.value;
              if (recipientMap[input2.name] == null) {
                recipientMap[input2.name] = /* @__PURE__ */ new Set();
              }
              recipientMap[input2.name].add(top.name);
              if (visited.has(input2.name)) {
                continue;
              }
              stack2.push(input2);
            }
          } catch (e_7_1) {
            e_7 = { error: e_7_1 };
          } finally {
            try {
              if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
            } finally {
              if (e_7) throw e_7.error;
            }
          }
        }
      }
      return { sorted, recipientMap };
    }
    function getNodeOutputs(fetch2) {
      var e_8, _a2;
      var layerOutputs;
      if (fetch2.sourceLayer.inboundNodes.length === 1) {
        layerOutputs = fetch2.sourceLayer.output;
      } else {
        var nodeIndex = null;
        for (var i = 0; i < fetch2.sourceLayer.inboundNodes.length; ++i) {
          try {
            for (var _b = (e_8 = void 0, __values(fetch2.sourceLayer.inboundNodes[i].outputTensors)), _c = _b.next(); !_c.done; _c = _b.next()) {
              var outputTensor = _c.value;
              if (outputTensor.id === fetch2.id) {
                nodeIndex = i;
                break;
              }
            }
          } catch (e_8_1) {
            e_8 = { error: e_8_1 };
          } finally {
            try {
              if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
            } finally {
              if (e_8) throw e_8.error;
            }
          }
        }
        layerOutputs = fetch2.sourceLayer.getOutputAt(nodeIndex);
      }
      return layerOutputs;
    }
    var ENV$2 = tfc.env();
    ENV$2.registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES", function() {
      return 100;
    }, updateCacheMaxEntries);
    var Abs = "Abs";
    var Acos = "Acos";
    var Acosh = "Acosh";
    var Add$1 = "Add";
    var AddN = "AddN";
    var ArgMax = "ArgMax";
    var ArgMin = "ArgMin";
    var Asin = "Asin";
    var Asinh = "Asinh";
    var Atan = "Atan";
    var Atanh = "Atanh";
    var Atan2 = "Atan2";
    var AvgPool = "AvgPool";
    var AvgPoolGrad = "AvgPoolGrad";
    var AvgPool3D = "AvgPool3D";
    var AvgPool3DGrad = "AvgPool3DGrad";
    var BatchMatMul = "BatchMatMul";
    var BatchToSpaceND = "BatchToSpaceND";
    var BroadcastTo = "BroadcastTo";
    var Cast = "Cast";
    var Ceil = "Ceil";
    var ClipByValue = "ClipByValue";
    var Complex = "Complex";
    var ComplexAbs = "ComplexAbs";
    var Concat = "Concat";
    var Conv2D$1 = "Conv2D";
    var Conv2DBackpropFilter = "Conv2DBackpropFilter";
    var Conv2DBackpropInput = "Conv2DBackpropInput";
    var Conv3D$1 = "Conv3D";
    var Conv3DBackpropFilterV2 = "Conv3DBackpropFilterV2";
    var Conv3DBackpropInputV2 = "Conv3DBackpropInputV2";
    var Cos = "Cos";
    var Cosh = "Cosh";
    var Cumprod = "Cumprod";
    var Cumsum = "Cumsum";
    var DepthwiseConv2dNative = "DepthwiseConv2dNative";
    var DepthwiseConv2dNativeBackpropFilter = "DepthwiseConv2dNativeBackpropFilter";
    var DepthwiseConv2dNativeBackpropInput = "DepthwiseConv2dNativeBackpropInput";
    var Dilation2D = "Dilation2D";
    var Dilation2DBackpropInput = "Dilation2DBackpropInput";
    var Dilation2DBackpropFilter = "Dilation2DBackpropFilter";
    var RealDiv = "RealDiv";
    var Elu$1 = "Elu";
    var EluGrad = "EluGrad";
    var Erf = "Erf";
    var Equal = "Equal";
    var Exp = "Exp";
    var ExpandDims = "ExpandDims";
    var Expm1 = "Expm1";
    var Fill = "Fill";
    var Floor = "Floor";
    var FloorDiv = "FloorDiv";
    var FusedBatchNorm = "FusedBatchNorm";
    var GatherV2 = "GatherV2";
    var Greater = "Greater";
    var GreaterEqual = "GreaterEqual";
    var Identity = "Identity";
    var Imag = "Imag";
    var IsFinite = "IsFinite";
    var IsInf = "IsInf";
    var IsNan = "IsNan";
    var LeakyRelu = "LeakyRelu";
    var Less = "Less";
    var LessEqual = "LessEqual";
    var Log = "Log";
    var Log1p = "Log1p";
    var LogicalAnd = "LogicalAnd";
    var LogicalNot = "LogicalNot";
    var LogSoftmax$1 = "LogSoftmax";
    var LRN = "LRN";
    var LRNGrad = "LRNGrad";
    var Max = "Max";
    var Maximum$1 = "Maximum";
    var MaxPool = "MaxPool";
    var MaxPoolGrad = "MaxPoolGrad";
    var MaxPool3D = "MaxPool3D";
    var MaxPool3DGrad = "MaxPool3DGrad";
    var Mean = "Mean";
    var Min = "Min";
    var Minimum$1 = "Minimum";
    var MirrorPad = "MirrorPad";
    var Mod = "Mod";
    var Multiply$1 = "Multiply";
    var Neg = "Neg";
    var OnesLike = "OnesLike";
    var OneHot = "OneHot";
    var Pack = "Pack";
    var PadV2 = "PadV2";
    var Pow = "Pow";
    var Prelu = "Prelu";
    var Prod = "Prod";
    var Real = "Real";
    var Reciprocal = "Reciprocal";
    var Relu$1 = "Relu";
    var Reshape$1 = "Reshape";
    var ResizeNearestNeighbor = "ResizeNearestNeighbor";
    var ResizeNearestNeighborGrad = "ResizeNearestNeighborGrad";
    var ResizeBilinear = "ResizeBilinear";
    var ResizeBilinearGrad = "ResizeBilinearGrad";
    var Relu6$1 = "Relu6";
    var Reverse = "Reverse";
    var Round = "Round";
    var Rsqrt = "Rsqrt";
    var TensorScatterUpdate = "TensorScatterUpdate";
    var Select = "Select";
    var Selu$1 = "Selu";
    var Slice = "Slice";
    var Sin = "Sin";
    var Sinh = "Sinh";
    var Sign = "Sign";
    var Sigmoid$1 = "Sigmoid";
    var Softplus$1 = "Softplus";
    var Sqrt = "Sqrt";
    var Sum = "Sum";
    var SpaceToBatchND = "SpaceToBatchND";
    var SplitV = "SplitV";
    var Softmax$2 = "Softmax";
    var SquaredDifference = "SquaredDifference";
    var Square = "Square";
    var Sub = "Sub";
    var Tan = "Tan";
    var Tanh$1 = "Tanh";
    var Tile = "Tile";
    var Transpose = "Transpose";
    var Unpack = "Unpack";
    var UnsortedSegmentSum = "UnsortedSegmentSum";
    var ZerosLike = "ZerosLike";
    var Step = "Step";
    var EPSILON_FLOAT32 = 1e-7;
    var EPSILON_FLOAT16 = 1e-4;
    var KernelBackend = (
      /** @class */
      function() {
        function KernelBackend2() {
        }
        KernelBackend2.prototype.refCount = function(dataId) {
          return notYetImplemented("refCount");
        };
        KernelBackend2.prototype.incRef = function(dataId) {
          return notYetImplemented("incRef");
        };
        KernelBackend2.prototype.timerAvailable = function() {
          return true;
        };
        KernelBackend2.prototype.time = function(f) {
          return notYetImplemented("time");
        };
        KernelBackend2.prototype.read = function(dataId) {
          return notYetImplemented("read");
        };
        KernelBackend2.prototype.readSync = function(dataId) {
          return notYetImplemented("readSync");
        };
        KernelBackend2.prototype.readToGPU = function(dataId, options) {
          return notYetImplemented("readToGPU");
        };
        KernelBackend2.prototype.numDataIds = function() {
          return notYetImplemented("numDataIds");
        };
        KernelBackend2.prototype.disposeData = function(dataId, force) {
          return notYetImplemented("disposeData");
        };
        KernelBackend2.prototype.write = function(values, shape, dtype) {
          return notYetImplemented("write");
        };
        KernelBackend2.prototype.move = function(dataId, values, shape, dtype, refCount) {
          return notYetImplemented("move");
        };
        KernelBackend2.prototype.createTensorFromGPUData = function(values, shape, dtype) {
          return notYetImplemented("createTensorFromGPUData");
        };
        KernelBackend2.prototype.memory = function() {
          return notYetImplemented("memory");
        };
        KernelBackend2.prototype.floatPrecision = function() {
          return notYetImplemented("floatPrecision");
        };
        KernelBackend2.prototype.epsilon = function() {
          return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;
        };
        KernelBackend2.prototype.dispose = function() {
          return notYetImplemented("dispose");
        };
        return KernelBackend2;
      }()
    );
    function notYetImplemented(kernelName) {
      throw new Error("'".concat(kernelName, "' not yet implemented or not found in the registry. ") + "This kernel may not be supported by the tfjs backend you have chosen");
    }
    function assert(expr, msg) {
      if (!expr) {
        throw new Error(typeof msg === "string" ? msg : msg());
      }
    }
    function assertShapesMatch(shapeA, shapeB, errorMessagePrefix) {
      if (errorMessagePrefix === void 0) {
        errorMessagePrefix = "";
      }
      assert(arraysEqual(shapeA, shapeB), function() {
        return errorMessagePrefix + " Shapes ".concat(shapeA, " and ").concat(shapeB, " must match");
      });
    }
    function sizeFromShape(shape) {
      if (shape.length === 0) {
        return 1;
      }
      var size = shape[0];
      for (var i = 1; i < shape.length; i++) {
        size *= shape[i];
      }
      return size;
    }
    function arraysEqual(n1, n2) {
      if (n1 === n2) {
        return true;
      }
      if (n1 == null || n2 == null) {
        return false;
      }
      if (n1.length !== n2.length) {
        return false;
      }
      for (var i = 0; i < n1.length; i++) {
        if (n1[i] !== n2[i]) {
          return false;
        }
      }
      return true;
    }
    function isInt(a) {
      return a % 1 === 0;
    }
    function rightPad(a, size) {
      if (size <= a.length) {
        return a;
      }
      return a + " ".repeat(size - a.length);
    }
    function parseAxisParam(axis, shape) {
      var rank = shape.length;
      axis = axis == null ? shape.map(function(s, i) {
        return i;
      }) : [].concat(axis);
      assert(axis.every(function(ax) {
        return ax >= -rank && ax < rank;
      }), function() {
        return "All values in axis param must be in range [-".concat(rank, ", ").concat(rank, ") but ") + "got axis ".concat(axis);
      });
      assert(axis.every(function(ax) {
        return isInt(ax);
      }), function() {
        return "All values in axis param must be integers but " + "got axis ".concat(axis);
      });
      return axis.map(function(a) {
        return a < 0 ? rank + a : a;
      });
    }
    function getArrayFromDType(dtype, size) {
      var values = null;
      if (dtype == null || dtype === "float32") {
        values = new Float32Array(size);
      } else if (dtype === "int32") {
        values = new Int32Array(size);
      } else if (dtype === "bool") {
        values = new Uint8Array(size);
      } else if (dtype === "string") {
        values = new Array(size);
      } else {
        throw new Error("Unknown data type ".concat(dtype));
      }
      return values;
    }
    function checkConversionForErrors(vals, dtype) {
      for (var i = 0; i < vals.length; i++) {
        var num = vals[i];
        if (isNaN(num) || !isFinite(num)) {
          throw Error("A tensor of type ".concat(dtype, " being uploaded contains ").concat(num, "."));
        }
      }
    }
    function isValidDtype(dtype) {
      return dtype === "bool" || dtype === "complex64" || dtype === "float32" || dtype === "int32" || dtype === "string";
    }
    function bytesPerElement(dtype) {
      if (dtype === "float32" || dtype === "int32") {
        return 4;
      } else if (dtype === "complex64") {
        return 8;
      } else if (dtype === "bool") {
        return 1;
      } else {
        throw new Error("Unknown dtype ".concat(dtype));
      }
    }
    function bytesFromStringArray(arr) {
      if (arr == null) {
        return 0;
      }
      var bytes = 0;
      arr.forEach(function(x) {
        return bytes += x.length;
      });
      return bytes;
    }
    function isString(value) {
      return typeof value === "string" || value instanceof String;
    }
    function isBoolean(value) {
      return typeof value === "boolean";
    }
    function isNumber(value) {
      return typeof value === "number";
    }
    function inferDtype(values) {
      if (Array.isArray(values)) {
        return inferDtype(values[0]);
      }
      if (values instanceof Float32Array) {
        return "float32";
      } else if (values instanceof Int32Array || values instanceof Uint8Array || values instanceof Uint8ClampedArray) {
        return "int32";
      } else if (isNumber(values)) {
        return "float32";
      } else if (isString(values)) {
        return "string";
      } else if (isBoolean(values)) {
        return "bool";
      }
      return "float32";
    }
    function isFunction(f) {
      return !!(f && f.constructor && f.call && f.apply);
    }
    function computeStrides(shape) {
      var rank = shape.length;
      if (rank < 2) {
        return [];
      }
      var strides = new Array(rank - 1);
      strides[rank - 2] = shape[rank - 1];
      for (var i = rank - 3; i >= 0; --i) {
        strides[i] = strides[i + 1] * shape[i + 1];
      }
      return strides;
    }
    function createNestedArray(offset, shape, a, isComplex) {
      if (isComplex === void 0) {
        isComplex = false;
      }
      var ret = new Array();
      if (shape.length === 1) {
        var d = shape[0] * (isComplex ? 2 : 1);
        for (var i = 0; i < d; i++) {
          ret[i] = a[offset + i];
        }
      } else {
        var d = shape[0];
        var rest = shape.slice(1);
        var len = rest.reduce(function(acc, c) {
          return acc * c;
        }) * (isComplex ? 2 : 1);
        for (var i = 0; i < d; i++) {
          ret[i] = createNestedArray(offset + i * len, rest, a, isComplex);
        }
      }
      return ret;
    }
    function toNestedArray(shape, a, isComplex) {
      if (isComplex === void 0) {
        isComplex = false;
      }
      if (shape.length === 0) {
        return a[0];
      }
      var size = shape.reduce(function(acc, c) {
        return acc * c;
      }) * (isComplex ? 2 : 1);
      if (size === 0) {
        return [];
      }
      if (size !== a.length) {
        throw new Error("[".concat(shape, "] does not match the input size ").concat(a.length).concat(isComplex ? " for a complex tensor" : "", "."));
      }
      return createNestedArray(0, shape, a, isComplex);
    }
    function makeOnesTypedArray(size, dtype) {
      var array = makeZerosTypedArray(size, dtype);
      for (var i = 0; i < array.length; i++) {
        array[i] = 1;
      }
      return array;
    }
    function makeZerosTypedArray(size, dtype) {
      if (dtype == null || dtype === "float32" || dtype === "complex64") {
        return new Float32Array(size);
      } else if (dtype === "int32") {
        return new Int32Array(size);
      } else if (dtype === "bool") {
        return new Uint8Array(size);
      } else {
        throw new Error("Unknown data type ".concat(dtype));
      }
    }
    function assertNonNegativeIntegerDimensions(shape) {
      shape.forEach(function(dimSize) {
        assert(Number.isInteger(dimSize) && dimSize >= 0, function() {
          return "Tensor must have a shape comprised of positive integers but got " + "shape [".concat(shape, "].");
        });
      });
    }
    function isPromise(object) {
      return object && object.then && typeof object.then === "function";
    }
    var TENSORFLOWJS_FLAGS_PREFIX = "tfjsflags";
    var Environment = (
      /** @class */
      function() {
        function Environment2(global2) {
          this.global = global2;
          this.flags = {};
          this.flagRegistry = {};
          this.urlFlags = {};
          this.getQueryParams = getQueryParams;
          this.populateURLFlags();
        }
        Environment2.prototype.setPlatform = function(platformName, platform) {
          if (this.platform != null) {
            if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) {
              console.warn("Platform ".concat(this.platformName, " has already been set. ") + "Overwriting the platform with ".concat(platformName, "."));
            }
          }
          this.platformName = platformName;
          this.platform = platform;
        };
        Environment2.prototype.registerFlag = function(flagName, evaluationFn, setHook) {
          this.flagRegistry[flagName] = { evaluationFn, setHook };
          if (this.urlFlags[flagName] != null) {
            var flagValue = this.urlFlags[flagName];
            if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) {
              console.warn("Setting feature override from URL ".concat(flagName, ": ").concat(flagValue, "."));
            }
            this.set(flagName, flagValue);
          }
        };
        Environment2.prototype.getAsync = function(flagName) {
          return __awaiter(this, void 0, void 0, function() {
            var _a2, _b;
            return __generator(this, function(_c) {
              switch (_c.label) {
                case 0:
                  if (flagName in this.flags) {
                    return [2, this.flags[flagName]];
                  }
                  _a2 = this.flags;
                  _b = flagName;
                  return [4, this.evaluateFlag(flagName)];
                case 1:
                  _a2[_b] = _c.sent();
                  return [2, this.flags[flagName]];
              }
            });
          });
        };
        Environment2.prototype.get = function(flagName) {
          if (flagName in this.flags) {
            return this.flags[flagName];
          }
          var flagValue = this.evaluateFlag(flagName);
          if (isPromise(flagValue)) {
            throw new Error("Flag ".concat(flagName, " cannot be synchronously evaluated. ") + "Please use getAsync() instead.");
          }
          this.flags[flagName] = flagValue;
          return this.flags[flagName];
        };
        Environment2.prototype.getNumber = function(flagName) {
          return this.get(flagName);
        };
        Environment2.prototype.getBool = function(flagName) {
          return this.get(flagName);
        };
        Environment2.prototype.getString = function(flagName) {
          return this.get(flagName);
        };
        Environment2.prototype.getFlags = function() {
          return this.flags;
        };
        Object.defineProperty(Environment2.prototype, "features", {
          // For backwards compatibility.
          get: function() {
            return this.flags;
          },
          enumerable: false,
          configurable: true
        });
        Environment2.prototype.set = function(flagName, value) {
          if (this.flagRegistry[flagName] == null) {
            throw new Error("Cannot set flag ".concat(flagName, " as it has not been registered."));
          }
          this.flags[flagName] = value;
          if (this.flagRegistry[flagName].setHook != null) {
            this.flagRegistry[flagName].setHook(value);
          }
        };
        Environment2.prototype.evaluateFlag = function(flagName) {
          if (this.flagRegistry[flagName] == null) {
            throw new Error("Cannot evaluate flag '".concat(flagName, "': no evaluation function found."));
          }
          return this.flagRegistry[flagName].evaluationFn();
        };
        Environment2.prototype.setFlags = function(flags) {
          this.flags = Object.assign({}, flags);
        };
        Environment2.prototype.reset = function() {
          this.flags = {};
          this.urlFlags = {};
          this.populateURLFlags();
        };
        Environment2.prototype.populateURLFlags = function() {
          var _this = this;
          if (typeof this.global === "undefined" || typeof this.global.location === "undefined" || typeof this.global.location.search === "undefined") {
            return;
          }
          var urlParams = this.getQueryParams(this.global.location.search);
          if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {
            var keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(",");
            keyValues.forEach(function(keyValue) {
              var _a2 = __read(keyValue.split(":"), 2), key = _a2[0], value = _a2[1];
              _this.urlFlags[key] = parseValue(key, value);
            });
          }
        };
        return Environment2;
      }()
    );
    function getQueryParams(queryString) {
      var params = {};
      queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, function(s) {
        var t = [];
        for (var _i = 1; _i < arguments.length; _i++) {
          t[_i - 1] = arguments[_i];
        }
        decodeParam(params, t[0], t[1]);
        return t.join("=");
      });
      return params;
    }
    function decodeParam(params, name, value) {
      params[decodeURIComponent(name)] = decodeURIComponent(value || "");
    }
    function parseValue(flagName, value) {
      var lowerCaseValue = value.toLowerCase();
      if (lowerCaseValue === "true" || lowerCaseValue === "false") {
        return lowerCaseValue === "true";
      } else if ("".concat(+lowerCaseValue) === lowerCaseValue) {
        return +lowerCaseValue;
      } else {
        return value;
      }
    }
    function env() {
      return ENV$1;
    }
    var ENV$1 = null;
    function setEnvironmentGlobal(environment) {
      ENV$1 = environment;
    }
    var globalNameSpace;
    function getGlobalNamespace() {
      if (globalNameSpace == null) {
        var ns = void 0;
        if (typeof window !== "undefined") {
          ns = window;
        } else if (typeof global !== "undefined") {
          ns = global;
        } else if (typeof process !== "undefined") {
          ns = process;
        } else if (typeof self !== "undefined") {
          ns = self;
        } else {
          throw new Error("Could not find a global object");
        }
        globalNameSpace = ns;
      }
      return globalNameSpace;
    }
    function getGlobalMap() {
      var ns = getGlobalNamespace();
      if (ns._tfGlobals == null) {
        ns._tfGlobals = /* @__PURE__ */ new Map();
      }
      return ns._tfGlobals;
    }
    function getGlobal(key, init) {
      var globalMap = getGlobalMap();
      if (globalMap.has(key)) {
        return globalMap.get(key);
      } else {
        var singleton = init();
        globalMap.set(key, singleton);
        return globalMap.get(key);
      }
    }
    function warn() {
      var msg = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        msg[_i] = arguments[_i];
      }
      if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) {
        console.warn.apply(console, __spreadArray([], __read(msg), false));
      }
    }
    var kernelRegistry = getGlobal("kernelRegistry", function() {
      return /* @__PURE__ */ new Map();
    });
    var gradRegistry = getGlobal("gradRegistry", function() {
      return /* @__PURE__ */ new Map();
    });
    function getKernel(kernelName, backendName) {
      var key = makeKey(kernelName, backendName);
      return kernelRegistry.get(key);
    }
    function getGradient(kernelName) {
      return gradRegistry.get(kernelName);
    }
    function getKernelsForBackend(backendName) {
      var it = kernelRegistry.entries();
      var result = [];
      while (true) {
        var _a2 = it.next(), done = _a2.done, value = _a2.value;
        if (done) {
          break;
        }
        var _b = __read(value, 2), key = _b[0], config = _b[1];
        var _c = __read(key.split("_"), 1), backend = _c[0];
        if (backend === backendName) {
          result.push(config);
        }
      }
      return result;
    }
    function registerGradient(config) {
      var kernelName = config.kernelName;
      if (gradRegistry.has(kernelName)) {
        if (env().getBool("DEBUG")) {
          warn("Overriding the gradient for '".concat(kernelName, "'"));
        }
      }
      gradRegistry.set(kernelName, config);
    }
    function makeKey(kernelName, backendName) {
      return "".concat(backendName, "_").concat(kernelName);
    }
    function isTypedArrayBrowser(a) {
      return a instanceof Float32Array || a instanceof Int32Array || a instanceof Uint8Array || a instanceof Uint8ClampedArray;
    }
    var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
    function getDefaultExportFromCjs(x) {
      return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
    }
    function getAugmentedNamespace(n) {
      if (n.__esModule)
        return n;
      var f = n.default;
      if (typeof f == "function") {
        var a = function a2() {
          if (this instanceof a2) {
            var args = [null];
            args.push.apply(args, arguments);
            var Ctor = Function.bind.apply(f, args);
            return new Ctor();
          }
          return f.apply(this, arguments);
        };
        a.prototype = f.prototype;
      } else
        a = {};
      Object.defineProperty(a, "__esModule", { value: true });
      Object.keys(n).forEach(function(k) {
        var d = Object.getOwnPropertyDescriptor(n, k);
        Object.defineProperty(a, k, d.get ? d : {
          enumerable: true,
          get: function() {
            return n[k];
          }
        });
      });
      return a;
    }
    var long = Long$1;
    var wasm = null;
    try {
      wasm = 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 Long$1(low, high, unsigned) {
      this.low = low | 0;
      this.high = high | 0;
      this.unsigned = !!unsigned;
    }
    Long$1.prototype.__isLong__;
    Object.defineProperty(Long$1.prototype, "__isLong__", { value: true });
    function isLong(obj) {
      return (obj && obj["__isLong__"]) === true;
    }
    Long$1.isLong = isLong;
    var INT_CACHE = {};
    var UINT_CACHE = {};
    function fromInt(value, unsigned) {
      var obj, cachedObj, cache;
      if (unsigned) {
        value >>>= 0;
        if (cache = 0 <= value && value < 256) {
          cachedObj = UINT_CACHE[value];
          if (cachedObj)
            return cachedObj;
        }
        obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
        if (cache)
          UINT_CACHE[value] = obj;
        return obj;
      } else {
        value |= 0;
        if (cache = -128 <= value && value < 128) {
          cachedObj = INT_CACHE[value];
          if (cachedObj)
            return cachedObj;
        }
        obj = fromBits(value, value < 0 ? -1 : 0, false);
        if (cache)
          INT_CACHE[value] = obj;
        return obj;
      }
    }
    Long$1.fromInt = fromInt;
    function fromNumber(value, unsigned) {
      if (isNaN(value))
        return unsigned ? UZERO : ZERO;
      if (unsigned) {
        if (value < 0)
          return UZERO;
        if (value >= TWO_PWR_64_DBL)
          return MAX_UNSIGNED_VALUE;
      } else {
        if (value <= -TWO_PWR_63_DBL)
          return MIN_VALUE;
        if (value + 1 >= TWO_PWR_63_DBL)
          return MAX_VALUE;
      }
      if (value < 0)
        return fromNumber(-value, unsigned).neg();
      return fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned);
    }
    Long$1.fromNumber = fromNumber;
    function fromBits(lowBits, highBits, unsigned) {
      return new Long$1(lowBits, highBits, unsigned);
    }
    Long$1.fromBits = fromBits;
    var pow_dbl = Math.pow;
    function fromString(str, unsigned, radix) {
      if (str.length === 0)
        throw Error("empty string");
      if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
        return ZERO;
      if (typeof unsigned === "number") {
        radix = unsigned, unsigned = false;
      } else {
        unsigned = !!unsigned;
      }
      radix = radix || 10;
      if (radix < 2 || 36 < radix)
        throw RangeError("radix");
      var p;
      if ((p = str.indexOf("-")) > 0)
        throw Error("interior hyphen");
      else if (p === 0) {
        return fromString(str.substring(1), unsigned, radix).neg();
      }
      var radixToPower = fromNumber(pow_dbl(radix, 8));
      var result = ZERO;
      for (var i = 0; i < str.length; i += 8) {
        var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
        if (size < 8) {
          var power = fromNumber(pow_dbl(radix, size));
          result = result.mul(power).add(fromNumber(value));
        } else {
          result = result.mul(radixToPower);
          result = result.add(fromNumber(value));
        }
      }
      result.unsigned = unsigned;
      return result;
    }
    Long$1.fromString = fromString;
    function fromValue(val, unsigned) {
      if (typeof val === "number")
        return fromNumber(val, unsigned);
      if (typeof val === "string")
        return fromString(val, unsigned);
      return fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned);
    }
    Long$1.fromValue = fromValue;
    var TWO_PWR_16_DBL = 1 << 16;
    var TWO_PWR_24_DBL = 1 << 24;
    var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
    var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
    var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
    var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
    var ZERO = fromInt(0);
    Long$1.ZERO = ZERO;
    var UZERO = fromInt(0, true);
    Long$1.UZERO = UZERO;
    var ONE = fromInt(1);
    Long$1.ONE = ONE;
    var UONE = fromInt(1, true);
    Long$1.UONE = UONE;
    var NEG_ONE = fromInt(-1);
    Long$1.NEG_ONE = NEG_ONE;
    var MAX_VALUE = fromBits(4294967295 | 0, 2147483647 | 0, false);
    Long$1.MAX_VALUE = MAX_VALUE;
    var MAX_UNSIGNED_VALUE = fromBits(4294967295 | 0, 4294967295 | 0, true);
    Long$1.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
    var MIN_VALUE = fromBits(0, 2147483648 | 0, false);
    Long$1.MIN_VALUE = MIN_VALUE;
    var LongPrototype = Long$1.prototype;
    LongPrototype.toInt = function toInt() {
      return this.unsigned ? this.low >>> 0 : this.low;
    };
    LongPrototype.toNumber = function toNumber() {
      if (this.unsigned)
        return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
      return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
    };
    LongPrototype.toString = function toString(radix) {
      radix = radix || 10;
      if (radix < 2 || 36 < radix)
        throw RangeError("radix");
      if (this.isZero())
        return "0";
      if (this.isNegative()) {
        if (this.eq(MIN_VALUE)) {
          var radixLong = fromNumber(radix), div2 = this.div(radixLong), rem1 = div2.mul(radixLong).sub(this);
          return div2.toString(radix) + rem1.toInt().toString(radix);
        } else
          return "-" + this.neg().toString(radix);
      }
      var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), rem = this;
      var result = "";
      while (true) {
        var remDiv = rem.div(radixToPower), intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, digits = intval.toString(radix);
        rem = remDiv;
        if (rem.isZero())
          return digits + result;
        else {
          while (digits.length < 6)
            digits = "0" + digits;
          result = "" + digits + result;
        }
      }
    };
    LongPrototype.getHighBits = function getHighBits() {
      return this.high;
    };
    LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
      return this.high >>> 0;
    };
    LongPrototype.getLowBits = function getLowBits() {
      return this.low;
    };
    LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
      return this.low >>> 0;
    };
    LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
      if (this.isNegative())
        return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
      var val = this.high != 0 ? this.high : this.low;
      for (var bit = 31; bit > 0; bit--)
        if ((val & 1 << bit) != 0)
          break;
      return this.high != 0 ? bit + 33 : bit + 1;
    };
    LongPrototype.isZero = function isZero() {
      return this.high === 0 && this.low === 0;
    };
    LongPrototype.eqz = LongPrototype.isZero;
    LongPrototype.isNegative = function isNegative() {
      return !this.unsigned && this.high < 0;
    };
    LongPrototype.isPositive = function isPositive() {
      return this.unsigned || this.high >= 0;
    };
    LongPrototype.isOdd = function isOdd() {
      return (this.low & 1) === 1;
    };
    LongPrototype.isEven = function isEven() {
      return (this.low & 1) === 0;
    };
    LongPrototype.equals = function equals(other) {
      if (!isLong(other))
        other = fromValue(other);
      if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
        return false;
      return this.high === other.high && this.low === other.low;
    };
    LongPrototype.eq = LongPrototype.equals;
    LongPrototype.notEquals = function notEquals(other) {
      return !this.eq(
        /* validates */
        other
      );
    };
    LongPrototype.neq = LongPrototype.notEquals;
    LongPrototype.ne = LongPrototype.notEquals;
    LongPrototype.lessThan = function lessThan(other) {
      return this.comp(
        /* validates */
        other
      ) < 0;
    };
    LongPrototype.lt = LongPrototype.lessThan;
    LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
      return this.comp(
        /* validates */
        other
      ) <= 0;
    };
    LongPrototype.lte = LongPrototype.lessThanOrEqual;
    LongPrototype.le = LongPrototype.lessThanOrEqual;
    LongPrototype.greaterThan = function greaterThan(other) {
      return this.comp(
        /* validates */
        other
      ) > 0;
    };
    LongPrototype.gt = LongPrototype.greaterThan;
    LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
      return this.comp(
        /* validates */
        other
      ) >= 0;
    };
    LongPrototype.gte = LongPrototype.greaterThanOrEqual;
    LongPrototype.ge = LongPrototype.greaterThanOrEqual;
    LongPrototype.compare = function compare(other) {
      if (!isLong(other))
        other = fromValue(other);
      if (this.eq(other))
        return 0;
      var thisNeg = this.isNegative(), otherNeg = other.isNegative();
      if (thisNeg && !otherNeg)
        return -1;
      if (!thisNeg && otherNeg)
        return 1;
      if (!this.unsigned)
        return this.sub(other).isNegative() ? -1 : 1;
      return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1;
    };
    LongPrototype.comp = LongPrototype.compare;
    LongPrototype.negate = function negate() {
      if (!this.unsigned && this.eq(MIN_VALUE))
        return MIN_VALUE;
      return this.not().add(ONE);
    };
    LongPrototype.neg = LongPrototype.negate;
    LongPrototype.add = function add2(addend) {
      if (!isLong(addend))
        addend = fromValue(addend);
      var a48 = this.high >>> 16;
      var a32 = this.high & 65535;
      var a16 = this.low >>> 16;
      var a00 = this.low & 65535;
      var b48 = addend.high >>> 16;
      var b32 = addend.high & 65535;
      var b16 = addend.low >>> 16;
      var b00 = addend.low & 65535;
      var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
      c00 += a00 + b00;
      c16 += c00 >>> 16;
      c00 &= 65535;
      c16 += a16 + b16;
      c32 += c16 >>> 16;
      c16 &= 65535;
      c32 += a32 + b32;
      c48 += c32 >>> 16;
      c32 &= 65535;
      c48 += a48 + b48;
      c48 &= 65535;
      return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
    };
    LongPrototype.subtract = function subtract(subtrahend) {
      if (!isLong(subtrahend))
        subtrahend = fromValue(subtrahend);
      return this.add(subtrahend.neg());
    };
    LongPrototype.sub = LongPrototype.subtract;
    LongPrototype.multiply = function multiply2(multiplier) {
      if (this.isZero())
        return ZERO;
      if (!isLong(multiplier))
        multiplier = fromValue(multiplier);
      if (wasm) {
        var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
        return fromBits(low, wasm.get_high(), this.unsigned);
      }
      if (multiplier.isZero())
        return ZERO;
      if (this.eq(MIN_VALUE))
        return multiplier.isOdd() ? MIN_VALUE : ZERO;
      if (multiplier.eq(MIN_VALUE))
        return this.isOdd() ? MIN_VALUE : ZERO;
      if (this.isNegative()) {
        if (multiplier.isNegative())
          return this.neg().mul(multiplier.neg());
        else
          return this.neg().mul(multiplier).neg();
      } else if (multiplier.isNegative())
        return this.mul(multiplier.neg()).neg();
      if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
        return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
      var a48 = this.high >>> 16;
      var a32 = this.high & 65535;
      var a16 = this.low >>> 16;
      var a00 = this.low & 65535;
      var b48 = multiplier.high >>> 16;
      var b32 = multiplier.high & 65535;
      var b16 = multiplier.low >>> 16;
      var b00 = multiplier.low & 65535;
      var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
      c00 += a00 * b00;
      c16 += c00 >>> 16;
      c00 &= 65535;
      c16 += a16 * b00;
      c32 += c16 >>> 16;
      c16 &= 65535;
      c16 += a00 * b16;
      c32 += c16 >>> 16;
      c16 &= 65535;
      c32 += a32 * b00;
      c48 += c32 >>> 16;
      c32 &= 65535;
      c32 += a16 * b16;
      c48 += c32 >>> 16;
      c32 &= 65535;
      c32 += a00 * b32;
      c48 += c32 >>> 16;
      c32 &= 65535;
      c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
      c48 &= 65535;
      return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
    };
    LongPrototype.mul = LongPrototype.multiply;
    LongPrototype.divide = function divide(divisor) {
      if (!isLong(divisor))
        divisor = fromValue(divisor);
      if (divisor.isZero())
        throw Error("division by zero");
      if (wasm) {
        if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) {
          return this;
        }
        var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
        return fromBits(low, wasm.get_high(), this.unsigned);
      }
      if (this.isZero())
        return this.unsigned ? UZERO : ZERO;
      var approx, rem, res;
      if (!this.unsigned) {
        if (this.eq(MIN_VALUE)) {
          if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
            return MIN_VALUE;
          else if (divisor.eq(MIN_VALUE))
            return ONE;
          else {
            var halfThis = this.shr(1);
            approx = halfThis.div(divisor).shl(1);
            if (approx.eq(ZERO)) {
              return divisor.isNegative() ? ONE : NEG_ONE;
            } else {
              rem = this.sub(divisor.mul(approx));
              res = approx.add(rem.div(divisor));
              return res;
            }
          }
        } else if (divisor.eq(MIN_VALUE))
          return this.unsigned ? UZERO : ZERO;
        if (this.isNegative()) {
          if (divisor.isNegative())
            return this.neg().div(divisor.neg());
          return this.neg().div(divisor).neg();
        } else if (divisor.isNegative())
          return this.div(divisor.neg()).neg();
        res = ZERO;
      } else {
        if (!divisor.unsigned)
          divisor = divisor.toUnsigned();
        if (divisor.gt(this))
          return UZERO;
        if (divisor.gt(this.shru(1)))
          return UONE;
        res = UZERO;
      }
      rem = this;
      while (rem.gte(divisor)) {
        approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
        var log2 = Math.ceil(Math.log(approx) / Math.LN2), delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48), approxRes = fromNumber(approx), approxRem = approxRes.mul(divisor);
        while (approxRem.isNegative() || approxRem.gt(rem)) {
          approx -= delta;
          approxRes = fromNumber(approx, this.unsigned);
          approxRem = approxRes.mul(divisor);
        }
        if (approxRes.isZero())
          approxRes = ONE;
        res = res.add(approxRes);
        rem = rem.sub(approxRem);
      }
      return res;
    };
    LongPrototype.div = LongPrototype.divide;
    LongPrototype.modulo = function modulo(divisor) {
      if (!isLong(divisor))
        divisor = fromValue(divisor);
      if (wasm) {
        var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
        return fromBits(low, wasm.get_high(), this.unsigned);
      }
      return this.sub(this.div(divisor).mul(divisor));
    };
    LongPrototype.mod = LongPrototype.modulo;
    LongPrototype.rem = LongPrototype.modulo;
    LongPrototype.not = function not() {
      return fromBits(~this.low, ~this.high, this.unsigned);
    };
    LongPrototype.and = function and(other) {
      if (!isLong(other))
        other = fromValue(other);
      return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
    };
    LongPrototype.or = function or(other) {
      if (!isLong(other))
        other = fromValue(other);
      return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
    };
    LongPrototype.xor = function xor(other) {
      if (!isLong(other))
        other = fromValue(other);
      return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
    };
    LongPrototype.shiftLeft = function shiftLeft(numBits) {
      if (isLong(numBits))
        numBits = numBits.toInt();
      if ((numBits &= 63) === 0)
        return this;
      else if (numBits < 32)
        return fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned);
      else
        return fromBits(0, this.low << numBits - 32, this.unsigned);
    };
    LongPrototype.shl = LongPrototype.shiftLeft;
    LongPrototype.shiftRight = function shiftRight(numBits) {
      if (isLong(numBits))
        numBits = numBits.toInt();
      if ((numBits &= 63) === 0)
        return this;
      else if (numBits < 32)
        return fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned);
      else
        return fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned);
    };
    LongPrototype.shr = LongPrototype.shiftRight;
    LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
      if (isLong(numBits))
        numBits = numBits.toInt();
      numBits &= 63;
      if (numBits === 0)
        return this;
      else {
        var high = this.high;
        if (numBits < 32) {
          var low = this.low;
          return fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits, this.unsigned);
        } else if (numBits === 32)
          return fromBits(high, 0, this.unsigned);
        else
          return fromBits(high >>> numBits - 32, 0, this.unsigned);
      }
    };
    LongPrototype.shru = LongPrototype.shiftRightUnsigned;
    LongPrototype.shr_u = LongPrototype.shiftRightUnsigned;
    LongPrototype.toSigned = function toSigned() {
      if (!this.unsigned)
        return this;
      return fromBits(this.low, this.high, false);
    };
    LongPrototype.toUnsigned = function toUnsigned() {
      if (this.unsigned)
        return this;
      return fromBits(this.low, this.high, true);
    };
    LongPrototype.toBytes = function toBytes(le) {
      return le ? this.toBytesLE() : this.toBytesBE();
    };
    LongPrototype.toBytesLE = function toBytesLE() {
      var hi = this.high, lo = this.low;
      return [
        lo & 255,
        lo >>> 8 & 255,
        lo >>> 16 & 255,
        lo >>> 24,
        hi & 255,
        hi >>> 8 & 255,
        hi >>> 16 & 255,
        hi >>> 24
      ];
    };
    LongPrototype.toBytesBE = function toBytesBE() {
      var hi = this.high, lo = this.low;
      return [
        hi >>> 24,
        hi >>> 16 & 255,
        hi >>> 8 & 255,
        hi & 255,
        lo >>> 24,
        lo >>> 16 & 255,
        lo >>> 8 & 255,
        lo & 255
      ];
    };
    Long$1.fromBytes = function fromBytes(bytes, unsigned, le) {
      return le ? Long$1.fromBytesLE(bytes, unsigned) : Long$1.fromBytesBE(bytes, unsigned);
    };
    Long$1.fromBytesLE = function fromBytesLE(bytes, unsigned) {
      return new Long$1(bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, unsigned);
    };
    Long$1.fromBytesBE = function fromBytesBE(bytes, unsigned) {
      return new Long$1(bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], unsigned);
    };
    var long$1 = /* @__PURE__ */ getDefaultExportFromCjs(long);
    var LongExports = /* @__PURE__ */ _mergeNamespaces({
      __proto__: null,
      default: long$1
    }, [long]);
    var Long = (
      // tslint:disable-next-line
      long$1 || LongExports
    );
    function hexToLong(hex) {
      return Long.fromString(hex, true, 16);
    }
    hexToLong("c3a5c85c97cb3127");
    hexToLong("b492b66fbe98f273");
    hexToLong("9ae16a3b2f90404f");
    function noConversionNeeded(a, dtype) {
      return a instanceof Float32Array && dtype === "float32" || a instanceof Int32Array && dtype === "int32" || a instanceof Uint8Array && dtype === "bool";
    }
    function toTypedArray(a, dtype) {
      if (dtype === "string") {
        throw new Error("Cannot convert a string[] to a TypedArray");
      }
      if (Array.isArray(a)) {
        a = flatten$1(a);
      }
      if (env().getBool("DEBUG")) {
        checkConversionForErrors(a, dtype);
      }
      if (noConversionNeeded(a, dtype)) {
        return a;
      }
      if (dtype == null || dtype === "float32" || dtype === "complex64") {
        return new Float32Array(a);
      } else if (dtype === "int32") {
        return new Int32Array(a);
      } else if (dtype === "bool") {
        var bool = new Uint8Array(a.length);
        for (var i = 0; i < bool.length; ++i) {
          if (Math.round(a[i]) !== 0) {
            bool[i] = 1;
          }
        }
        return bool;
      } else {
        throw new Error("Unknown data type ".concat(dtype));
      }
    }
    function now() {
      return env().platform.now();
    }
    function encodeString(s, encoding) {
      if (encoding === void 0) {
        encoding = "utf-8";
      }
      encoding = encoding || "utf-8";
      return env().platform.encode(s, encoding);
    }
    function decodeString(bytes, encoding) {
      if (encoding === void 0) {
        encoding = "utf-8";
      }
      encoding = encoding || "utf-8";
      return env().platform.decode(bytes, encoding);
    }
    function isTypedArray(a) {
      if (env().platform.isTypedArray != null) {
        return env().platform.isTypedArray(a);
      } else {
        return isTypedArrayBrowser(a);
      }
    }
    function flatten$1(arr, result, skipTypedArray) {
      var e_12, _a2;
      if (result === void 0) {
        result = [];
      }
      if (skipTypedArray === void 0) {
        skipTypedArray = false;
      }
      if (result == null) {
        result = [];
      }
      if (typeof arr === "boolean" || typeof arr === "number" || typeof arr === "string" || isPromise(arr) || arr == null || isTypedArray(arr) && skipTypedArray) {
        result.push(arr);
      } else if (Array.isArray(arr) || isTypedArray(arr)) {
        for (var i = 0; i < arr.length; ++i) {
          flatten$1(arr[i], result, skipTypedArray);
        }
      } else {
        var maxIndex = -1;
        try {
          for (var _b = __values(Object.keys(arr)), _c = _b.next(); !_c.done; _c = _b.next()) {
            var key = _c.value;
            if (/^([1-9]+[0-9]*|0)$/.test(key)) {
              maxIndex = Math.max(maxIndex, Number(key));
            }
          }
        } catch (e_1_1) {
          e_12 = { error: e_1_1 };
        } finally {
          try {
            if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
          } finally {
            if (e_12) throw e_12.error;
          }
        }
        for (var i = 0; i <= maxIndex; i++) {
          flatten$1(arr[i], result, skipTypedArray);
        }
      }
      return result;
    }
    var Profiler = (
      /** @class */
      function() {
        function Profiler2(backendTimer, logger) {
          this.backendTimer = backendTimer;
          this.logger = logger;
          if (logger == null) {
            this.logger = new Logger();
          }
        }
        Profiler2.prototype.profileKernel = function(kernelName, inputs, f) {
          var e_12, _a2;
          var outputs;
          var holdResultWrapperFn = function() {
            outputs = f();
          };
          var timer;
          var start = now();
          if (this.backendTimer.timerAvailable()) {
            timer = this.backendTimer.time(holdResultWrapperFn);
          } else {
            holdResultWrapperFn();
            try {
              for (var outputs_1 = __values(outputs), outputs_1_1 = outputs_1.next(); !outputs_1_1.done; outputs_1_1 = outputs_1.next()) {
                var output = outputs_1_1.value;
                output.dataSync();
              }
            } catch (e_1_1) {
              e_12 = { error: e_1_1 };
            } finally {
              try {
                if (outputs_1_1 && !outputs_1_1.done && (_a2 = outputs_1.return)) _a2.call(outputs_1);
              } finally {
                if (e_12) throw e_12.error;
              }
            }
            timer = Promise.resolve({ kernelMs: now() - start });
          }
          if (env().getBool("CHECK_COMPUTATION_FOR_ERRORS")) {
            var _loop_1 = function(i2) {
              var output2 = outputs[i2];
              output2.data().then(function(tensorVals) {
                checkComputationForErrors(tensorVals, output2.dtype, kernelName);
              });
            };
            for (var i = 0; i < outputs.length; i++) {
              _loop_1(i);
            }
          }
          var kernelProfile = {
            kernelName,
            outputs,
            inputs,
            timeMs: timer.then(function(timing) {
              return timing.kernelMs;
            }),
            extraInfo: timer.then(function(timing) {
              return timing.getExtraProfileInfo != null ? timing.getExtraProfileInfo() : "";
            })
          };
          return kernelProfile;
        };
        Profiler2.prototype.logKernelProfile = function(kernelProfile) {
          var _this = this;
          var kernelName = kernelProfile.kernelName, outputs = kernelProfile.outputs, timeMs = kernelProfile.timeMs, inputs = kernelProfile.inputs, extraInfo = kernelProfile.extraInfo;
          outputs.forEach(function(result) {
            Promise.all([result.data(), timeMs, extraInfo]).then(function(valueContainer) {
              _this.logger.logKernelProfile(kernelName, result, valueContainer[0], valueContainer[1], inputs, valueContainer[2]);
            });
          });
        };
        return Profiler2;
      }()
    );
    function checkComputationForErrors(vals, dtype, kernelName) {
      if (dtype !== "float32") {
        return false;
      }
      for (var i = 0; i < vals.length; i++) {
        var num = vals[i];
        if (isNaN(num) || !isFinite(num)) {
          console.warn("Found ".concat(num, " in the result of '").concat(kernelName, "'"));
          return true;
        }
      }
      return false;
    }
    var Logger = (
      /** @class */
      function() {
        function Logger2() {
        }
        Logger2.prototype.logKernelProfile = function(name, result, vals, timeMs, inputs, extraInfo) {
          var time = typeof timeMs === "number" ? rightPad("".concat(timeMs, "ms"), 9) : timeMs["error"];
          var paddedName = rightPad(name, 25);
          var rank = result.rank;
          var size = result.size;
          var shape = rightPad(result.shape.toString(), 14);
          var inputShapesDescription = "";
          for (var name_1 in inputs) {
            var input2 = inputs[name_1];
            if (input2 != null) {
              var inputShape = input2.shape || result.shape;
              var inputRank = inputShape.length;
              inputShapesDescription += "".concat(name_1, ": ").concat(inputRank, "D ").concat(inputRank > 0 ? inputShape : "", " ");
            }
          }
          console.log("%c".concat(paddedName, "	%c").concat(time, "	%c").concat(rank, "D ").concat(shape, "	%c").concat(size, "	%c").concat(inputShapesDescription, "	%c").concat(extraInfo), "font-weight:bold", "color:red", "color:blue", "color: orange", "color: green", "color: steelblue");
        };
        return Logger2;
      }()
    );
    function getFilteredNodesXToY(tape, xs, y) {
      var tensorsFromX = {};
      var nodesFromX = {};
      for (var i = 0; i < xs.length; i++) {
        tensorsFromX[xs[i].id] = true;
      }
      for (var i = 0; i < tape.length; i++) {
        var node = tape[i];
        var nodeInputs = node.inputs;
        for (var inputName in nodeInputs) {
          var input2 = nodeInputs[inputName];
          var anyInputFromX = false;
          for (var j = 0; j < xs.length; j++) {
            if (tensorsFromX[input2.id]) {
              node.outputs.forEach(function(output) {
                return tensorsFromX[output.id] = true;
              });
              anyInputFromX = true;
              nodesFromX[node.id] = true;
              break;
            }
          }
          if (anyInputFromX) {
            break;
          }
        }
      }
      var tensorsLeadToY = {};
      tensorsLeadToY[y.id] = true;
      var nodesToY = {};
      for (var i = tape.length - 1; i >= 0; i--) {
        var node = tape[i];
        var nodeInputs = node.inputs;
        for (var j = 0; j < node.outputs.length; j++) {
          if (tensorsLeadToY[node.outputs[j].id]) {
            for (var inputName in nodeInputs) {
              tensorsLeadToY[nodeInputs[inputName].id] = true;
              nodesToY[node.id] = true;
            }
            break;
          }
        }
      }
      var filteredTape = [];
      for (var i = 0; i < tape.length; i++) {
        var node = tape[i];
        if (nodesFromX[node.id] && nodesToY[node.id]) {
          var prunedInputs = {};
          for (var inputName in node.inputs) {
            var nodeInput = node.inputs[inputName];
            if (tensorsFromX[nodeInput.id]) {
              prunedInputs[inputName] = nodeInput;
            }
          }
          var prunedNode = Object.assign({}, node);
          prunedNode.inputs = prunedInputs;
          prunedNode.outputs = node.outputs;
          filteredTape.push(prunedNode);
        }
      }
      return filteredTape;
    }
    function backpropagateGradients(tensorAccumulatedGradientMap, filteredTape, tidy2, add2) {
      var _loop_1 = function(i2) {
        var node = filteredTape[i2];
        var dys = [];
        node.outputs.forEach(function(o) {
          var gradTensor = tensorAccumulatedGradientMap[o.id];
          if (gradTensor != null) {
            dys.push(gradTensor);
          } else {
            dys.push(null);
          }
        });
        if (node.gradient == null) {
          throw new Error("Cannot compute gradient: gradient function not found " + "for ".concat(node.kernelName, "."));
        }
        var inputGradients = node.gradient(dys);
        var _loop_2 = function(inputName2) {
          if (!(inputName2 in inputGradients)) {
            throw new Error("Cannot backprop through input ".concat(inputName2, ". ") + "Available gradients found: ".concat(Object.keys(inputGradients), "."));
          }
          var dx = tidy2(function() {
            return inputGradients[inputName2]();
          });
          if (dx.dtype !== "float32") {
            throw new Error("Error in gradient for op ".concat(node.kernelName, ". The gradient of input ") + "".concat(inputName2, " must have 'float32' dtype, but has '").concat(dx.dtype, "'"));
          }
          var x = node.inputs[inputName2];
          if (!arraysEqual(dx.shape, x.shape)) {
            throw new Error("Error in gradient for op ".concat(node.kernelName, ". The gradient of input ") + "'".concat(inputName2, "' has shape '").concat(dx.shape, "', which does not match ") + "the shape of the input '".concat(x.shape, "'"));
          }
          if (tensorAccumulatedGradientMap[x.id] == null) {
            tensorAccumulatedGradientMap[x.id] = dx;
          } else {
            var curGradient = tensorAccumulatedGradientMap[x.id];
            tensorAccumulatedGradientMap[x.id] = add2(curGradient, dx);
            curGradient.dispose();
          }
        };
        for (var inputName in node.inputs) {
          _loop_2(inputName);
        }
      };
      for (var i = filteredTape.length - 1; i >= 0; i--) {
        _loop_1(i);
      }
    }
    var FORMAT_LIMIT_NUM_VALS = 20;
    var FORMAT_NUM_FIRST_LAST_VALS = 3;
    var FORMAT_NUM_SIG_DIGITS = 7;
    function tensorToString(vals, shape, dtype, verbose) {
      var strides = computeStrides(shape);
      var padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides);
      var rank = shape.length;
      var valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol);
      var lines = ["Tensor"];
      if (verbose) {
        lines.push("  dtype: ".concat(dtype));
        lines.push("  rank: ".concat(rank));
        lines.push("  shape: [".concat(shape, "]"));
        lines.push("  values:");
      }
      lines.push(valsLines.map(function(l) {
        return "    " + l;
      }).join("\n"));
      return lines.join("\n");
    }
    function computeMaxSizePerColumn(vals, shape, dtype, strides) {
      var n = sizeFromShape(shape);
      var numCols = strides[strides.length - 1];
      var padPerCol = new Array(numCols).fill(0);
      var rank = shape.length;
      var valuesOrTuples = dtype === "complex64" ? createComplexTuples(vals) : vals;
      if (rank > 1) {
        for (var row = 0; row < n / numCols; row++) {
          var offset = row * numCols;
          for (var j = 0; j < numCols; j++) {
            padPerCol[j] = Math.max(padPerCol[j], valToString(valuesOrTuples[offset + j], 0, dtype).length);
          }
        }
      }
      return padPerCol;
    }
    function valToString(val, pad2, dtype) {
      var valStr;
      if (Array.isArray(val)) {
        valStr = "".concat(parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS)), " + ") + "".concat(parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS)), "j");
      } else if (isString(val)) {
        valStr = "'".concat(val, "'");
      } else if (dtype === "bool") {
        valStr = boolNumToString(val);
      } else {
        valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString();
      }
      return rightPad(valStr, pad2);
    }
    function boolNumToString(v) {
      return v === 0 ? "false" : "true";
    }
    function subTensorToString(vals, shape, dtype, strides, padPerCol, isLast) {
      if (isLast === void 0) {
        isLast = true;
      }
      var storagePerElement = dtype === "complex64" ? 2 : 1;
      var size = shape[0];
      var rank = shape.length;
      if (rank === 0) {
        if (dtype === "complex64") {
          var complexTuple = createComplexTuples(vals);
          return [valToString(complexTuple[0], 0, dtype)];
        }
        if (dtype === "bool") {
          return [boolNumToString(vals[0])];
        }
        return [vals[0].toString()];
      }
      if (rank === 1) {
        if (size > FORMAT_LIMIT_NUM_VALS) {
          var firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement;
          var firstVals = Array.from(vals.slice(0, firstValsSize));
          var lastVals = Array.from(vals.slice((size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement, size * storagePerElement));
          if (dtype === "complex64") {
            firstVals = createComplexTuples(firstVals);
            lastVals = createComplexTuples(lastVals);
          }
          return [
            "[" + firstVals.map(function(x, i2) {
              return valToString(x, padPerCol[i2], dtype);
            }).join(", ") + ", ..., " + lastVals.map(function(x, i2) {
              return valToString(x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i2], dtype);
            }).join(", ") + "]"
          ];
        }
        var displayVals = dtype === "complex64" ? createComplexTuples(vals) : Array.from(vals);
        return [
          "[" + displayVals.map(function(x, i2) {
            return valToString(x, padPerCol[i2], dtype);
          }).join(", ") + "]"
        ];
      }
      var subshape = shape.slice(1);
      var substrides = strides.slice(1);
      var stride = strides[0] * storagePerElement;
      var lines = [];
      if (size > FORMAT_LIMIT_NUM_VALS) {
        for (var i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {
          var start = i * stride;
          var end = start + stride;
          lines.push.apply(lines, __spreadArray([], __read(subTensorToString(
            vals.slice(start, end),
            subshape,
            dtype,
            substrides,
            padPerCol,
            false
            /* isLast */
          )), false));
        }
        lines.push("...");
        for (var i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {
          var start = i * stride;
          var end = start + stride;
          lines.push.apply(lines, __spreadArray([], __read(subTensorToString(
            vals.slice(start, end),
            subshape,
            dtype,
            substrides,
            padPerCol,
            i === size - 1
            /* isLast */
          )), false));
        }
      } else {
        for (var i = 0; i < size; i++) {
          var start = i * stride;
          var end = start + stride;
          lines.push.apply(lines, __spreadArray([], __read(subTensorToString(
            vals.slice(start, end),
            subshape,
            dtype,
            substrides,
            padPerCol,
            i === size - 1
            /* isLast */
          )), false));
        }
      }
      var sep = rank === 2 ? "," : "";
      lines[0] = "[" + (size > 0 ? lines[0] + sep : "");
      for (var i = 1; i < lines.length - 1; i++) {
        lines[i] = " " + lines[i] + sep;
      }
      var newLineSep = ",\n";
      for (var i = 2; i < rank; i++) {
        newLineSep += "\n";
      }
      lines[lines.length - 1] = " " + lines[lines.length - 1] + "]" + (isLast ? "" : newLineSep);
      return lines;
    }
    function createComplexTuples(vals) {
      var complexTuples = [];
      for (var i = 0; i < vals.length; i += 2) {
        complexTuples.push([vals[i], vals[i + 1]]);
      }
      return complexTuples;
    }
    (function() {
      function TensorBuffer(shape, dtype, values) {
        var _this = this;
        this.dtype = dtype;
        this.shape = shape.slice();
        this.size = sizeFromShape(shape);
        if (values != null) {
          var n_1 = values.length;
          assert(n_1 === this.size, function() {
            return "Length of values '".concat(n_1, "' does not match the size ") + "inferred by the shape '".concat(_this.size, "'.");
          });
        }
        if (dtype === "complex64") {
          throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");
        }
        this.values = values || getArrayFromDType(dtype, this.size);
        this.strides = computeStrides(shape);
      }
      TensorBuffer.prototype.set = function(value) {
        var _this = this;
        var locs = [];
        for (var _i = 1; _i < arguments.length; _i++) {
          locs[_i - 1] = arguments[_i];
        }
        if (locs.length === 0) {
          locs = [0];
        }
        assert(locs.length === this.rank, function() {
          return "The number of provided coordinates (".concat(locs.length, ") must ") + "match the rank (".concat(_this.rank, ")");
        });
        var index = this.locToIndex(locs);
        this.values[index] = value;
      };
      TensorBuffer.prototype.get = function() {
        var e_12, _b;
        var locs = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          locs[_i] = arguments[_i];
        }
        if (locs.length === 0) {
          locs = [0];
        }
        var i = 0;
        try {
          for (var locs_1 = __values(locs), locs_1_1 = locs_1.next(); !locs_1_1.done; locs_1_1 = locs_1.next()) {
            var loc = locs_1_1.value;
            if (loc < 0 || loc >= this.shape[i]) {
              var msg = "Requested out of range element at ".concat(locs, ". ") + "  Buffer shape=".concat(this.shape);
              throw new Error(msg);
            }
            i++;
          }
        } catch (e_1_1) {
          e_12 = { error: e_1_1 };
        } finally {
          try {
            if (locs_1_1 && !locs_1_1.done && (_b = locs_1.return)) _b.call(locs_1);
          } finally {
            if (e_12) throw e_12.error;
          }
        }
        var index = locs[locs.length - 1];
        for (var i_1 = 0; i_1 < locs.length - 1; ++i_1) {
          index += this.strides[i_1] * locs[i_1];
        }
        return this.values[index];
      };
      TensorBuffer.prototype.locToIndex = function(locs) {
        if (this.rank === 0) {
          return 0;
        } else if (this.rank === 1) {
          return locs[0];
        }
        var index = locs[locs.length - 1];
        for (var i = 0; i < locs.length - 1; ++i) {
          index += this.strides[i] * locs[i];
        }
        return index;
      };
      TensorBuffer.prototype.indexToLoc = function(index) {
        if (this.rank === 0) {
          return [];
        } else if (this.rank === 1) {
          return [index];
        }
        var locs = new Array(this.shape.length);
        for (var i = 0; i < locs.length - 1; ++i) {
          locs[i] = Math.floor(index / this.strides[i]);
          index -= locs[i] * this.strides[i];
        }
        locs[locs.length - 1] = index;
        return locs;
      };
      Object.defineProperty(TensorBuffer.prototype, "rank", {
        get: function() {
          return this.shape.length;
        },
        enumerable: false,
        configurable: true
      });
      TensorBuffer.prototype.toTensor = function() {
        return trackerFn().makeTensor(this.values, this.shape, this.dtype);
      };
      return TensorBuffer;
    })();
    var trackerFn = null;
    var opHandler = null;
    function setTensorTracker(fn) {
      trackerFn = fn;
    }
    var Tensor = (
      /** @class */
      function() {
        function Tensor2(shape, dtype, dataId, id) {
          this.kept = false;
          this.isDisposedInternal = false;
          this.shape = shape.slice();
          this.dtype = dtype || "float32";
          this.size = sizeFromShape(shape);
          this.strides = computeStrides(shape);
          this.dataId = dataId;
          this.id = id;
          this.rankType = this.rank < 5 ? this.rank.toString() : "higher";
        }
        Object.defineProperty(Tensor2.prototype, "rank", {
          get: function() {
            return this.shape.length;
          },
          enumerable: false,
          configurable: true
        });
        Tensor2.prototype.buffer = function() {
          return __awaiter(this, void 0, void 0, function() {
            var vals;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  return [4, this.data()];
                case 1:
                  vals = _b.sent();
                  return [2, opHandler.buffer(this.shape, this.dtype, vals)];
              }
            });
          });
        };
        Tensor2.prototype.bufferSync = function() {
          return opHandler.buffer(this.shape, this.dtype, this.dataSync());
        };
        Tensor2.prototype.array = function() {
          return __awaiter(this, void 0, void 0, function() {
            var vals;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  return [4, this.data()];
                case 1:
                  vals = _b.sent();
                  return [2, toNestedArray(this.shape, vals, this.dtype === "complex64")];
              }
            });
          });
        };
        Tensor2.prototype.arraySync = function() {
          return toNestedArray(this.shape, this.dataSync(), this.dtype === "complex64");
        };
        Tensor2.prototype.data = function() {
          return __awaiter(this, void 0, void 0, function() {
            var data, bytes;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  this.throwIfDisposed();
                  data = trackerFn().read(this.dataId);
                  if (!(this.dtype === "string")) return [3, 2];
                  return [4, data];
                case 1:
                  bytes = _b.sent();
                  try {
                    return [2, bytes.map(function(b) {
                      return decodeString(b);
                    })];
                  } catch (_a2) {
                    throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");
                  }
                  _b.label = 2;
                case 2:
                  return [2, data];
              }
            });
          });
        };
        Tensor2.prototype.dataToGPU = function(options) {
          this.throwIfDisposed();
          return trackerFn().readToGPU(this.dataId, options);
        };
        Tensor2.prototype.dataSync = function() {
          this.throwIfDisposed();
          var data = trackerFn().readSync(this.dataId);
          if (this.dtype === "string") {
            try {
              return data.map(function(b) {
                return decodeString(b);
              });
            } catch (_a2) {
              throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");
            }
          }
          return data;
        };
        Tensor2.prototype.bytes = function() {
          return __awaiter(this, void 0, void 0, function() {
            var data;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  this.throwIfDisposed();
                  return [4, trackerFn().read(this.dataId)];
                case 1:
                  data = _b.sent();
                  if (this.dtype === "string") {
                    return [2, data];
                  } else {
                    return [2, new Uint8Array(data.buffer)];
                  }
              }
            });
          });
        };
        Tensor2.prototype.dispose = function() {
          if (this.isDisposed) {
            return;
          }
          if (this.kerasMask) {
            this.kerasMask.dispose();
          }
          trackerFn().disposeTensor(this);
          this.isDisposedInternal = true;
        };
        Object.defineProperty(Tensor2.prototype, "isDisposed", {
          get: function() {
            return this.isDisposedInternal;
          },
          enumerable: false,
          configurable: true
        });
        Tensor2.prototype.throwIfDisposed = function() {
          if (this.isDisposed) {
            throw new Error("Tensor is disposed.");
          }
        };
        Tensor2.prototype.print = function(verbose) {
          if (verbose === void 0) {
            verbose = false;
          }
          return opHandler.print(this, verbose);
        };
        Tensor2.prototype.clone = function() {
          this.throwIfDisposed();
          return opHandler.clone(this);
        };
        Tensor2.prototype.toString = function(verbose) {
          if (verbose === void 0) {
            verbose = false;
          }
          var vals = this.dataSync();
          return tensorToString(vals, this.shape, this.dtype, verbose);
        };
        Tensor2.prototype.cast = function(dtype) {
          this.throwIfDisposed();
          return opHandler.cast(this, dtype);
        };
        Tensor2.prototype.variable = function(trainable, name, dtype) {
          if (trainable === void 0) {
            trainable = true;
          }
          this.throwIfDisposed();
          return trackerFn().makeVariable(this, trainable, name, dtype);
        };
        return Tensor2;
      }()
    );
    Object.defineProperty(Tensor, Symbol.hasInstance, {
      value: function(instance) {
        return !!instance && instance.data != null && instance.dataSync != null && instance.throwIfDisposed != null;
      }
    });
    function getGlobalTensorClass() {
      return getGlobal("Tensor", function() {
        return Tensor;
      });
    }
    getGlobalTensorClass();
    var Variable = (
      /** @class */
      function(_super) {
        __extends(Variable2, _super);
        function Variable2(initialValue, trainable, name, tensorId) {
          var _this = _super.call(this, initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId) || this;
          _this.trainable = trainable;
          _this.name = name;
          return _this;
        }
        Variable2.prototype.assign = function(newValue) {
          if (newValue.dtype !== this.dtype) {
            throw new Error("dtype of the new value (".concat(newValue.dtype, ") and ") + "previous value (".concat(this.dtype, ") must match"));
          }
          if (!arraysEqual(newValue.shape, this.shape)) {
            throw new Error("shape of the new value (".concat(newValue.shape, ") and ") + "previous value (".concat(this.shape, ") must match"));
          }
          trackerFn().disposeTensor(this);
          this.dataId = newValue.dataId;
          trackerFn().incRef(
            this,
            null
            /* backend */
          );
        };
        Variable2.prototype.dispose = function() {
          trackerFn().disposeVariable(this);
          this.isDisposedInternal = true;
        };
        return Variable2;
      }(Tensor)
    );
    Object.defineProperty(Variable, Symbol.hasInstance, {
      value: function(instance) {
        return instance instanceof Tensor && instance.assign != null && instance.assign instanceof Function;
      }
    });
    var Rank;
    (function(Rank2) {
      Rank2["R0"] = "R0";
      Rank2["R1"] = "R1";
      Rank2["R2"] = "R2";
      Rank2["R3"] = "R3";
      Rank2["R4"] = "R4";
      Rank2["R5"] = "R5";
      Rank2["R6"] = "R6";
    })(Rank || (Rank = {}));
    var UpcastInt32AndMap;
    (function(UpcastInt32AndMap2) {
      UpcastInt32AndMap2["float32"] = "float32";
      UpcastInt32AndMap2["int32"] = "int32";
      UpcastInt32AndMap2["bool"] = "int32";
      UpcastInt32AndMap2["complex64"] = "complex64";
    })(UpcastInt32AndMap || (UpcastInt32AndMap = {}));
    var UpcastBoolAndMap;
    (function(UpcastBoolAndMap2) {
      UpcastBoolAndMap2["float32"] = "float32";
      UpcastBoolAndMap2["int32"] = "int32";
      UpcastBoolAndMap2["bool"] = "bool";
      UpcastBoolAndMap2["complex64"] = "complex64";
    })(UpcastBoolAndMap || (UpcastBoolAndMap = {}));
    var UpcastFloat32AndMap;
    (function(UpcastFloat32AndMap2) {
      UpcastFloat32AndMap2["float32"] = "float32";
      UpcastFloat32AndMap2["int32"] = "float32";
      UpcastFloat32AndMap2["bool"] = "float32";
      UpcastFloat32AndMap2["complex64"] = "complex64";
    })(UpcastFloat32AndMap || (UpcastFloat32AndMap = {}));
    var UpcastComplex64AndMap;
    (function(UpcastComplex64AndMap2) {
      UpcastComplex64AndMap2["float32"] = "complex64";
      UpcastComplex64AndMap2["int32"] = "complex64";
      UpcastComplex64AndMap2["bool"] = "complex64";
      UpcastComplex64AndMap2["complex64"] = "complex64";
    })(UpcastComplex64AndMap || (UpcastComplex64AndMap = {}));
    var upcastTypeMap = {
      "float32": UpcastFloat32AndMap,
      "int32": UpcastInt32AndMap,
      "bool": UpcastBoolAndMap,
      "complex64": UpcastComplex64AndMap
    };
    function upcastType(typeA, typeB) {
      if (typeA === "string" || typeB === "string") {
        if (typeA === "string" && typeB === "string") {
          return "string";
        }
        throw new Error("Can not upcast ".concat(typeA, " with ").concat(typeB));
      }
      return upcastTypeMap[typeA][typeB];
    }
    function isWebGLData(values) {
      return values != null && typeof values === "object" && "texture" in values && values.texture instanceof WebGLTexture;
    }
    function isWebGPUData(values) {
      return typeof GPUBuffer !== "undefined" && values != null && typeof values === "object" && "buffer" in values && values.buffer instanceof GPUBuffer;
    }
    function makeTypesMatch(a, b) {
      if (a.dtype === b.dtype) {
        return [a, b];
      }
      var dtype = upcastType(a.dtype, b.dtype);
      return [a.cast(dtype), b.cast(dtype)];
    }
    function getTensorsInContainer(result) {
      var list = [];
      var seen = /* @__PURE__ */ new Set();
      walkTensorContainer(result, list, seen);
      return list;
    }
    function walkTensorContainer(container, list, seen) {
      if (container == null) {
        return;
      }
      if (container instanceof Tensor) {
        list.push(container);
        return;
      }
      if (!isIterable(container)) {
        return;
      }
      var iterable = container;
      for (var k in iterable) {
        var val = iterable[k];
        if (!seen.has(val)) {
          seen.add(val);
          walkTensorContainer(val, list, seen);
        }
      }
    }
    function isIterable(obj) {
      return Array.isArray(obj) || typeof obj === "object";
    }
    function isRegisteredKernelInvocation(kernelInvocation) {
      return kernelInvocation.kernelName != null;
    }
    var EngineState = (
      /** @class */
      function() {
        function EngineState2() {
          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 = /* @__PURE__ */ new WeakMap();
          this.profiling = false;
          this.activeProfile = {
            newBytes: 0,
            newTensors: 0,
            peakBytes: 0,
            kernels: [],
            result: null,
            get kernelNames() {
              return Array.from(new Set(this.kernels.map(function(k) {
                return k.name;
              })));
            }
          };
        }
        EngineState2.prototype.dispose = function() {
          for (var variableName in this.registeredVariables) {
            this.registeredVariables[variableName].dispose();
          }
        };
        return EngineState2;
      }()
    );
    var Engine = (
      /** @class */
      function() {
        function Engine2(ENV2) {
          this.ENV = ENV2;
          this.registry = {};
          this.registryFactory = {};
          this.pendingBackendInitId = 0;
          this.state = new EngineState();
        }
        Engine2.prototype.ready = function() {
          return __awaiter(this, void 0, void 0, function() {
            var sortedBackends, i, backendName, success;
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  if (this.pendingBackendInit != null) {
                    return [2, this.pendingBackendInit.then(function() {
                    })];
                  }
                  if (this.backendInstance != null) {
                    return [
                      2
                      /*return*/
                    ];
                  }
                  sortedBackends = this.getSortedBackends();
                  i = 0;
                  _a2.label = 1;
                case 1:
                  if (!(i < sortedBackends.length)) return [3, 5];
                  backendName = sortedBackends[i];
                  return [4, this.initializeBackend(backendName).success];
                case 2:
                  success = _a2.sent();
                  if (!success) return [3, 4];
                  return [4, this.setBackend(backendName)];
                case 3:
                  _a2.sent();
                  return [
                    2
                    /*return*/
                  ];
                case 4:
                  i++;
                  return [3, 1];
                case 5:
                  throw new Error("Could not initialize any backends, all backend initializations failed.");
              }
            });
          });
        };
        Object.defineProperty(Engine2.prototype, "backend", {
          get: function() {
            if (this.pendingBackendInit != null) {
              throw new Error("Backend '".concat(this.backendName, "' has not yet been initialized. Make ") + "sure to await tf.ready() or await tf.setBackend() before calling other methods");
            }
            if (this.backendInstance == null) {
              var _a2 = this.initializeBackendsAndReturnBest(), name = _a2.name, asyncInit = _a2.asyncInit;
              if (asyncInit) {
                throw new Error("The highest priority backend '".concat(name, "' has not yet been ") + "initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods");
              }
              this.setBackend(name);
            }
            return this.backendInstance;
          },
          enumerable: false,
          configurable: true
        });
        Engine2.prototype.backendNames = function() {
          return Object.keys(this.registryFactory);
        };
        Engine2.prototype.findBackend = function(backendName) {
          if (!(backendName in this.registry)) {
            if (backendName in this.registryFactory) {
              var asyncInit = this.initializeBackend(backendName).asyncInit;
              if (asyncInit) {
                return null;
              }
            } else {
              return null;
            }
          }
          return this.registry[backendName];
        };
        Engine2.prototype.findBackendFactory = function(backendName) {
          if (!(backendName in this.registryFactory)) {
            return null;
          }
          return this.registryFactory[backendName].factory;
        };
        Engine2.prototype.registerBackend = function(backendName, factory, priority) {
          if (priority === void 0) {
            priority = 1;
          }
          if (backendName in this.registryFactory) {
            warn("".concat(backendName, " backend was already registered. ") + "Reusing existing backend factory.");
            return false;
          }
          this.registryFactory[backendName] = { factory, priority };
          return true;
        };
        Engine2.prototype.setBackend = function(backendName) {
          return __awaiter(this, void 0, void 0, function() {
            var _a2, success, asyncInit, result, _b;
            return __generator(this, function(_c) {
              switch (_c.label) {
                case 0:
                  if (this.registryFactory[backendName] == null) {
                    throw new Error("Backend name '".concat(backendName, "' not found in registry"));
                  }
                  this.backendName = backendName;
                  if (!(this.registry[backendName] == null)) return [3, 4];
                  this.backendInstance = null;
                  _a2 = this.initializeBackend(backendName), success = _a2.success, asyncInit = _a2.asyncInit;
                  if (!asyncInit) return [3, 2];
                  return [4, success];
                case 1:
                  _b = _c.sent();
                  return [3, 3];
                case 2:
                  _b = success;
                  _c.label = 3;
                case 3:
                  result = _b;
                  if (!result) {
                    return [2, false];
                  }
                  _c.label = 4;
                case 4:
                  this.backendInstance = this.registry[backendName];
                  this.setupRegisteredKernels();
                  this.profiler = new Profiler(this.backendInstance);
                  return [2, true];
              }
            });
          });
        };
        Engine2.prototype.setupRegisteredKernels = function() {
          var _this = this;
          var kernels = getKernelsForBackend(this.backendName);
          kernels.forEach(function(kernel) {
            if (kernel.setupFunc != null) {
              kernel.setupFunc(_this.backendInstance);
            }
          });
        };
        Engine2.prototype.disposeRegisteredKernels = function(backendName) {
          var _this = this;
          var kernels = getKernelsForBackend(backendName);
          kernels.forEach(function(kernel) {
            if (kernel.disposeFunc != null) {
              kernel.disposeFunc(_this.registry[backendName]);
            }
          });
        };
        Engine2.prototype.initializeBackend = function(backendName) {
          var _this = this;
          var registryFactoryEntry = this.registryFactory[backendName];
          if (registryFactoryEntry == null) {
            throw new Error("Cannot initialize backend ".concat(backendName, ", no registration found."));
          }
          try {
            var backend = registryFactoryEntry.factory();
            if (backend && !(backend instanceof KernelBackend) && typeof backend.then === "function") {
              var promiseId_1 = ++this.pendingBackendInitId;
              var success = backend.then(function(backendInstance) {
                if (promiseId_1 < _this.pendingBackendInitId) {
                  return false;
                }
                _this.registry[backendName] = backendInstance;
                _this.pendingBackendInit = null;
                return true;
              }).catch(function(err) {
                if (promiseId_1 < _this.pendingBackendInitId) {
                  return false;
                }
                _this.pendingBackendInit = null;
                warn("Initialization of backend ".concat(backendName, " failed"));
                warn(err.stack || err.message);
                return false;
              });
              this.pendingBackendInit = success;
              return { success, asyncInit: true };
            } else {
              this.registry[backendName] = backend;
              return { success: true, asyncInit: false };
            }
          } catch (err) {
            warn("Initialization of backend ".concat(backendName, " failed"));
            warn(err.stack || err.message);
            return { success: false, asyncInit: false };
          }
        };
        Engine2.prototype.removeBackend = function(backendName) {
          if (!(backendName in this.registryFactory)) {
            throw new Error("".concat(backendName, " backend not found in registry"));
          }
          if (this.backendName === backendName && this.pendingBackendInit != null) {
            this.pendingBackendInitId++;
          }
          if (backendName in this.registry) {
            this.disposeRegisteredKernels(backendName);
            this.registry[backendName].dispose();
            delete this.registry[backendName];
          }
          delete this.registryFactory[backendName];
          if (this.backendName === backendName) {
            this.pendingBackendInit = null;
            this.backendName = null;
            this.backendInstance = null;
          }
        };
        Engine2.prototype.getSortedBackends = function() {
          var _this = this;
          if (Object.keys(this.registryFactory).length === 0) {
            throw new Error("No backend found in registry.");
          }
          return Object.keys(this.registryFactory).sort(function(a, b) {
            return _this.registryFactory[b].priority - _this.registryFactory[a].priority;
          });
        };
        Engine2.prototype.initializeBackendsAndReturnBest = function() {
          var sortedBackends = this.getSortedBackends();
          for (var i = 0; i < sortedBackends.length; i++) {
            var backendName = sortedBackends[i];
            var _a2 = this.initializeBackend(backendName), success = _a2.success, asyncInit = _a2.asyncInit;
            if (asyncInit || success) {
              return { name: backendName, asyncInit };
            }
          }
          throw new Error("Could not initialize any backends, all backend initializations failed.");
        };
        Engine2.prototype.moveData = function(backend, dataId) {
          var info = this.state.tensorInfo.get(dataId);
          var srcBackend = info.backend;
          var values = this.readSync(dataId);
          var refCount = srcBackend.refCount(dataId);
          srcBackend.disposeData(dataId, true);
          info.backend = backend;
          backend.move(dataId, values, info.shape, info.dtype, refCount);
          if (this.shouldCheckForMemLeaks()) {
            this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;
          }
        };
        Engine2.prototype.tidy = function(nameOrFn, fn) {
          var _this = this;
          var name = null;
          if (fn == null) {
            if (typeof nameOrFn !== "function") {
              throw new Error("Please provide a function to tidy()");
            }
            fn = nameOrFn;
          } else {
            if (typeof nameOrFn !== "string" && !(nameOrFn instanceof String)) {
              throw new Error("When calling with two arguments, the first argument to tidy() must be a string");
            }
            if (typeof fn !== "function") {
              throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");
            }
            name = nameOrFn;
          }
          var result;
          return this.scopedRun(function() {
            return _this.startScope(name);
          }, function() {
            return _this.endScope(result);
          }, function() {
            result = fn();
            if (result instanceof Promise) {
              console.error("Cannot return a Promise inside of tidy.");
            }
            return result;
          });
        };
        Engine2.prototype.scopedRun = function(start, end, f) {
          start();
          try {
            var res = f();
            end();
            return res;
          } catch (ex) {
            end();
            throw ex;
          }
        };
        Engine2.prototype.nextTensorId = function() {
          return Engine2.nextTensorId++;
        };
        Engine2.prototype.nextVariableId = function() {
          return Engine2.nextVariableId++;
        };
        Engine2.prototype.clone = function(x) {
          var y = ENGINE.runKernel(Identity, { x });
          var inputs = { x };
          var grad = function(dy) {
            return {
              x: function() {
                var dtype = "float32";
                var gradInputs = { x: dy };
                var attrs = { dtype };
                return ENGINE.runKernel(
                  Cast,
                  gradInputs,
                  // tslint:disable-next-line: no-unnecessary-type-assertion
                  attrs
                );
              }
            };
          };
          var saved = [];
          this.addTapeNode(this.state.activeScope.name, inputs, [y], grad, saved, {});
          return y;
        };
        Engine2.prototype.runKernel = function(kernelName, inputs, attrs) {
          if (this.backendName == null) {
            this.backend;
          }
          var hasKernel = getKernel(kernelName, this.backendName) != null;
          if (!hasKernel) {
            throw new Error("Kernel '".concat(kernelName, "' not registered for backend '").concat(this.backendName, "'"));
          }
          return this.runKernelFunc({ kernelName, inputs, attrs });
        };
        Engine2.prototype.shouldCheckForMemLeaks = function() {
          return this.ENV.getBool("IS_TEST");
        };
        Engine2.prototype.checkKernelForMemLeak = function(kernelName, numDataIdsBefore, outInfos) {
          var numDataIdsAfter = this.backend.numDataIds();
          var numOutputDataIds = 0;
          outInfos.forEach(function(info) {
            numOutputDataIds += info.dtype === "complex64" ? 3 : 1;
          });
          var numMoves = this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1];
          var dataIdsLeaked = numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves;
          if (dataIdsLeaked > 0) {
            throw new Error("Backend '".concat(this.backendName, "' has an internal memory leak ") + "(".concat(dataIdsLeaked, " data ids) after running '").concat(kernelName, "'"));
          }
        };
        Engine2.prototype.runKernelFunc = function(kernelParams) {
          var _this = this;
          var outputs;
          var saved = [];
          var isTapeOn = this.isTapeOn();
          var startingBytecount = this.state.numBytes;
          var startingNumTensors = this.state.numTensors;
          if (this.shouldCheckForMemLeaks()) {
            this.state.numDataMovesStack.push(0);
          }
          var kernelFunc;
          if (this.backendName == null) {
            this.backend;
          }
          var out;
          var kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ? kernelParams.kernelName : this.state.activeScope != null ? this.state.activeScope.name : "";
          if (isRegisteredKernelInvocation(kernelParams)) {
            var kernelName_1 = kernelParams.kernelName, inputs_1 = kernelParams.inputs, attrs_1 = kernelParams.attrs;
            if (this.backendName == null) {
              this.backend;
            }
            var kernel_1 = getKernel(kernelName_1, this.backendName);
            assert(kernel_1 != null, function() {
              return "Cannot find registered kernel '".concat(kernelName_1, "' for backend '").concat(_this.backendName, "'");
            });
            kernelFunc = function() {
              var numDataIdsBefore = _this.backend.numDataIds();
              out = kernel_1.kernelFunc({ inputs: inputs_1, attrs: attrs_1, backend: _this.backend });
              var outInfos = Array.isArray(out) ? out : [out];
              if (_this.shouldCheckForMemLeaks()) {
                _this.checkKernelForMemLeak(kernelName_1, numDataIdsBefore, outInfos);
              }
              var outTensors = outInfos.map(function(outInfo) {
                if (outInfo.rank != null) {
                  return outInfo;
                }
                return _this.makeTensorFromTensorInfo(outInfo);
              });
              if (isTapeOn) {
                var tensorsToSave = _this.getTensorsForGradient(kernelName_1, inputs_1, outTensors);
                saved = _this.saveTensorsForBackwardMode(tensorsToSave);
              }
              return outTensors;
            };
          } else {
            var forwardFunc_1 = kernelParams.forwardFunc;
            var saveFunc_1 = function(tensors) {
              if (!isTapeOn) {
                return;
              }
              saved = tensors.map(function(tensor) {
                return _this.keep(_this.clone(tensor));
              });
            };
            kernelFunc = function() {
              var numDataIdsBefore = _this.backend.numDataIds();
              out = _this.tidy(function() {
                return forwardFunc_1(_this.backend, saveFunc_1);
              });
              var outs = Array.isArray(out) ? out : [out];
              if (_this.shouldCheckForMemLeaks()) {
                _this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs);
              }
              return outs;
            };
          }
          var inputs = kernelParams.inputs, attrs = kernelParams.attrs;
          var backwardsFunc = isRegisteredKernelInvocation(kernelParams) ? null : kernelParams.backwardsFunc;
          var kernelProfile;
          this.scopedRun(
            // Stop recording to a tape when running a kernel.
            function() {
              return _this.state.kernelDepth++;
            },
            function() {
              return _this.state.kernelDepth--;
            },
            function() {
              if (!_this.ENV.getBool("DEBUG") && !_this.state.profiling) {
                outputs = kernelFunc();
              } else {
                kernelProfile = _this.profiler.profileKernel(kernelOrScopeName, inputs, function() {
                  return kernelFunc();
                });
                if (_this.ENV.getBool("DEBUG")) {
                  _this.profiler.logKernelProfile(kernelProfile);
                }
                outputs = kernelProfile.outputs;
              }
            }
          );
          if (isTapeOn) {
            this.addTapeNode(kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs);
          }
          if (this.state.profiling) {
            this.state.activeProfile.kernels.push({
              name: kernelOrScopeName,
              bytesAdded: this.state.numBytes - startingBytecount,
              totalBytesSnapshot: this.state.numBytes,
              tensorsAdded: this.state.numTensors - startingNumTensors,
              totalTensorsSnapshot: this.state.numTensors,
              inputShapes: Object.keys(inputs).map(function(key) {
                return inputs[key] != null ? inputs[key].shape : null;
              }),
              outputShapes: outputs.map(function(item) {
                return item.shape;
              }),
              kernelTimeMs: kernelProfile.timeMs,
              extraInfo: kernelProfile.extraInfo
            });
          }
          return Array.isArray(out) ? outputs : outputs[0];
        };
        Engine2.prototype.saveTensorsForBackwardMode = function(tensors) {
          var _this = this;
          var saved = tensors.map(function(tensor) {
            return _this.keep(_this.clone(tensor));
          });
          return saved;
        };
        Engine2.prototype.getTensorsForGradient = function(kernelName, inputs, outputs) {
          var gradConfig = getGradient(kernelName);
          if (gradConfig != null) {
            var inputsToSave = gradConfig.inputsToSave || [];
            var outputsToSave_1 = gradConfig.outputsToSave || [];
            var inputTensorsToSave = void 0;
            if (gradConfig.saveAllInputs) {
              assert(Array.isArray(inputs), function() {
                return "saveAllInputs is true, expected inputs to be an array.";
              });
              inputTensorsToSave = Object.keys(inputs).map(function(key) {
                return inputs[key];
              });
            } else {
              inputTensorsToSave = inputsToSave.map(function(inputName) {
                return inputs[inputName];
              });
            }
            var outputTensorsToSave = outputs.filter(function(_, i) {
              return outputsToSave_1[i];
            });
            return inputTensorsToSave.concat(outputTensorsToSave);
          }
          return [];
        };
        Engine2.prototype.makeTensor = function(values, shape, dtype, backend) {
          if (values == null) {
            throw new Error("Values passed to engine.makeTensor() are null");
          }
          dtype = dtype || "float32";
          backend = backend || this.backend;
          var backendVals = values;
          if (dtype === "string" && isString(values[0])) {
            backendVals = values.map(function(d) {
              return encodeString(d);
            });
          }
          var dataId = backend.write(backendVals, shape, dtype);
          var t = new Tensor(shape, dtype, dataId, this.nextTensorId());
          this.trackTensor(t, backend);
          if (dtype === "string") {
            var info = this.state.tensorInfo.get(dataId);
            var newBytes = bytesFromStringArray(backendVals);
            this.state.numBytes += newBytes - info.bytes;
            info.bytes = newBytes;
          }
          return t;
        };
        Engine2.prototype.makeTensorFromDataId = function(dataId, shape, dtype, backend) {
          dtype = dtype || "float32";
          var tensorInfo = { dataId, shape, dtype };
          return this.makeTensorFromTensorInfo(tensorInfo, backend);
        };
        Engine2.prototype.makeTensorFromTensorInfo = function(tensorInfo, backend) {
          var dataId = tensorInfo.dataId, shape = tensorInfo.shape, dtype = tensorInfo.dtype;
          var t = new Tensor(shape, dtype, dataId, this.nextTensorId());
          this.trackTensor(t, backend);
          return t;
        };
        Engine2.prototype.makeVariable = function(initialValue, trainable, name, dtype) {
          if (trainable === void 0) {
            trainable = true;
          }
          name = name || this.nextVariableId().toString();
          if (dtype != null && dtype !== initialValue.dtype) {
            initialValue = initialValue.cast(dtype);
          }
          var v = new Variable(initialValue, trainable, name, this.nextTensorId());
          if (this.state.registeredVariables[v.name] != null) {
            throw new Error("Variable with name ".concat(v.name, " was already registered"));
          }
          this.state.registeredVariables[v.name] = v;
          this.incRef(v, this.backend);
          return v;
        };
        Engine2.prototype.trackTensor = function(a, backend) {
          this.state.numTensors++;
          if (a.dtype === "string") {
            this.state.numStringTensors++;
          }
          var bytes = 0;
          if (a.dtype !== "complex64" && a.dtype !== "string") {
            bytes = a.size * bytesPerElement(a.dtype);
          }
          this.state.numBytes += bytes;
          if (!this.state.tensorInfo.has(a.dataId)) {
            this.state.numDataBuffers++;
            this.state.tensorInfo.set(a.dataId, {
              backend: backend || this.backend,
              dtype: a.dtype,
              shape: a.shape,
              bytes
            });
          }
          if (!(a instanceof Variable)) {
            this.track(a);
          }
        };
        Engine2.prototype.incRef = function(a, backend) {
          this.trackTensor(a, backend);
          this.backend.incRef(a.dataId);
        };
        Engine2.prototype.removeDataId = function(dataId, backend) {
          if (this.state.tensorInfo.has(dataId) && this.state.tensorInfo.get(dataId).backend === backend) {
            this.state.tensorInfo.delete(dataId);
            this.state.numDataBuffers--;
          }
        };
        Engine2.prototype.disposeTensor = function(a) {
          if (!this.state.tensorInfo.has(a.dataId)) {
            return;
          }
          var info = this.state.tensorInfo.get(a.dataId);
          this.state.numTensors--;
          if (a.dtype === "string") {
            this.state.numStringTensors--;
            this.state.numBytes -= info.bytes;
          }
          if (a.dtype !== "complex64" && a.dtype !== "string") {
            var bytes = a.size * bytesPerElement(a.dtype);
            this.state.numBytes -= bytes;
          }
          if (info.backend.disposeData(a.dataId)) {
            this.removeDataId(a.dataId, info.backend);
          }
        };
        Engine2.prototype.disposeVariables = function() {
          for (var varName in this.state.registeredVariables) {
            var v = this.state.registeredVariables[varName];
            this.disposeVariable(v);
          }
        };
        Engine2.prototype.disposeVariable = function(v) {
          this.disposeTensor(v);
          if (this.state.registeredVariables[v.name] != null) {
            delete this.state.registeredVariables[v.name];
          }
        };
        Engine2.prototype.memory = function() {
          var info = this.backend.memory();
          info.numTensors = this.state.numTensors;
          info.numDataBuffers = this.state.numDataBuffers;
          info.numBytes = this.state.numBytes;
          if (this.state.numStringTensors > 0) {
            info.unreliable = true;
            if (info.reasons == null) {
              info.reasons = [];
            }
            info.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)");
          }
          return info;
        };
        Engine2.prototype.profile = function(query) {
          return __awaiter(this, void 0, void 0, function() {
            var startBytes, startNumTensors, _a2, _b, _c, kernel, _d, _e, e_1_1;
            var e_12, _f;
            return __generator(this, function(_g) {
              switch (_g.label) {
                case 0:
                  this.state.profiling = true;
                  startBytes = this.state.numBytes;
                  startNumTensors = this.state.numTensors;
                  this.state.activeProfile.kernels = [];
                  _a2 = this.state.activeProfile;
                  return [4, query()];
                case 1:
                  _a2.result = _g.sent();
                  this.state.profiling = false;
                  this.state.activeProfile.peakBytes = Math.max.apply(Math, __spreadArray([], __read(this.state.activeProfile.kernels.map(function(d) {
                    return d.totalBytesSnapshot;
                  })), false));
                  this.state.activeProfile.newBytes = this.state.numBytes - startBytes;
                  this.state.activeProfile.newTensors = this.state.numTensors - startNumTensors;
                  _g.label = 2;
                case 2:
                  _g.trys.push([2, 8, 9, 10]);
                  _b = __values(this.state.activeProfile.kernels), _c = _b.next();
                  _g.label = 3;
                case 3:
                  if (!!_c.done) return [3, 7];
                  kernel = _c.value;
                  _d = kernel;
                  return [4, kernel.kernelTimeMs];
                case 4:
                  _d.kernelTimeMs = _g.sent();
                  _e = kernel;
                  return [4, kernel.extraInfo];
                case 5:
                  _e.extraInfo = _g.sent();
                  _g.label = 6;
                case 6:
                  _c = _b.next();
                  return [3, 3];
                case 7:
                  return [3, 10];
                case 8:
                  e_1_1 = _g.sent();
                  e_12 = { error: e_1_1 };
                  return [3, 10];
                case 9:
                  try {
                    if (_c && !_c.done && (_f = _b.return)) _f.call(_b);
                  } finally {
                    if (e_12) throw e_12.error;
                  }
                  return [
                    7
                    /*endfinally*/
                  ];
                case 10:
                  return [2, this.state.activeProfile];
              }
            });
          });
        };
        Engine2.prototype.isTapeOn = function() {
          return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;
        };
        Engine2.prototype.addTapeNode = function(kernelName, inputs, outputs, gradientsFunc, saved, attrs) {
          var _this = this;
          var tapeNode = { id: this.state.nextTapeNodeId++, kernelName, inputs, outputs, saved };
          var gradConfig = getGradient(kernelName);
          if (gradConfig != null) {
            gradientsFunc = gradConfig.gradFunc;
          }
          if (gradientsFunc != null) {
            tapeNode.gradient = function(dys) {
              dys = dys.map(function(dy, i) {
                if (dy == null) {
                  var output = outputs[i];
                  var vals = makeZerosTypedArray(output.size, output.dtype);
                  return _this.makeTensor(vals, output.shape, output.dtype);
                }
                return dy;
              });
              return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs);
            };
          }
          this.state.activeTape.push(tapeNode);
        };
        Engine2.prototype.keep = function(result) {
          result.kept = true;
          return result;
        };
        Engine2.prototype.startTape = function() {
          if (this.state.gradientDepth === 0) {
            this.state.activeTape = [];
          }
          this.state.gradientDepth++;
        };
        Engine2.prototype.endTape = function() {
          this.state.gradientDepth--;
        };
        Engine2.prototype.startScope = function(name) {
          var scopeInfo = {
            track: [],
            name: "unnamed scope",
            id: this.state.nextScopeId++
          };
          if (name) {
            scopeInfo.name = name;
          }
          this.state.scopeStack.push(scopeInfo);
          this.state.activeScope = scopeInfo;
        };
        Engine2.prototype.endScope = function(result) {
          var _this = this;
          var tensorsToTrackInParent = getTensorsInContainer(result);
          var tensorsToTrackInParentSet = new Set(tensorsToTrackInParent.map(function(t) {
            return t.id;
          }));
          for (var i = 0; i < this.state.activeScope.track.length; i++) {
            var tensor = this.state.activeScope.track[i];
            if (!tensor.kept && !tensorsToTrackInParentSet.has(tensor.id)) {
              tensor.dispose();
            }
          }
          var oldScope = this.state.scopeStack.pop();
          this.state.activeScope = this.state.scopeStack.length === 0 ? null : this.state.scopeStack[this.state.scopeStack.length - 1];
          tensorsToTrackInParent.forEach(function(tensor2) {
            if (!tensor2.kept && tensor2.scopeId === oldScope.id) {
              _this.track(tensor2);
            }
          });
        };
        Engine2.prototype.gradients = function(f, xs, dy, allowNoGradients) {
          var _this = this;
          if (allowNoGradients === void 0) {
            allowNoGradients = false;
          }
          assert(xs.length > 0, function() {
            return "gradients() received an empty list of xs.";
          });
          if (dy != null && dy.dtype !== "float32") {
            throw new Error("dy must have 'float32' dtype, but has '".concat(dy.dtype, "'"));
          }
          var y = this.scopedRun(function() {
            return _this.startTape();
          }, function() {
            return _this.endTape();
          }, function() {
            return _this.tidy("forward", f);
          });
          assert(y instanceof Tensor, function() {
            return "The result y returned by f() must be a tensor.";
          });
          var filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y);
          if (!allowNoGradients && filteredTape.length === 0 && xs.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", function() {
            var accumulatedGradientMap = {};
            accumulatedGradientMap[y.id] = dy == null ? ones$2(y.shape) : dy;
            backpropagateGradients(
              accumulatedGradientMap,
              filteredTape,
              // Pass the tidy function to avoid circular dep with `tape.ts`.
              function(f2) {
                return _this.tidy(f2);
              },
              // Pass an add function to avoide a circular dep with `tape.ts`.
              add$2
            );
            var grads = xs.map(function(x) {
              return accumulatedGradientMap[x.id];
            });
            if (_this.state.gradientDepth === 0) {
              _this.state.activeTape.forEach(function(node) {
                var e_2, _a2;
                try {
                  for (var _b = __values(node.saved), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var tensor = _c.value;
                    tensor.dispose();
                  }
                } catch (e_2_1) {
                  e_2 = { error: e_2_1 };
                } finally {
                  try {
                    if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
                  } finally {
                    if (e_2) throw e_2.error;
                  }
                }
              });
              _this.state.activeTape = null;
            }
            return { value: y, grads };
          });
        };
        Engine2.prototype.customGrad = function(f) {
          var _this = this;
          assert(isFunction(f), function() {
            return "The f passed in customGrad(f) must be a function.";
          });
          return function() {
            var inputs = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              inputs[_i] = arguments[_i];
            }
            assert(inputs.every(function(t) {
              return t instanceof Tensor;
            }), function() {
              return "The args passed in customGrad(f)(x1, x2,...) must all be tensors";
            });
            var res;
            var inputMap = {};
            inputs.forEach(function(input2, i) {
              inputMap[i] = input2;
            });
            var forwardFunc = function(_, save) {
              res = f.apply(void 0, __spreadArray([], __read(__spreadArray(__spreadArray([], __read(inputs), false), [save], false)), false));
              assert(res.value instanceof Tensor, function() {
                return "The function f passed in customGrad(f) must return an object where `obj.value` is a tensor";
              });
              assert(isFunction(res.gradFunc), function() {
                return "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.";
              });
              return res.value;
            };
            var backwardsFunc = function(dy, saved) {
              var gradRes = res.gradFunc(dy, saved);
              var grads = Array.isArray(gradRes) ? gradRes : [gradRes];
              assert(grads.length === inputs.length, function() {
                return "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(...).";
              });
              assert(grads.every(function(t) {
                return t instanceof Tensor;
              }), function() {
                return "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.";
              });
              var gradMap = {};
              grads.forEach(function(grad, i) {
                gradMap[i] = function() {
                  return grad;
                };
              });
              return gradMap;
            };
            return _this.runKernelFunc({
              forwardFunc,
              backwardsFunc,
              inputs: inputMap
            });
          };
        };
        Engine2.prototype.readSync = function(dataId) {
          var info = this.state.tensorInfo.get(dataId);
          return info.backend.readSync(dataId);
        };
        Engine2.prototype.read = function(dataId) {
          var info = this.state.tensorInfo.get(dataId);
          return info.backend.read(dataId);
        };
        Engine2.prototype.readToGPU = function(dataId, options) {
          var info = this.state.tensorInfo.get(dataId);
          return info.backend.readToGPU(dataId, options);
        };
        Engine2.prototype.time = function(query) {
          return __awaiter(this, void 0, void 0, function() {
            var start, timingInfo;
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  start = now();
                  return [4, this.backend.time(query)];
                case 1:
                  timingInfo = _a2.sent();
                  timingInfo.wallMs = now() - start;
                  return [2, timingInfo];
              }
            });
          });
        };
        Engine2.prototype.track = function(result) {
          if (this.state.activeScope != null) {
            result.scopeId = this.state.activeScope.id;
            this.state.activeScope.track.push(result);
          }
          return result;
        };
        Object.defineProperty(Engine2.prototype, "registeredVariables", {
          get: function() {
            return this.state.registeredVariables;
          },
          enumerable: false,
          configurable: true
        });
        Engine2.prototype.reset = function() {
          this.pendingBackendInitId++;
          this.state.dispose();
          this.ENV.reset();
          this.state = new EngineState();
          for (var backendName in this.registry) {
            this.disposeRegisteredKernels(backendName);
            this.registry[backendName].dispose();
            delete this.registry[backendName];
          }
          this.backendName = null;
          this.backendInstance = null;
          this.pendingBackendInit = null;
        };
        return Engine2;
      }()
    );
    Engine.nextTensorId = 0;
    Engine.nextVariableId = 0;
    function ones$2(shape) {
      var values = makeOnesTypedArray(sizeFromShape(shape), "float32");
      return ENGINE.makeTensor(values, shape, "float32");
    }
    function getOrMakeEngine() {
      var ns = getGlobalNamespace();
      if (ns._tfengine == null) {
        var environment = new Environment(ns);
        ns._tfengine = new Engine(environment);
      }
      setEnvironmentGlobal(ns._tfengine.ENV);
      setTensorTracker(function() {
        return ns._tfengine;
      });
      return ns._tfengine;
    }
    var ENGINE = getOrMakeEngine();
    function add$2(a, b) {
      var inputs = { a, b };
      return ENGINE.runKernel(Add$1, inputs);
    }
    function inferShape(val, dtype) {
      var firstElem = val;
      if (isTypedArray(val)) {
        return dtype === "string" ? [] : [val.length];
      }
      if (isWebGLData(val)) {
        var usedChannels = val.channels || "RGBA";
        return [val.height, val.width * usedChannels.length];
      } else if (isWebGPUData(val)) {
        return [val.buffer.size / (dtype == null ? 4 : bytesPerElement(dtype))];
      }
      if (!Array.isArray(val)) {
        return [];
      }
      var shape = [];
      while (Array.isArray(firstElem) || isTypedArray(firstElem) && dtype !== "string") {
        shape.push(firstElem.length);
        firstElem = firstElem[0];
      }
      if (Array.isArray(val) && env().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")) {
        deepAssertShapeConsistency(val, shape, []);
      }
      return shape;
    }
    function deepAssertShapeConsistency(val, shape, indices) {
      indices = indices || [];
      if (!Array.isArray(val) && !isTypedArray(val)) {
        assert(shape.length === 0, function() {
          return "Element arr[".concat(indices.join("]["), "] is a primitive, ") + "but should be an array/TypedArray of ".concat(shape[0], " elements");
        });
        return;
      }
      assert(shape.length > 0, function() {
        return "Element arr[".concat(indices.join("]["), "] should be a primitive, ") + "but is an array of ".concat(val.length, " elements");
      });
      assert(val.length === shape[0], function() {
        return "Element arr[".concat(indices.join("]["), "] should have ").concat(shape[0], " ") + "elements, but has ".concat(val.length, " elements");
      });
      var subShape = shape.slice(1);
      for (var i = 0; i < val.length; ++i) {
        deepAssertShapeConsistency(val[i], subShape, indices.concat(i));
      }
    }
    function assertDtype(expectedDtype, actualDType, argName, functionName) {
      if (expectedDtype === "string_or_numeric") {
        return;
      }
      if (expectedDtype == null) {
        throw new Error("Expected dtype cannot be null.");
      }
      if (expectedDtype !== "numeric" && expectedDtype !== actualDType || expectedDtype === "numeric" && actualDType === "string") {
        throw new Error("Argument '".concat(argName, "' passed to '").concat(functionName, "' must ") + "be ".concat(expectedDtype, " tensor, but got ").concat(actualDType, " tensor"));
      }
    }
    function convertToTensor(x, argName, functionName, parseAsDtype) {
      if (parseAsDtype === void 0) {
        parseAsDtype = "numeric";
      }
      if (x instanceof getGlobalTensorClass()) {
        assertDtype(parseAsDtype, x.dtype, argName, functionName);
        return x;
      }
      var inferredDtype = inferDtype(x);
      if (inferredDtype !== "string" && ["bool", "int32", "float32"].indexOf(parseAsDtype) >= 0) {
        inferredDtype = parseAsDtype;
      }
      assertDtype(parseAsDtype, inferredDtype, argName, functionName);
      if (x == null || !isTypedArray(x) && !Array.isArray(x) && typeof x !== "number" && typeof x !== "boolean" && typeof x !== "string") {
        var type = x == null ? "null" : x.constructor.name;
        throw new Error("Argument '".concat(argName, "' passed to '").concat(functionName, "' must be a ") + "Tensor or TensorLike, but got '".concat(type, "'"));
      }
      var inferredShape = inferShape(x, inferredDtype);
      if (!isTypedArray(x) && !Array.isArray(x)) {
        x = [x];
      }
      var skipTypedArray = true;
      var values = inferredDtype !== "string" ? toTypedArray(x, inferredDtype) : flatten$1(x, [], skipTypedArray);
      return ENGINE.makeTensor(values, inferredShape, inferredDtype);
    }
    function convertToTensorArray(arg, argName, functionName, parseAsDtype) {
      if (parseAsDtype === void 0) {
        parseAsDtype = "numeric";
      }
      if (!Array.isArray(arg)) {
        throw new Error("Argument ".concat(argName, " passed to ").concat(functionName, " must be a ") + "`Tensor[]` or `TensorLike[]`");
      }
      var tensors = arg;
      return tensors.map(function(t, i) {
        return convertToTensor(t, "".concat(argName, "[").concat(i, "]"), functionName, parseAsDtype);
      });
    }
    var OP_SCOPE_SUFFIX = "__op";
    function op(f) {
      var keys = Object.keys(f);
      if (keys.length !== 1) {
        throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with " + "".concat(keys.length, " keys."));
      }
      var opName = keys[0];
      var fn = f[opName];
      if (opName.endsWith("_")) {
        opName = opName.substring(0, opName.length - 1);
      }
      opName = opName + OP_SCOPE_SUFFIX;
      var f2 = function() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        ENGINE.startScope(opName);
        try {
          var result = fn.apply(void 0, __spreadArray([], __read(args), false));
          if (isPromise(result)) {
            console.error("Cannot return a Promise inside of tidy.");
          }
          ENGINE.endScope(result);
          return result;
        } catch (ex) {
          ENGINE.endScope(null);
          throw ex;
        }
      };
      Object.defineProperty(f2, "name", { value: opName, configurable: true });
      return f2;
    }
    function cast_(x, dtype) {
      var $x = convertToTensor(x, "x", "cast");
      if (!isValidDtype(dtype)) {
        throw new Error("Failed to cast to unknown dtype ".concat(dtype));
      }
      if (dtype === "string" && $x.dtype !== "string" || dtype !== "string" && $x.dtype === "string") {
        throw new Error("Only strings can be casted to strings");
      }
      var inputs = { x: $x };
      var attrs = { dtype };
      return ENGINE.runKernel(Cast, inputs, attrs);
    }
    var cast = /* @__PURE__ */ op({ cast_ });
    function mul_(a, b) {
      var _a2;
      var $a = convertToTensor(a, "a", "mul");
      var $b = convertToTensor(b, "b", "mul");
      _a2 = __read(makeTypesMatch($a, $b), 2), $a = _a2[0], $b = _a2[1];
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Multiply$1, inputs);
    }
    var mul = /* @__PURE__ */ op({ mul_ });
    function step_(x, alpha) {
      if (alpha === void 0) {
        alpha = 0;
      }
      var $x = convertToTensor(x, "x", "step");
      var inputs = { x: $x };
      var attrs = { alpha };
      return ENGINE.runKernel(Step, inputs, attrs);
    }
    var step = /* @__PURE__ */ op({ step_ });
    var absGradConfig = {
      kernelName: Abs,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return mul(dy, step(cast(x, "float32"), -1));
        } };
      }
    };
    function floorDiv_(a, b) {
      var _a2;
      var $a = convertToTensor(a, "a", "floorDiv");
      var $b = convertToTensor(b, "b", "floorDiv");
      _a2 = __read(makeTypesMatch($a, $b), 2), $a = _a2[0], $b = _a2[1];
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(FloorDiv, inputs);
    }
    var floorDiv = /* @__PURE__ */ op({ floorDiv_ });
    function div_(a, b) {
      var _a2;
      var $a = convertToTensor(a, "a", "div");
      var $b = convertToTensor(b, "b", "div");
      _a2 = __read(makeTypesMatch($a, $b), 2), $a = _a2[0], $b = _a2[1];
      if ($a.dtype === "int32" && $b.dtype === "int32") {
        return floorDiv($a, $b);
      }
      var inputs = { a: $a, b: $b };
      var attrs = {};
      return ENGINE.runKernel(RealDiv, inputs, attrs);
    }
    var div = /* @__PURE__ */ op({ div_ });
    function neg_(x) {
      var $x = convertToTensor(x, "x", "neg");
      var inputs = { x: $x };
      return ENGINE.runKernel(Neg, inputs);
    }
    var neg = /* @__PURE__ */ op({ neg_ });
    function makeTensor(values, shape, inferredShape, dtype) {
      if (dtype == null) {
        dtype = inferDtype(values);
      } else if (dtype === "complex64") {
        throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");
      }
      if (isWebGPUData(values) || isWebGLData(values)) {
        if (dtype !== "float32" && dtype !== "int32") {
          throw new Error("Creating tensor from GPU data only supports " + "'float32'|'int32' dtype, while the dtype is ".concat(dtype, "."));
        }
        return ENGINE.backend.createTensorFromGPUData(values, shape || inferredShape, dtype);
      }
      if (!isTypedArray(values) && !Array.isArray(values) && typeof values !== "number" && typeof values !== "boolean" && typeof values !== "string") {
        throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");
      }
      if (shape != null) {
        assertNonNegativeIntegerDimensions(shape);
        var providedSize_1 = sizeFromShape(shape);
        var inferredSize_1 = sizeFromShape(inferredShape);
        assert(providedSize_1 === inferredSize_1, function() {
          return "Based on the provided shape, [".concat(shape, "], the tensor should have ") + "".concat(providedSize_1, " values but has ").concat(inferredSize_1);
        });
        for (var i = 0; i < inferredShape.length; ++i) {
          var inferred = inferredShape[i];
          var flatDimsDontMatch = i === inferredShape.length - 1 ? inferred !== sizeFromShape(shape.slice(i)) : true;
          assert(inferredShape[i] === shape[i] || !flatDimsDontMatch, function() {
            return "Error creating a new Tensor. Inferred shape " + "(".concat(inferredShape, ") does not match the provided ") + "shape (".concat(shape, "). ");
          });
        }
      }
      if (!isTypedArray(values) && !Array.isArray(values)) {
        values = [values];
      }
      shape = shape || inferredShape;
      values = dtype !== "string" ? toTypedArray(values, dtype) : flatten$1(values, [], true);
      return ENGINE.makeTensor(values, shape, dtype);
    }
    function scalar(value, dtype) {
      if ((isTypedArray(value) && dtype !== "string" || Array.isArray(value)) && dtype !== "complex64") {
        throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");
      }
      if (dtype === "string" && isTypedArray(value) && !(value instanceof Uint8Array)) {
        throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");
      }
      var shape = [];
      var inferredShape = [];
      return makeTensor(value, shape, inferredShape, dtype);
    }
    function sqrt_(x) {
      var $x = convertToTensor(x, "x", "sqrt", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Sqrt, inputs);
    }
    var sqrt = /* @__PURE__ */ op({ sqrt_ });
    function square_(x) {
      var $x = convertToTensor(x, "x", "square");
      var attrs = {};
      return ENGINE.runKernel("Square", { x: $x }, attrs);
    }
    var square = /* @__PURE__ */ op({ square_ });
    function sub_(a, b) {
      var _a2;
      var $a = convertToTensor(a, "a", "sub");
      var $b = convertToTensor(b, "b", "sub");
      _a2 = __read(makeTypesMatch($a, $b), 2), $a = _a2[0], $b = _a2[1];
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Sub, inputs);
    }
    var sub = /* @__PURE__ */ op({ sub_ });
    var acosGradConfig = {
      kernelName: Acos,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return {
          x: function() {
            var a = square(cast(x, "float32"));
            var b = sqrt(sub(scalar(1), a));
            return neg(div(dy, b));
          }
        };
      }
    };
    var acoshGradConfig = {
      kernelName: Acosh,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return {
          x: function() {
            var a = sqrt(sub(square(cast(x, "float32")), 1));
            return div(dy, a);
          }
        };
      }
    };
    function getReductionAxes(inShape, outShape) {
      var result = [];
      for (var i = 0; i < outShape.length; i++) {
        var inDim = inShape[inShape.length - i - 1];
        var outAxis = outShape.length - i - 1;
        var outDim = outShape[outAxis];
        if (inDim == null || inDim === 1 && outDim > 1) {
          result.unshift(outAxis);
        }
      }
      return result;
    }
    function assertAndGetBroadcastShape(shapeA, shapeB) {
      var l = Math.max(shapeA.length, shapeB.length);
      var result = new Array(l);
      for (var i = 0; i < l; i++) {
        var a = shapeA[shapeA.length - i - 1];
        if (a == null) {
          a = 1;
        }
        var b = shapeB[shapeB.length - i - 1];
        if (b == null) {
          b = 1;
        }
        if (a === 1) {
          result[l - i - 1] = b;
        } else if (b === 1) {
          result[l - i - 1] = a;
        } else if (a !== b) {
          var errMsg = "Operands could not be broadcast together with shapes " + "".concat(shapeA, " and ").concat(shapeB, ".");
          throw Error(errMsg);
        } else {
          result[l - i - 1] = a;
        }
      }
      return result;
    }
    function reshape_(x, shape) {
      var $x = convertToTensor(x, "x", "reshape", "string_or_numeric");
      var inputs = { x: $x };
      var attrs = { shape };
      return ENGINE.runKernel(Reshape$1, inputs, attrs);
    }
    var reshape$1 = /* @__PURE__ */ op({ reshape_ });
    function sum_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "sum");
      if ($x.dtype === "bool") {
        $x = cast($x, "int32");
      }
      var inputs = { x: $x };
      var attrs = { axis, keepDims };
      return ENGINE.runKernel(Sum, inputs, attrs);
    }
    var sum = /* @__PURE__ */ op({ sum_ });
    var addGradConfig = {
      kernelName: Add$1,
      inputsToSave: ["a", "b"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 2), a = _a2[0], b = _a2[1];
        var outShape = assertAndGetBroadcastShape(a.shape, b.shape);
        var derA = function() {
          var res = dy;
          var reduceAxes = getReductionAxes(a.shape, outShape);
          if (reduceAxes.length > 0) {
            res = sum(res, reduceAxes);
          }
          return reshape$1(res, a.shape);
        };
        var derB = function() {
          var res = dy;
          var reduceAxes = getReductionAxes(b.shape, outShape);
          if (reduceAxes.length > 0) {
            res = sum(res, reduceAxes);
          }
          return reshape$1(res, b.shape);
        };
        return { a: derA, b: derB };
      }
    };
    var addNGradConfig = {
      kernelName: AddN,
      saveAllInputs: true,
      gradFunc: function(dy, saved) {
        var ders = {};
        saved.forEach(function(_, i) {
          ders[i] = function() {
            return dy.clone();
          };
        });
        return ders;
      }
    };
    function zerosLike_(x) {
      var $x = convertToTensor(x, "x", "zerosLike");
      var inputs = { x: $x };
      return ENGINE.runKernel(ZerosLike, inputs);
    }
    var zerosLike = /* @__PURE__ */ op({ zerosLike_ });
    var argMaxGradConfig = {
      kernelName: ArgMax,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return zerosLike(x);
        } };
      }
    };
    var argMinGradConfig = {
      kernelName: ArgMin,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return zerosLike(x);
        } };
      }
    };
    var asinGradConfig = {
      kernelName: Asin,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return div(dy, sqrt(sub(scalar(1), square(cast(x, "float32")))));
        } };
      }
    };
    function add_(a, b) {
      var _a2;
      var $a = convertToTensor(a, "a", "add");
      var $b = convertToTensor(b, "b", "add");
      _a2 = __read(makeTypesMatch($a, $b), 2), $a = _a2[0], $b = _a2[1];
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Add$1, inputs);
    }
    var add$1 = /* @__PURE__ */ op({ add_ });
    var asinhGradConfig = {
      kernelName: Asinh,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return {
          x: function() {
            var a = sqrt(add$1(scalar(1), square(cast(x, "float32"))));
            return div(dy, a);
          }
        };
      }
    };
    var atan2GradConfig = {
      kernelName: Atan2,
      inputsToSave: ["a", "b"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 2), a = _a2[0], b = _a2[1];
        var outShape = assertAndGetBroadcastShape(a.shape, b.shape);
        var derA = function() {
          var d = add$1(square(a), square(b));
          var res = mul(dy, div(b, d));
          var reduceAxes = getReductionAxes(a.shape, outShape);
          if (reduceAxes.length > 0) {
            res = sum(res, reduceAxes);
          }
          return reshape$1(res, a.shape);
        };
        var derB = function() {
          var d = add$1(square(a), square(b));
          var res = neg(mul(dy, div(a, d)));
          var reduceAxes = getReductionAxes(b.shape, outShape);
          if (reduceAxes.length > 0) {
            res = sum(res, reduceAxes);
          }
          return reshape$1(res, b.shape);
        };
        return { a: derA, b: derB };
      }
    };
    var atanGradConfig = {
      kernelName: Atan,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return div(dy, add$1(square(cast(x, "float32")), 1));
        } };
      }
    };
    var atanhGradConfig = {
      kernelName: Atanh,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return div(dy, sub(scalar(1), square(cast(x, "float32"))));
        } };
      }
    };
    function parseTupleParam(param) {
      if (typeof param === "number") {
        return [param, param, param];
      }
      if (param.length === 2) {
        return [param[0], param[1], 1];
      }
      return param;
    }
    function tupleValuesAreOne(param) {
      var _a2 = __read(parseTupleParam(param), 3), dimA = _a2[0], dimB = _a2[1], dimC = _a2[2];
      return dimA === 1 && dimB === 1 && dimC === 1;
    }
    function eitherStridesOrDilationsAreOne(strides, dilations) {
      return tupleValuesAreOne(strides) || tupleValuesAreOne(dilations);
    }
    function stridesOrDilationsArePositive(values) {
      return parseTupleParam(values).every(function(value) {
        return value > 0;
      });
    }
    function checkPadOnDimRoundingMode(opDesc, pad2, dimRoundingMode) {
      if (dimRoundingMode != null) {
        if (typeof pad2 === "string") {
          throw Error("Error in ".concat(opDesc, ": pad must be an integer when using ") + "dimRoundingMode ".concat(dimRoundingMode, " but got pad ").concat(pad2, "."));
        } else if (typeof pad2 === "number") {
          assert(isInt(pad2), function() {
            return "Error in ".concat(opDesc, ": pad must be an integer when using ") + "dimRoundingMode ".concat(dimRoundingMode, " but got pad ").concat(pad2, ".");
          });
        } else if (typeof pad2 === "object") {
          pad2.forEach(function(p) {
            p.forEach(function(v) {
              assert(isInt(v), function() {
                return "Error in ".concat(opDesc, ": pad must be an integer when using ") + "dimRoundingMode ".concat(dimRoundingMode, " but got pad ").concat(v, ".");
              });
            });
          });
        } else {
          throw Error("Error in ".concat(opDesc, ": Unknown padding parameter: ").concat(pad2));
        }
      }
    }
    function avgPool3dGrad_(dy, input2, filterSize, strides, pad2, dimRoundingMode) {
      var $dy = convertToTensor(dy, "dy", "avgPool3dGrad");
      var $input = convertToTensor(input2, "input", "avgPool3dGrad");
      var dy5D = $dy;
      var input5D = $input;
      var reshapedTo5D = false;
      if ($input.rank === 4) {
        reshapedTo5D = true;
        dy5D = reshape$1($dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2], $dy.shape[3]]);
        input5D = reshape$1($input, [
          1,
          $input.shape[0],
          $input.shape[1],
          $input.shape[2],
          $input.shape[3]
        ]);
      }
      assert(dy5D.rank === 5, function() {
        return "Error in avgPool3dGrad: dy must be rank 5 but got rank " + "".concat(dy5D.rank, ".");
      });
      assert(input5D.rank === 5, function() {
        return "Error in avgPool3dGrad: input must be rank 5 but got rank " + "".concat(input5D.rank, ".");
      });
      checkPadOnDimRoundingMode("avgPool3dGrad", pad2, dimRoundingMode);
      var inputs = { dy: dy5D, input: input5D };
      var attrs = { filterSize, strides, pad: pad2, dimRoundingMode };
      var res = ENGINE.runKernel(AvgPool3DGrad, inputs, attrs);
      if (reshapedTo5D) {
        return reshape$1(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
      }
      return res;
    }
    var avgPool3dGrad = /* @__PURE__ */ op({ avgPool3dGrad_ });
    var avgPool3DGradConfig = {
      kernelName: AvgPool3D,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 1), x = _a2[0];
        var filterSize = attrs.filterSize, strides = attrs.strides, pad2 = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
        return {
          x: function() {
            return avgPool3dGrad(dy, x, filterSize, strides, pad2, dimRoundingMode);
          }
        };
      }
    };
    function avgPoolGrad_(dy, input2, filterSize, strides, pad2) {
      var $dy = convertToTensor(dy, "dy", "avgPoolGrad");
      var $input = convertToTensor(input2, "input", "avgPoolGrad");
      assert($input.rank === $dy.rank, function() {
        return "Rank of input (".concat($input.rank, ") does not match rank of dy (").concat($dy.rank, ")");
      });
      var input4D = $input;
      var dy4D = $dy;
      var reshapedTo4D = false;
      if ($input.rank === 3) {
        reshapedTo4D = true;
        input4D = reshape$1($input, [1, $input.shape[0], $input.shape[1], $input.shape[2]]);
        dy4D = reshape$1($dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2]]);
      }
      assert(dy4D.rank === 4, function() {
        return "Error in avgPoolGrad: dy must be rank 4 but got rank " + "".concat(dy4D.rank, ".");
      });
      assert(input4D.rank === 4, function() {
        return "Error in avgPoolGrad: input must be rank 4 but got rank " + "".concat(input4D.rank, ".");
      });
      var inputs = { dy: dy4D, input: input4D };
      var attrs = { filterSize, strides, pad: pad2 };
      var res = ENGINE.runKernel(AvgPoolGrad, inputs, attrs);
      if (reshapedTo4D) {
        return reshape$1(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var avgPoolGrad = /* @__PURE__ */ op({ avgPoolGrad_ });
    var avgPoolGradConfig = {
      kernelName: AvgPool,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 1), x = _a2[0];
        var filterSize = attrs.filterSize, strides = attrs.strides, pad2 = attrs.pad;
        return { x: function() {
          return avgPoolGrad(dy, x, filterSize, strides, pad2);
        } };
      }
    };
    function matMul_(a, b, transposeA, transposeB) {
      var _a2;
      if (transposeA === void 0) {
        transposeA = false;
      }
      if (transposeB === void 0) {
        transposeB = false;
      }
      var $a = convertToTensor(a, "a", "matMul");
      var $b = convertToTensor(b, "b", "matMul");
      _a2 = __read(makeTypesMatch($a, $b), 2), $a = _a2[0], $b = _a2[1];
      var inputs = { a: $a, b: $b };
      var attrs = { transposeA, transposeB };
      return ENGINE.runKernel(BatchMatMul, inputs, attrs);
    }
    var matMul = /* @__PURE__ */ op({ matMul_ });
    var batchMatMulGradConfig = {
      kernelName: BatchMatMul,
      inputsToSave: ["a", "b"],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 2), a = _a2[0], b = _a2[1];
        var transposeA = attrs.transposeA, transposeB = attrs.transposeB;
        if (!transposeA && !transposeB) {
          return {
            a: function() {
              return matMul(dy, b, false, true);
            },
            b: function() {
              return matMul(a, dy, true, false);
            }
          };
        } else if (!transposeA && transposeB) {
          return {
            a: function() {
              return matMul(dy, b, false, false);
            },
            b: function() {
              return matMul(dy, a, true, false);
            }
          };
        } else if (transposeA && !transposeB) {
          return {
            a: function() {
              return matMul(b, dy, false, true);
            },
            b: function() {
              return matMul(a, dy, false, false);
            }
          };
        } else {
          return {
            a: function() {
              return matMul(b, dy, true, true);
            },
            b: function() {
              return matMul(dy, a, true, true);
            }
          };
        }
      }
    };
    function spaceToBatchND_(x, blockShape, paddings) {
      var $x = convertToTensor(x, "x", "spaceToBatchND");
      assert($x.rank >= 1 + blockShape.length, function() {
        return "input rank ".concat($x.rank, " should be > than [blockShape] ").concat(blockShape.length);
      });
      assert(paddings.length === blockShape.length, function() {
        return "paddings.shape[0] ".concat(paddings.length, " must be equal to [blockShape] ").concat(blockShape.length);
      });
      assert($x.shape.reduce(function(a, b, i) {
        if (i > 0 && i <= blockShape.length) {
          return a && (b + paddings[i - 1][0] + paddings[i - 1][1]) % blockShape[i - 1] === 0;
        }
        return a;
      }, true), function() {
        return "input spatial dimensions ".concat($x.shape.slice(1), " with paddings ").concat(paddings.toString(), " must be divisible by blockShapes ").concat(blockShape.toString());
      });
      var inputs = { x: $x };
      var attrs = { blockShape, paddings };
      return ENGINE.runKernel(SpaceToBatchND, inputs, attrs);
    }
    var spaceToBatchND = /* @__PURE__ */ op({ spaceToBatchND_ });
    var batchToSpaceNDGradConfig = {
      kernelName: BatchToSpaceND,
      gradFunc: function(dy, saved, attrs) {
        var blockShape = attrs.blockShape, crops = attrs.crops;
        return { x: function() {
          return spaceToBatchND(dy, blockShape, crops);
        } };
      }
    };
    var broadcastToGradConfig = {
      kernelName: BroadcastTo,
      gradFunc: function(dy, saved, attrs) {
        var broadCastToAttrs = attrs;
        var inputShape = broadCastToAttrs.inputShape;
        var outputShape = broadCastToAttrs.shape;
        var reps = Array.from(outputShape);
        for (var i = inputShape.length - 1; i >= 0; i--) {
          if (inputShape[i] === outputShape[i]) {
            reps[i] = 1;
          } else if (inputShape[i] !== 1) {
            throw new Error("broadcastTo(): [".concat(inputShape, "] cannot be broadcast to [").concat(outputShape, "]."));
          }
        }
        var axes = [];
        for (var i = 0; i < reps.length; i++) {
          if (reps[i] > 1) {
            axes.push(i);
          }
        }
        return { x: function() {
          return sum(
            dy,
            axes,
            true
            /* keepDims */
          );
        } };
      }
    };
    var castGradConfig = {
      kernelName: Cast,
      gradFunc: function(dy) {
        return { x: function() {
          return dy.clone();
        } };
      }
    };
    var ceilGradConfig = {
      kernelName: Ceil,
      gradFunc: function(dy) {
        return { x: function() {
          return zerosLike(dy);
        } };
      }
    };
    function greaterEqual_(a, b) {
      var _a2;
      var $a = convertToTensor(a, "a", "greaterEqual", "string_or_numeric");
      var $b = convertToTensor(b, "b", "greaterEqual", "string_or_numeric");
      _a2 = __read(makeTypesMatch($a, $b), 2), $a = _a2[0], $b = _a2[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(GreaterEqual, inputs);
    }
    var greaterEqual = /* @__PURE__ */ op({ greaterEqual_ });
    function lessEqual_(a, b) {
      var _a2;
      var $a = convertToTensor(a, "a", "lessEqual", "string_or_numeric");
      var $b = convertToTensor(b, "b", "lessEqual", "string_or_numeric");
      _a2 = __read(makeTypesMatch($a, $b), 2), $a = _a2[0], $b = _a2[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(LessEqual, inputs);
    }
    var lessEqual = /* @__PURE__ */ op({ lessEqual_ });
    function logicalAnd_(a, b) {
      var $a = convertToTensor(a, "a", "logicalAnd", "bool");
      var $b = convertToTensor(b, "b", "logicalAnd", "bool");
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(LogicalAnd, inputs);
    }
    var logicalAnd = /* @__PURE__ */ op({ logicalAnd_ });
    function clone_(x) {
      var $x = convertToTensor(x, "x", "clone", "string_or_numeric");
      var inputs = { x: $x };
      return ENGINE.runKernel(Identity, inputs);
    }
    var clone = /* @__PURE__ */ op({ clone_ });
    function broadcastTo_(x, shape) {
      var input2 = convertToTensor(x, "broadcastTo", "x");
      var xShape = input2.shape;
      assertNonNegativeIntegerDimensions(shape);
      if (shape.length < input2.rank) {
        throw new Error("broadcastTo(): shape.length=".concat(shape.length, " < input.rank=").concat(input2.rank, "."));
      }
      if (shape.length > input2.rank) {
        var newShape = input2.shape.slice();
        while (newShape.length < shape.length) {
          newShape.unshift(1);
        }
        input2 = reshape$1(input2, newShape);
      }
      var inputShape = input2.shape;
      var reps = Array.from(shape);
      for (var i = shape.length - 1; i >= 0; i--) {
        if (inputShape[i] === shape[i]) {
          reps[i] = 1;
        } else if (input2.shape[i] !== 1) {
          throw new Error("broadcastTo(): [".concat(xShape, "] cannot be broadcast to [").concat(shape, "]."));
        }
      }
      var axes = reps.map(function(n, i2) {
        return n > 1 ? i2 : -1;
      }).filter(function(i2) {
        return i2 >= 0;
      });
      if (axes.length === 0) {
        return clone(input2);
      }
      var inputs = { x: input2 };
      var attrs = { reps };
      return ENGINE.runKernel(Tile, inputs, attrs);
    }
    var broadcastTo = /* @__PURE__ */ op({ broadcastTo_ });
    function where_(condition, a, b) {
      var $a = convertToTensor(a, "a", "where");
      var $b = convertToTensor(b, "b", "where");
      var $condition = convertToTensor(condition, "condition", "where", "bool");
      var broadcastShape = assertAndGetBroadcastShape(assertAndGetBroadcastShape($condition.shape, $a.shape), $b.shape);
      var $broadcastedCondition = broadcastTo($condition, broadcastShape);
      var $broadcastedA = broadcastTo($a, broadcastShape);
      var $broadcastedB = broadcastTo($b, broadcastShape);
      var inputs = {
        condition: $broadcastedCondition,
        t: $broadcastedA,
        e: $broadcastedB
      };
      return ENGINE.runKernel(Select, inputs);
    }
    var where = /* @__PURE__ */ op({ where_ });
    var clipByValueGradConfig = {
      kernelName: ClipByValue,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 1), x = _a2[0];
        var clipValueMin = attrs.clipValueMin, clipValueMax = attrs.clipValueMax;
        return {
          x: function() {
            return where(logicalAnd(greaterEqual(x, clipValueMin), lessEqual(x, clipValueMax)), dy, zerosLike(dy));
          }
        };
      }
    };
    var complexAbsGradConfig = {
      kernelName: ComplexAbs,
      inputsToSave: ["x"],
      gradFunc: absGradConfig.gradFunc
    };
    function split_(x, numOrSizeSplits, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $x = convertToTensor(x, "x", "split");
      var inputs = { x: $x };
      var attr = { numOrSizeSplits, axis };
      return ENGINE.runKernel(SplitV, inputs, attr);
    }
    var split = /* @__PURE__ */ op({ split_ });
    var concatGradConfig = {
      kernelName: Concat,
      saveAllInputs: true,
      gradFunc: function(dy, saved, attrs) {
        var shapes = saved.map(function(t) {
          return t.shape;
        });
        var axis = attrs.axis;
        var $axis = parseAxisParam(axis, saved[0].shape)[0];
        var sizeSplits = shapes.map(function(s) {
          return s[$axis];
        });
        var derTensors = split(dy, sizeSplits, $axis);
        return derTensors.map(function(t) {
          return function() {
            return t;
          };
        });
      }
    };
    function conv2DBackpropFilter_(x, dy, filterShape, strides, pad2, dataFormat, dimRoundingMode) {
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      var x4D = x;
      if (x.rank === 3) {
        x4D = reshape$1(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
      }
      var dy4D = dy;
      if (dy4D.rank === 3) {
        dy4D = reshape$1(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
      }
      assert(x4D.rank === 4, function() {
        return "Error in conv2dDerFilter: input must be rank 4, but got shape " + "".concat(x4D.shape, ".");
      });
      assert(dy4D.rank === 4, function() {
        return "Error in conv2dDerFilter: dy must be rank 4, but got shape " + "".concat(dy4D.shape, ".");
      });
      assert(filterShape.length === 4, function() {
        return "Error in conv2dDerFilter: filterShape must be length 4, but got " + "".concat(filterShape, ".");
      });
      var inDepth = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
      var outDepth = dataFormat === "NHWC" ? dy4D.shape[3] : dy4D.shape[1];
      assert(inDepth === filterShape[2], function() {
        return "Error in conv2dDerFilter: depth of input ".concat(inDepth, ") must ") + "match input depth in filter (".concat(filterShape[2], ".");
      });
      assert(outDepth === filterShape[3], function() {
        return "Error in conv2dDerFilter: depth of dy (".concat(outDepth, ") must ") + "match output depth for filter (".concat(filterShape[3], ").");
      });
      checkPadOnDimRoundingMode("conv2dDerFilter", pad2, dimRoundingMode);
      var inputs = { x: x4D, dy: dy4D };
      var attrs = { strides, pad: pad2, dataFormat, dimRoundingMode, filterShape };
      return ENGINE.runKernel(Conv2DBackpropFilter, inputs, attrs);
    }
    var conv2DBackpropFilter = /* @__PURE__ */ op({ conv2DBackpropFilter_ });
    function conv2DBackpropInput_(xShape, dy, filter, strides, pad2, dataFormat, dimRoundingMode) {
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      assert(xShape.length === dy.rank, function() {
        return "Length of inShape " + "(".concat(xShape.length, ") and rank of dy (").concat(dy.rank, ") must match");
      });
      var xShape4D = xShape;
      var dy4D = dy;
      var reshapedTo4D = false;
      if (dy.rank === 3) {
        reshapedTo4D = true;
        dy4D = reshape$1(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
        xShape4D = [1, xShape[0], xShape[1], xShape[2]];
      }
      assert(xShape4D.length === 4, function() {
        return "Error in conv2dDerInput: inShape must be length 4, but got length " + "".concat(xShape4D.length, ".");
      });
      assert(dy4D.rank === 4, function() {
        return "Error in conv2dDerInput: dy must be rank 4, but got " + "rank ".concat(dy4D.rank);
      });
      assert(filter.rank === 4, function() {
        return "Error in conv2dDerInput: filter must be rank 4, but got " + "rank ".concat(filter.rank);
      });
      var inDepth = dataFormat === "NHWC" ? xShape4D[3] : xShape4D[1];
      var outDepth = dataFormat === "NHWC" ? dy4D.shape[3] : dy4D.shape[1];
      assert(inDepth === filter.shape[2], function() {
        return "Error in conv2dDerInput: depth of input (".concat(inDepth, ") must ") + "match input depth for filter ".concat(filter.shape[2], ".");
      });
      assert(outDepth === filter.shape[3], function() {
        return "Error in conv2dDerInput: depth of output (".concat(outDepth, ") must ") + "match output depth for filter ".concat(filter.shape[3], ".");
      });
      checkPadOnDimRoundingMode("conv2dDerInput", pad2, dimRoundingMode);
      var inputs = { dy: dy4D, filter };
      var attrs = { strides, pad: pad2, dataFormat, dimRoundingMode, inputShape: xShape4D };
      var res = ENGINE.runKernel(Conv2DBackpropInput, inputs, attrs);
      if (reshapedTo4D) {
        return reshape$1(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var conv2DBackpropInput = /* @__PURE__ */ op({ conv2DBackpropInput_ });
    var conv2DGradConfig = {
      kernelName: Conv2D$1,
      inputsToSave: ["x", "filter"],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 2), x4D = _a2[0], $filter = _a2[1];
        var dilations = attrs.dilations, strides = attrs.strides, pad2 = attrs.pad, dataFormat = attrs.dataFormat;
        assert(tupleValuesAreOne(dilations), function() {
          return "Error in gradient of conv2D: dilation rates greater than 1 " + "are not yet supported in gradients. Got dilations '".concat(dilations, "'");
        });
        return {
          x: function() {
            return conv2DBackpropInput(x4D.shape, dy, $filter, strides, pad2, dataFormat);
          },
          filter: function() {
            return conv2DBackpropFilter(x4D, dy, $filter.shape, strides, pad2, dataFormat);
          }
        };
      }
    };
    function conv2d_(x, filter, strides, pad2, dataFormat, dilations, dimRoundingMode) {
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      if (dilations === void 0) {
        dilations = [1, 1];
      }
      var $x = convertToTensor(x, "x", "conv2d", "float32");
      var $filter = convertToTensor(filter, "filter", "conv2d", "float32");
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape$1($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, function() {
        return "Error in conv2d: input must be rank 4, but got rank ".concat(x4D.rank, ".");
      });
      assert($filter.rank === 4, function() {
        return "Error in conv2d: filter must be rank 4, but got rank " + "".concat($filter.rank, ".");
      });
      checkPadOnDimRoundingMode("conv2d", pad2, dimRoundingMode);
      var inDepth = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
      assert(inDepth === $filter.shape[2], function() {
        return "Error in conv2d: depth of input (".concat(inDepth, ") must match ") + "input depth for filter ".concat($filter.shape[2], ".");
      });
      assert(eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in conv2D: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      assert(stridesOrDilationsArePositive(dilations), function() {
        return "Error in conv2D: Dilated rates should be larger than 0.";
      });
      assert(stridesOrDilationsArePositive(strides), function() {
        return "Error in conv2D: Strides should be larger than 0.";
      });
      var inputs = { x: x4D, filter: $filter };
      var attrs = { strides, pad: pad2, dataFormat, dilations, dimRoundingMode };
      var res = ENGINE.runKernel(Conv2D$1, inputs, attrs);
      if (reshapedTo4D) {
        return reshape$1(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var conv2d$1 = /* @__PURE__ */ op({ conv2d_ });
    var conv2DBackpropInputGradConfig = {
      kernelName: Conv2DBackpropInput,
      inputsToSave: ["dy", "filter"],
      gradFunc: function(ddx, saved, attrs) {
        var _a2 = __read(saved, 2), dy = _a2[0], filter = _a2[1];
        var strides = attrs.strides, pad2 = attrs.pad, dataFormat = attrs.dataFormat, dimRoundingMode = attrs.dimRoundingMode;
        return {
          dy: function() {
            return conv2d$1(ddx, filter, strides, pad2, dataFormat, 1, dimRoundingMode);
          },
          filter: function() {
            return conv2DBackpropFilter(ddx, dy, filter.shape, strides, pad2, dataFormat, dimRoundingMode);
          }
        };
      }
    };
    function conv3DBackpropFilter_(x, dy, filterShape, strides, pad2) {
      var x5D = x;
      if (x.rank === 4) {
        x5D = reshape$1(x, [1, x.shape[0], x.shape[1], x.shape[2], x.shape[3]]);
      }
      var dy5D = dy;
      if (dy5D.rank === 4) {
        dy5D = reshape$1(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);
      }
      assert(x5D.rank === 5, function() {
        return "Error in conv3dDerFilter: input must be rank 5, but got shape " + "".concat(x5D.shape, ".");
      });
      assert(dy5D.rank === 5, function() {
        return "Error in conv3dDerFilter: dy must be rank 5, but got shape " + "".concat(dy5D.shape, ".");
      });
      assert(filterShape.length === 5, function() {
        return "Error in conv3dDerFilter: filterShape must be length 5, but got " + "".concat(filterShape, ".");
      });
      assert(x5D.shape[4] === filterShape[3], function() {
        return "Error in conv3dDerFilter: depth of input ".concat(x5D.shape[4], ") must ") + "match input depth in filter (".concat(filterShape[3], ".");
      });
      assert(dy5D.shape[4] === filterShape[4], function() {
        return "Error in conv3dDerFilter: depth of dy (".concat(dy5D.shape[4], ") must ") + "match output depth for filter (".concat(filterShape[4], ").");
      });
      var inputs = { x: x5D, dy: dy5D };
      var attrs = { strides, pad: pad2, filterShape };
      return ENGINE.runKernel(Conv3DBackpropFilterV2, inputs, attrs);
    }
    var conv3DBackpropFilter = /* @__PURE__ */ op({ conv3DBackpropFilter_ });
    function conv3DBackpropInput_(xShape, dy, filter, strides, pad2) {
      assert(xShape.length === dy.rank, function() {
        return "Length of inShape " + "(".concat(xShape.length, ") and rank of dy (").concat(dy.rank, ") must match");
      });
      var xShape5D = xShape;
      var dy5D = dy;
      var reshapedTo5D = false;
      if (dy.rank === 4) {
        reshapedTo5D = true;
        dy5D = reshape$1(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);
        xShape5D = [1, xShape[0], xShape[1], xShape[2], xShape[3]];
      }
      var inDepth = xShape5D[4];
      var outDepth = dy5D.shape[4];
      assert(xShape5D.length === 5, function() {
        return "Error in conv3dDerInput: inShape must be length 5, but got length " + "".concat(xShape5D.length, ".");
      });
      assert(dy5D.rank === 5, function() {
        return "Error in conv3dDerInput: dy must be rank 5, but got " + "rank ".concat(dy5D.rank);
      });
      assert(filter.rank === 5, function() {
        return "Error in conv3dDerInput: filter must be rank 5, but got " + "rank ".concat(filter.rank);
      });
      assert(inDepth === filter.shape[3], function() {
        return "Error in conv3dDerInput: depth of input (".concat(inDepth, ") must ") + "match input depth for filter ".concat(filter.shape[3], ".");
      });
      assert(outDepth === filter.shape[4], function() {
        return "Error in conv3dDerInput: depth of output (".concat(outDepth, ") must ") + "match output depth for filter ".concat(filter.shape[4], ".");
      });
      var inputs = { dy: dy5D, filter };
      var attrs = { pad: pad2, strides, inputShape: xShape5D };
      var res = ENGINE.runKernel(Conv3DBackpropInputV2, inputs, attrs);
      if (reshapedTo5D) {
        return reshape$1(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
      }
      return res;
    }
    var conv3DBackpropInput = /* @__PURE__ */ op({ conv3DBackpropInput_ });
    var conv3DGradConfig = {
      kernelName: Conv3D$1,
      inputsToSave: ["x", "filter"],
      gradFunc: function(dy, saved, attrs) {
        var dilations = attrs.dilations, strides = attrs.strides, pad2 = attrs.pad;
        assert(tupleValuesAreOne(dilations), function() {
          return "Error in gradient of conv3D: dilation rates greater than 1 are " + "not yet supported in gradients. Got dilations '".concat(dilations, "'");
        });
        var _a2 = __read(saved, 2), x5D = _a2[0], $filter = _a2[1];
        return {
          x: function() {
            return conv3DBackpropInput(x5D.shape, dy, $filter, strides, pad2);
          },
          filter: function() {
            return conv3DBackpropFilter(x5D, dy, $filter.shape, strides, pad2);
          }
        };
      }
    };
    function sin_(x) {
      var $x = convertToTensor(x, "x", "sin", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Sin, inputs);
    }
    var sin = /* @__PURE__ */ op({ sin_ });
    var cosGradConfig = {
      kernelName: Cos,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return mul(neg(sin(cast(x, "float32"))), dy);
        } };
      }
    };
    function sinh_(x) {
      var $x = convertToTensor(x, "x", "sinh");
      var inputs = { x: $x };
      return ENGINE.runKernel(Sinh, inputs);
    }
    var sinh = /* @__PURE__ */ op({ sinh_ });
    var coshGradConfig = {
      kernelName: Cosh,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return mul(sinh(cast(x, "float32")), dy);
        } };
      }
    };
    function axesAreInnerMostDims(axes, rank) {
      for (var i = 0; i < axes.length; ++i) {
        if (axes[axes.length - i - 1] !== rank - 1 - i) {
          return false;
        }
      }
      return true;
    }
    function combineLocations(outputLoc, reduceLoc, axes) {
      var rank = outputLoc.length + reduceLoc.length;
      var loc = [];
      var outIdx = 0;
      var reduceIdx = 0;
      for (var dim = 0; dim < rank; dim++) {
        if (axes.indexOf(dim) === -1) {
          loc.push(outputLoc[outIdx++]);
        } else {
          loc.push(reduceLoc[reduceIdx++]);
        }
      }
      return loc;
    }
    function computeOutAndReduceShapes(aShape, axes) {
      var outShape = [];
      var rank = aShape.length;
      for (var dim = 0; dim < rank; dim++) {
        if (axes.indexOf(dim) === -1) {
          outShape.push(aShape[dim]);
        }
      }
      var reduceShape = axes.map(function(dim2) {
        return aShape[dim2];
      });
      return [outShape, reduceShape];
    }
    function expandShapeToKeepDim(shape, axes) {
      var reduceSubShape = axes.map(function(x) {
        return 1;
      });
      return combineLocations(shape, reduceSubShape, axes);
    }
    function getAxesPermutation(axes, rank) {
      if (axesAreInnerMostDims(axes, rank)) {
        return null;
      }
      var result = [];
      for (var i = 0; i < rank; ++i) {
        if (axes.indexOf(i) === -1) {
          result.push(i);
        }
      }
      axes.forEach(function(axis) {
        return result.push(axis);
      });
      return result;
    }
    function getUndoAxesPermutation(axes) {
      return axes.map(function(axis, i) {
        return [i, axis];
      }).sort(function(a, b) {
        return a[1] - b[1];
      }).map(function(x) {
        return x[0];
      });
    }
    function cumsum_(x, axis, exclusive, reverse2) {
      if (axis === void 0) {
        axis = 0;
      }
      if (exclusive === void 0) {
        exclusive = false;
      }
      if (reverse2 === void 0) {
        reverse2 = false;
      }
      var $x = convertToTensor(x, "x", "cumsum");
      var inputs = { x: $x };
      var attrs = { axis, exclusive, reverse: reverse2 };
      return ENGINE.runKernel(Cumsum, inputs, attrs);
    }
    var cumsum = /* @__PURE__ */ op({ cumsum_ });
    function tidy(nameOrFn, fn) {
      return ENGINE.tidy(nameOrFn, fn);
    }
    function dispose(container) {
      var tensors = getTensorsInContainer(container);
      tensors.forEach(function(tensor) {
        return tensor.dispose();
      });
    }
    function keep(result) {
      return ENGINE.keep(result);
    }
    function complex_(real2, imag2) {
      var $real = convertToTensor(real2, "real", "complex");
      var $imag = convertToTensor(imag2, "imag", "complex");
      assertShapesMatch($real.shape, $imag.shape, "real and imag shapes, ".concat($real.shape, " and ").concat($imag.shape, ", ") + "must match in call to tf.complex().");
      var inputs = { real: $real, imag: $imag };
      return ENGINE.runKernel(Complex, inputs);
    }
    var complex = /* @__PURE__ */ op({ complex_ });
    function imag_(input2) {
      var $input = convertToTensor(input2, "input", "imag");
      var inputs = { input: $input };
      return ENGINE.runKernel(Imag, inputs);
    }
    var imag = /* @__PURE__ */ op({ imag_ });
    function real_(input2) {
      var $input = convertToTensor(input2, "input", "real");
      var inputs = { input: $input };
      return ENGINE.runKernel(Real, inputs);
    }
    var real = /* @__PURE__ */ op({ real_ });
    function transpose_(x, perm, conjugate) {
      var $x = convertToTensor(x, "x", "transpose");
      if (perm == null) {
        perm = $x.shape.map(function(s, i) {
          return i;
        }).reverse();
      }
      assert($x.rank === perm.length, function() {
        return "Error in transpose: rank of input ".concat($x.rank, " ") + "must match length of perm ".concat(perm, ".");
      });
      perm.forEach(function(axis) {
        assert(axis >= 0 && axis < $x.rank, function() {
          return "All entries in 'perm' must be between 0 and ".concat($x.rank - 1) + " but got ".concat(perm);
        });
      });
      if ($x.rank <= 1) {
        return $x.clone();
      }
      var inputs = { x: $x };
      var attrs = { perm };
      if ($x.dtype === "complex64") {
        return tidy(function() {
          var $real = real($x);
          var $imag = imag($x);
          $real = ENGINE.runKernel(Transpose, { x: $real }, attrs);
          $imag = ENGINE.runKernel(Transpose, { x: $imag }, attrs);
          if (conjugate) {
            $imag = neg($imag);
          }
          return complex($real, $imag);
        });
      }
      return ENGINE.runKernel(Transpose, inputs, attrs);
    }
    var transpose = /* @__PURE__ */ op({ transpose_ });
    var cumsumGradConfig = {
      kernelName: Cumsum,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 1), x = _a2[0];
        var axis = attrs.axis, exclusive = attrs.exclusive, reverse2 = attrs.reverse;
        return {
          x: function() {
            var permutation = getAxesPermutation([axis], x.rank);
            var out = cumsum(dy, axis, exclusive, !reverse2);
            if (permutation != null) {
              out = transpose(out, permutation);
            }
            return out;
          }
        };
      }
    };
    function depthwiseConv2dNativeBackpropFilter_(x, dy, filterShape, strides, pad2, dilations, dimRoundingMode) {
      if (dilations === void 0) {
        dilations = [1, 1];
      }
      var x4D = x;
      if (x.rank === 3) {
        x4D = reshape$1(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
      }
      var dy4D = dy;
      if (dy4D.rank === 3) {
        dy4D = reshape$1(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
      }
      var inputs = { x: x4D, dy: dy4D };
      var attrs = { strides, pad: pad2, dimRoundingMode, dilations, filterShape };
      return ENGINE.runKernel(DepthwiseConv2dNativeBackpropFilter, inputs, attrs);
    }
    var depthwiseConv2dNativeBackpropFilter = op({ depthwiseConv2dNativeBackpropFilter_ });
    function depthwiseConv2dNativeBackpropInput_(xShape, dy, filter, strides, pad2, dilations, dimRoundingMode) {
      if (dilations === void 0) {
        dilations = [1, 1];
      }
      var dy4D = dy;
      var reshapedTo4D = false;
      if (dy.rank === 3) {
        reshapedTo4D = true;
        dy4D = reshape$1(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
      }
      var inputs = { dy: dy4D, filter };
      var attrs = { strides, pad: pad2, dimRoundingMode, dilations, inputShape: xShape };
      var res = (
        // tslint:disable-next-line: no-unnecessary-type-assertion
        ENGINE.runKernel(DepthwiseConv2dNativeBackpropInput, inputs, attrs)
      );
      if (reshapedTo4D) {
        return reshape$1(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var depthwiseConv2dNativeBackpropInput = op({ depthwiseConv2dNativeBackpropInput_ });
    var depthwiseConv2dNativeGradConfig = {
      kernelName: DepthwiseConv2dNative,
      inputsToSave: ["x", "filter"],
      gradFunc: function(dy, saved, attrs) {
        var dilations = attrs.dilations, strides = attrs.strides, pad2 = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
        var $dilations = dilations == null ? [1, 1] : dilations;
        assert(tupleValuesAreOne($dilations), function() {
          return "Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations " + "'".concat($dilations, "'");
        });
        var _a2 = __read(saved, 2), x = _a2[0], filter = _a2[1];
        assert(x.rank === 4, function() {
          return "Error in gradient of depthwiseConv2dNative: input must be " + "rank 4, but got rank ".concat(x.rank, ".");
        });
        assert(filter.rank === 4, function() {
          return "Error in gradient of depthwiseConv2dNative: filter must be " + "rank 4, but got rank ".concat(filter.rank, ".");
        });
        assert(x.shape[3] === filter.shape[2], function() {
          return "Error in gradient of depthwiseConv2d: number of input " + "channels (".concat(x.shape[3], ") must match the inChannels dimension ") + "in filter ".concat(filter.shape[2], ".");
        });
        assert(eitherStridesOrDilationsAreOne(strides, $dilations), function() {
          return "Error in gradient of depthwiseConv2d: Either strides or " + "dilations must be  1. Got strides ".concat(strides, " and dilations ") + "'".concat($dilations, "'.");
        });
        checkPadOnDimRoundingMode("depthwiseConv2d", pad2, dimRoundingMode);
        return {
          x: function() {
            return depthwiseConv2dNativeBackpropInput(x.shape, dy, filter, strides, pad2, $dilations, dimRoundingMode);
          },
          filter: function() {
            return depthwiseConv2dNativeBackpropFilter(x, dy, filter.shape, strides, pad2, $dilations, dimRoundingMode);
          }
        };
      }
    };
    var dilation2dGradConfig = {
      kernelName: Dilation2D,
      inputsToSave: ["x", "filter"],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 2), x = _a2[0], filter = _a2[1];
        var inputInputs = { x, filter, dy };
        var filterInputs = { x, filter, dy };
        return {
          x: function() {
            return ENGINE.runKernel(Dilation2DBackpropInput, inputInputs, attrs);
          },
          filter: function() {
            return ENGINE.runKernel(Dilation2DBackpropFilter, filterInputs, attrs);
          }
        };
      }
    };
    var eluGradConfig = {
      kernelName: Elu$1,
      outputsToSave: [true],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), y = _a2[0];
        var inputs = { dy, y };
        return { x: function() {
          return ENGINE.runKernel(EluGrad, inputs);
        } };
      }
    };
    function exp_(x) {
      var $x = convertToTensor(x, "x", "exp");
      var inputs = { x: $x };
      return ENGINE.runKernel(Exp, inputs);
    }
    var exp = /* @__PURE__ */ op({ exp_ });
    var erfGradConfig = {
      kernelName: Erf,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        var a = mul(exp(neg(square(x))), 2 / Math.sqrt(Math.PI));
        return { x: function() {
          return mul(dy, a);
        } };
      }
    };
    var expGradConfig = {
      kernelName: Exp,
      outputsToSave: [true],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), y = _a2[0];
        return { x: function() {
          return mul(dy, y);
        } };
      }
    };
    var expandDimsGradConfig = {
      kernelName: ExpandDims,
      inputsToSave: ["input"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), input2 = _a2[0];
        return { input: function() {
          return reshape$1(dy, input2.shape);
        } };
      }
    };
    var expm1GradConfig = {
      kernelName: Expm1,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return mul(dy, exp(x));
        } };
      }
    };
    var floorGradConfig = {
      kernelName: Floor,
      gradFunc: function(dy) {
        return { x: function() {
          return zerosLike(dy);
        } };
      }
    };
    var floorDivGradConfig = {
      kernelName: FloorDiv,
      inputsToSave: ["a", "b"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 2), a = _a2[0], b = _a2[1];
        var outShape = assertAndGetBroadcastShape(a.shape, b.shape);
        var derA = function() {
          var res = div(dy, cast(b, "float32"));
          var reduceAxes = getReductionAxes(a.shape, outShape);
          if (reduceAxes.length > 0) {
            return reshape$1(sum(res, reduceAxes), a.shape);
          }
          return res;
        };
        var derB = function() {
          var res = mul(dy, cast(a, "float32"));
          var reduceAxes = getReductionAxes(b.shape, outShape);
          if (reduceAxes.length > 0) {
            res = reshape$1(sum(res, reduceAxes), b.shape);
          }
          var tmp = square(b);
          return neg(div(res, cast(tmp, "float32")));
        };
        return { a: derA, b: derB };
      }
    };
    function rsqrt_(x) {
      var $x = convertToTensor(x, "x", "rsqrt", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Rsqrt, inputs);
    }
    var rsqrt = /* @__PURE__ */ op({ rsqrt_ });
    function tile_(x, reps) {
      var $x = convertToTensor(x, "x", "tile", "string_or_numeric");
      assert($x.rank === reps.length, function() {
        return "Error in transpose: rank of input ".concat($x.rank, " ") + "must match length of reps ".concat(reps, ".");
      });
      var inputs = { x: $x };
      var attrs = { reps };
      return ENGINE.runKernel(Tile, inputs, attrs);
    }
    var tile = /* @__PURE__ */ op({ tile_ });
    var fusedBatchNormGradConfig = {
      kernelName: FusedBatchNorm,
      inputsToSave: ["x", "mean", "variance", "scale"],
      gradFunc: function(dy, saved, attrs) {
        var varianceEpsilon = attrs.varianceEpsilon;
        var _a2 = __read(saved, 4), x = _a2[0], mean = _a2[1], variance = _a2[2], scale = _a2[3];
        var scaleValue = scale == null ? scalar(1) : scale;
        var reductionAxes = getReductionAxes(mean.shape, x.shape);
        var tileShape = [];
        if (mean.rank === 1) {
          for (var i = 0; i < x.shape.length - 1; ++i) {
            tileShape.push(x.shape[i]);
          }
          tileShape.push(1);
        }
        var xMinusMean = sub(x, mean);
        var dyTimesScaleValue = mul(dy, scaleValue);
        var oneOverSqrtVariance = rsqrt(add$1(variance, scalar(varianceEpsilon)));
        var minusHalfRCube = mul(mul(mul(oneOverSqrtVariance, oneOverSqrtVariance), oneOverSqrtVariance), scalar(-0.5));
        var derX = function() {
          if (mean.rank === 1) {
            return reshape$1(mul(mul(dy, tile(reshape$1(oneOverSqrtVariance, [1, 1, 1, mean.shape[0]]), tileShape)), scaleValue), x.shape);
          } else {
            return reshape$1(mul(mul(dy, oneOverSqrtVariance), scaleValue), x.shape);
          }
        };
        var derMean = function() {
          var meanDer = mul(mul(oneOverSqrtVariance, scalar(-1)), dyTimesScaleValue);
          if (mean.rank === 1) {
            meanDer = sum(meanDer, reductionAxes);
          }
          return reshape$1(meanDer, mean.shape);
        };
        var derVariance = function() {
          var varianceDer = mul(mul(minusHalfRCube, xMinusMean), dyTimesScaleValue);
          if (mean.rank === 1) {
            varianceDer = sum(varianceDer, reductionAxes);
          }
          return reshape$1(varianceDer, mean.shape);
        };
        var derScale = function() {
          var xMinusMean2TimesRsqrt = mul(xMinusMean, oneOverSqrtVariance);
          var scaleDer = mul(dy, xMinusMean2TimesRsqrt);
          if (mean.rank === 1) {
            scaleDer = sum(scaleDer, reductionAxes);
          }
          return reshape$1(scaleDer, mean.shape);
        };
        var derOffset = function() {
          var offsetDer = dy;
          if (mean.rank === 1) {
            offsetDer = sum(offsetDer, reductionAxes);
          }
          return reshape$1(offsetDer, mean.shape);
        };
        return {
          x: derX,
          mean: derMean,
          variance: derVariance,
          scale: derScale,
          offset: derOffset
        };
      }
    };
    function stack_(tensors, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $tensors = convertToTensorArray(tensors, "tensors", "stack", "string_or_numeric");
      assert($tensors.length >= 1, function() {
        return "Pass at least one tensor to tf.stack";
      });
      if ($tensors.length > 0) {
        assert(axis <= $tensors[0].rank, function() {
          return "Axis must be <= rank of the tensor";
        });
      }
      var inputs = $tensors;
      var attrs = { axis };
      return ENGINE.runKernel(Pack, inputs, attrs);
    }
    var stack = /* @__PURE__ */ op({ stack_ });
    function unsortedSegmentSum_(x, segmentIds, numSegments) {
      var $x = convertToTensor(x, "x", "unsortedSegmentSum");
      var $segmentIds = convertToTensor(segmentIds, "segmentIds", "unsortedSegmentSum", "int32");
      assert(isInt(numSegments), function() {
        return "numSegments must be of dtype int";
      });
      var inputs = { x: $x, segmentIds: $segmentIds };
      var attrs = { numSegments };
      return ENGINE.runKernel(UnsortedSegmentSum, inputs, attrs);
    }
    var unsortedSegmentSum = /* @__PURE__ */ op({ unsortedSegmentSum_ });
    var gatherGradConfig = {
      kernelName: GatherV2,
      inputsToSave: ["x", "indices"],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 2), x = _a2[0], indices = _a2[1];
        var axis = attrs.axis, batchDims = attrs.batchDims;
        var parsedAxis = parseAxisParam(axis, x.shape)[0];
        var derXBatch = function(x2, indices2, dy2) {
          return function() {
            var paramsShape = x2.shape;
            var indicesSize = indices2.size;
            var outerShape = paramsShape.slice(0, parsedAxis);
            var outerDims = outerShape.length;
            var innerShape = paramsShape.slice(axis, paramsShape.length).slice(1);
            var innerDims = innerShape.length;
            var outerAxesIndices = arrayRange(0, outerDims);
            var innerAxesIndices = arrayRange(outerDims + 1, outerDims + 1 + innerDims);
            var valuesShape = arrayConcat([
              outerShape,
              [indicesSize],
              innerShape
            ]);
            var values = reshape$1(dy2, valuesShape);
            var reshapedIndices = reshape$1(indices2, [indicesSize]);
            var transposeDims = arrayConcat([[outerDims], outerAxesIndices, innerAxesIndices]);
            var valuesTranspose = transpose(values, transposeDims);
            var paramsGrad = unsortedSegmentSum(valuesTranspose, reshapedIndices, x2.shape[parsedAxis]);
            var invertTransposeDims = getUndoAxesPermutation(transposeDims);
            paramsGrad = transpose(paramsGrad, invertTransposeDims);
            return paramsGrad;
          };
        };
        if (batchDims === 1) {
          var batchSize = x.shape[0];
          var xBatch_1 = x.split(batchSize, 0);
          var derXBatched = function() {
            var stacked = stack(xBatch_1.map(function(x2, i) {
              return derXBatch(x2, indices.slice(i, 1), dy.slice(i, 1))();
            }));
            return stacked.reshape(x.shape);
          };
          return { x: derXBatched, indices: function() {
            return indices;
          } };
        } else {
          return { x: derXBatch(x, indices, dy), indices: function() {
            return indices;
          } };
        }
      }
    };
    function arrayRange(start, stop) {
      var result = [];
      for (var i = start; i < stop; ++i) {
        result.push(i);
      }
      return result;
    }
    function arrayConcat(arrays) {
      var result = [];
      for (var i = 0; i < arrays.length; ++i) {
        for (var j = 0; j < arrays[i].length; ++j) {
          result.push(arrays[i][j]);
        }
      }
      return result;
    }
    var greaterEqualGradConfig = {
      kernelName: GreaterEqual,
      inputsToSave: ["a", "b"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 2), a = _a2[0], b = _a2[1];
        return { a: function() {
          return zerosLike(a);
        }, b: function() {
          return zerosLike(b);
        } };
      }
    };
    var identityGradConfig = {
      kernelName: Identity,
      gradFunc: function(dy) {
        return { x: function() {
          return cast(dy, "float32");
        } };
      }
    };
    var isFiniteGradConfig = {
      kernelName: IsFinite,
      gradFunc: function(dy) {
        return { x: function() {
          return zerosLike(dy);
        } };
      }
    };
    var isInfGradConfig = {
      kernelName: IsInf,
      gradFunc: function(dy) {
        return { x: function() {
          return zerosLike(dy);
        } };
      }
    };
    var isNanGradConfig = {
      kernelName: IsNan,
      gradFunc: function(dy) {
        return { x: function() {
          return zerosLike(dy);
        } };
      }
    };
    function greater_(a, b) {
      var _a2;
      var $a = convertToTensor(a, "a", "greater", "string_or_numeric");
      var $b = convertToTensor(b, "b", "greater", "string_or_numeric");
      _a2 = __read(makeTypesMatch($a, $b), 2), $a = _a2[0], $b = _a2[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Greater, inputs);
    }
    var greater$1 = /* @__PURE__ */ op({ greater_ });
    var leakyReluGradConfig = {
      kernelName: LeakyRelu,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 1), x = _a2[0];
        var alpha = attrs.alpha;
        var mask = greater$1(x, 0);
        return { x: function() {
          return where(mask, dy, mul(dy, alpha));
        } };
      }
    };
    var log1pGradConfig = {
      kernelName: Log1p,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return div(dy, add$1(x, 1));
        } };
      }
    };
    var logGradConfig = {
      kernelName: Log,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return div(dy, cast(x, "float32"));
        } };
      }
    };
    var logSoftmaxGradConfig = {
      kernelName: LogSoftmax$1,
      inputsToSave: [],
      outputsToSave: [true],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 1), value = _a2[0];
        var axis = attrs.axis;
        return {
          logits: function() {
            var keepDims = true;
            var softmax2 = exp(value);
            return sub(dy, mul(sum(dy, axis, keepDims), softmax2));
          }
        };
      }
    };
    function localResponseNormalizationBackprop_(x, y, dy, depthRadius, bias, alpha, beta) {
      if (depthRadius === void 0) {
        depthRadius = 5;
      }
      if (bias === void 0) {
        bias = 1;
      }
      if (alpha === void 0) {
        alpha = 1;
      }
      if (beta === void 0) {
        beta = 0.5;
      }
      var inputs = { x, y, dy };
      var attrs = { depthRadius, bias, alpha, beta };
      return ENGINE.runKernel(LRNGrad, inputs, attrs);
    }
    var localResponseNormalizationBackprop = op({ localResponseNormalizationBackprop_ });
    var lrnGradConfig = {
      kernelName: LRN,
      inputsToSave: ["x"],
      outputsToSave: [true],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 2), x = _a2[0], y = _a2[1];
        var depthRadius = attrs.depthRadius, bias = attrs.bias, alpha = attrs.alpha, beta = attrs.beta;
        return {
          x: function() {
            return localResponseNormalizationBackprop(x, y, dy, depthRadius, bias, alpha, beta);
          }
        };
      }
    };
    function equal_(a, b) {
      var _a2;
      var $a = convertToTensor(a, "a", "equal", "string_or_numeric");
      var $b = convertToTensor(b, "b", "equal", "string_or_numeric");
      _a2 = __read(makeTypesMatch($a, $b), 2), $a = _a2[0], $b = _a2[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Equal, inputs);
    }
    var equal = /* @__PURE__ */ op({ equal_ });
    function gradForMinAndMax(dy, y, xOrig, origAxes) {
      if (y.rank < xOrig.rank) {
        y = reshape$1(y, expandShapeToKeepDim(y.shape, origAxes));
      }
      if (dy.rank < xOrig.rank) {
        dy = reshape$1(dy, expandShapeToKeepDim(dy.shape, origAxes));
      }
      return {
        x: function() {
          var dx = mul(dy, cast(equal(xOrig, y), dy.dtype));
          return dx;
        }
      };
    }
    var maxGradConfig = {
      kernelName: Max,
      inputsToSave: ["x"],
      outputsToSave: [true],
      gradFunc: function(dy, saved, attrs) {
        var maxAttrs = attrs;
        var reductionIndices = maxAttrs.reductionIndices;
        var x = saved[0];
        var y = saved[1];
        var origAxes = parseAxisParam(reductionIndices, x.shape);
        var maxGrad = gradForMinAndMax(dy, y, x, origAxes);
        return {
          x: function() {
            return maxGrad["x"]();
          }
        };
      }
    };
    function less_(a, b) {
      var _a2;
      var $a = convertToTensor(a, "a", "less", "string_or_numeric");
      var $b = convertToTensor(b, "b", "less", "string_or_numeric");
      _a2 = __read(makeTypesMatch($a, $b), 2), $a = _a2[0], $b = _a2[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Less, inputs);
    }
    var less$1 = /* @__PURE__ */ op({ less_ });
    var maximumGradConfig = {
      kernelName: Maximum$1,
      inputsToSave: ["a", "b"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 2), a = _a2[0], b = _a2[1];
        var derA = function() {
          return mul(dy, cast(greaterEqual(a, b), "float32"));
        };
        var derB = function() {
          return mul(dy, cast(less$1(a, b), "float32"));
        };
        return { a: derA, b: derB };
      }
    };
    function maxPool3dGrad_(dy, input2, output, filterSize, strides, pad2, dimRoundingMode) {
      var $dy = convertToTensor(dy, "dy", "maxPool3dGrad");
      var $input = convertToTensor(input2, "input", "maxPool3dGrad");
      var $output = convertToTensor(output, "output", "maxPool3dGrad");
      var dy5D = $dy;
      var input5D = $input;
      var output5D = $output;
      var reshapedTo5D = false;
      if ($input.rank === 4) {
        reshapedTo5D = true;
        dy5D = reshape$1($dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2], $dy.shape[3]]);
        input5D = reshape$1($input, [
          1,
          $input.shape[0],
          $input.shape[1],
          $input.shape[2],
          $input.shape[3]
        ]);
        output5D = reshape$1($output, [
          1,
          $output.shape[0],
          $output.shape[1],
          $output.shape[2],
          $output.shape[3]
        ]);
      }
      assert(dy5D.rank === 5, function() {
        return "Error in maxPool3dGrad: dy must be rank 5 but got rank " + "".concat(dy5D.rank, ".");
      });
      assert(input5D.rank === 5, function() {
        return "Error in maxPool3dGrad: input must be rank 5 but got rank " + "".concat(input5D.rank, ".");
      });
      assert(output5D.rank === 5, function() {
        return "Error in maxPool3dGrad: output must be rank 5 but got rank " + "".concat(output5D.rank, ".");
      });
      checkPadOnDimRoundingMode("maxPool3dGrad", pad2, dimRoundingMode);
      var inputs = { dy: dy5D, input: input5D, output: output5D };
      var attrs = { filterSize, strides, pad: pad2, dimRoundingMode };
      var res = ENGINE.runKernel(MaxPool3DGrad, inputs, attrs);
      if (reshapedTo5D) {
        return reshape$1(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
      }
      return res;
    }
    var maxPool3dGrad = /* @__PURE__ */ op({ maxPool3dGrad_ });
    var maxPool3DGradConfig = {
      kernelName: MaxPool3D,
      inputsToSave: ["x"],
      outputsToSave: [true],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 2), x = _a2[0], y = _a2[1];
        var filterSize = attrs.filterSize, strides = attrs.strides, pad2 = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
        return {
          x: function() {
            return maxPool3dGrad(dy, x, y, filterSize, strides, pad2, dimRoundingMode);
          }
        };
      }
    };
    function maxPoolGrad_(dy, input2, output, filterSize, strides, pad2, dimRoundingMode) {
      var $dy = convertToTensor(dy, "dy", "maxPoolGrad");
      var $input = convertToTensor(input2, "input", "maxPoolGrad");
      var $output = convertToTensor(output, "output", "maxPoolGrad");
      assert($input.rank === $dy.rank, function() {
        return "Rank of input (".concat($input.rank, ") does not match rank of dy ") + "(".concat($dy.rank, ")");
      });
      assert($dy.rank === 4, function() {
        return "Error in maxPoolGrad: dy must be rank 4 but got rank " + "".concat($dy.rank, ".");
      });
      assert($input.rank === 4, function() {
        return "Error in maxPoolGrad: input must be rank 4 but got rank " + "".concat($input.rank, ".");
      });
      checkPadOnDimRoundingMode("maxPoolGrad", pad2, dimRoundingMode);
      var inputs = { dy: $dy, input: $input, output: $output };
      var attrs = { filterSize, strides, pad: pad2, dimRoundingMode };
      return ENGINE.runKernel(MaxPoolGrad, inputs, attrs);
    }
    var maxPoolGrad = /* @__PURE__ */ op({ maxPoolGrad_ });
    var maxPoolGradConfig = {
      kernelName: MaxPool,
      inputsToSave: ["x"],
      outputsToSave: [true],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 2), x = _a2[0], y = _a2[1];
        var filterSize = attrs.filterSize, strides = attrs.strides, pad2 = attrs.pad;
        return {
          x: function() {
            return maxPoolGrad(dy, x, y, filterSize, strides, pad2);
          }
        };
      }
    };
    function zeros$1(shape, dtype) {
      if (dtype === void 0) {
        dtype = "float32";
      }
      assertNonNegativeIntegerDimensions(shape);
      if (dtype === "complex64") {
        var real2 = zeros$1(shape, "float32");
        var imag2 = zeros$1(shape, "float32");
        return complex(real2, imag2);
      }
      var values = makeZerosTypedArray(sizeFromShape(shape), dtype);
      return ENGINE.makeTensor(values, shape, dtype);
    }
    function ones$1(shape, dtype) {
      if (dtype === void 0) {
        dtype = "float32";
      }
      assertNonNegativeIntegerDimensions(shape);
      if (dtype === "complex64") {
        var real2 = ones$1(shape, "float32");
        var imag2 = zeros$1(shape, "float32");
        return complex(real2, imag2);
      }
      var values = makeOnesTypedArray(sizeFromShape(shape), dtype);
      return ENGINE.makeTensor(values, shape, dtype);
    }
    var meanGradConfig = {
      kernelName: Mean,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 1), x = _a2[0];
        var axis = attrs.axis;
        var axes = parseAxisParam(axis, x.shape);
        var shapes = computeOutAndReduceShapes(x.shape, axes);
        var reduceShape = shapes[1];
        var reduceSize = sizeFromShape(reduceShape);
        var derX = function() {
          var expandedDyShape = x.shape.slice();
          axes.forEach(function(axis2) {
            expandedDyShape[axis2] = 1;
          });
          var expandedDy = reshape$1(dy, expandedDyShape);
          var res = div(mul(expandedDy, ones$1(x.shape, "float32")), reduceSize);
          return res;
        };
        return { x: derX };
      }
    };
    var minGradConfig = {
      kernelName: Min,
      inputsToSave: ["x"],
      outputsToSave: [true],
      gradFunc: function(dy, saved, attrs) {
        var minAttrs = attrs;
        var axis = minAttrs.axis;
        var _a2 = __read(saved, 2), x = _a2[0], y = _a2[1];
        var origAxes = parseAxisParam(axis, x.shape);
        var minGrad = gradForMinAndMax(dy, y, x, origAxes);
        return {
          x: function() {
            return minGrad["x"]();
          }
        };
      }
    };
    var minimumGradConfig = {
      kernelName: Minimum$1,
      inputsToSave: ["a", "b"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 2), a = _a2[0], b = _a2[1];
        var derA = function() {
          return mul(dy, cast(lessEqual(a, b), "float32"));
        };
        var derB = function() {
          return mul(dy, cast(greater$1(a, b), "float32"));
        };
        return { a: derA, b: derB };
      }
    };
    function slice_(x, begin, size) {
      var $x = convertToTensor(x, "x", "slice", "string_or_numeric");
      if ($x.rank === 0) {
        throw new Error("Slicing scalar is not possible");
      }
      var inputs = { x: $x };
      var attrs = { begin, size };
      return ENGINE.runKernel(Slice, inputs, attrs);
    }
    var slice = /* @__PURE__ */ op({ slice_ });
    var mirrorPadGradConfig = {
      kernelName: MirrorPad,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved, attrs) {
        var x = saved[0];
        var paddings = attrs.paddings;
        var begin = paddings.map(function(p) {
          return p[0];
        });
        return { x: function() {
          return slice(dy, begin, x.shape);
        } };
      }
    };
    function floor_(x) {
      var $x = convertToTensor(x, "x", "floor", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Floor, inputs);
    }
    var floor = /* @__PURE__ */ op({ floor_ });
    var modGradConfig = {
      kernelName: Mod,
      inputsToSave: ["a", "b"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 2), a = _a2[0], b = _a2[1];
        var outShape = assertAndGetBroadcastShape(a.shape, b.shape);
        var derA = function() {
          var reduceAxes = getReductionAxes(a.shape, outShape);
          if (reduceAxes.length > 0) {
            return reshape$1(sum(dy, reduceAxes), a.shape);
          }
          return dy;
        };
        var derB = function() {
          var res = mul(dy, neg(floor(div(a, b))));
          var reduceAxes = getReductionAxes(b.shape, outShape);
          if (reduceAxes.length > 0) {
            return reshape$1(sum(res, reduceAxes), b.shape);
          }
          return res;
        };
        return { a: derA, b: derB };
      }
    };
    var multiplyGradConfig = {
      kernelName: Multiply$1,
      inputsToSave: ["a", "b"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 2), a = _a2[0], b = _a2[1];
        var outShape = assertAndGetBroadcastShape(a.shape, b.shape);
        var derA = function() {
          var res = mul(dy, cast(b, "float32"));
          var reduceAxes = getReductionAxes(a.shape, outShape);
          if (reduceAxes.length > 0) {
            return reshape$1(sum(res, reduceAxes), a.shape);
          }
          return res;
        };
        var derB = function() {
          var res = mul(dy, cast(a, "float32"));
          var reduceAxes = getReductionAxes(b.shape, outShape);
          if (reduceAxes.length > 0) {
            return reshape$1(sum(res, reduceAxes), b.shape);
          }
          return res;
        };
        return { a: derA, b: derB };
      }
    };
    var negGradConfig = {
      kernelName: Neg,
      gradFunc: function(dy) {
        return { x: function() {
          return neg(dy);
        } };
      }
    };
    var oneHotGradConfig = {
      kernelName: OneHot,
      inputsToSave: ["indices"],
      gradFunc: function(dy, saved) {
        var indices = saved[0];
        return { indices: function() {
          return zeros$1(indices.shape, "float32");
        } };
      }
    };
    var onesLikeGradConfig = {
      kernelName: OnesLike,
      gradFunc: function(dy) {
        return { x: function() {
          return zerosLike(dy);
        } };
      }
    };
    function unstack_(x, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $x = convertToTensor(x, "x", "unstack", "string_or_numeric");
      assert(axis >= -$x.shape.length && axis < $x.shape.length, function() {
        return "Axis = ".concat(axis, " is not in [-").concat($x.shape.length, ", ").concat($x.shape.length, ")");
      });
      var inputs = { value: $x };
      var attrs = { axis };
      return ENGINE.runKernel(Unpack, inputs, attrs);
    }
    var unstack = /* @__PURE__ */ op({ unstack_ });
    var packGradConfig = {
      kernelName: Pack,
      saveAllInputs: true,
      gradFunc: function(dy, saved, attrs) {
        var axis = attrs.axis;
        var derTensors = unstack(dy, axis);
        return derTensors.map(function(t) {
          return function() {
            return t;
          };
        });
      }
    };
    var padV2GradConfig = {
      kernelName: PadV2,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved, attrs) {
        var x = saved[0];
        var paddings = attrs.paddings;
        var begin = paddings.map(function(p) {
          return p[0];
        });
        return { x: function() {
          return slice(dy, begin, x.shape);
        } };
      }
    };
    function log_(x) {
      var $x = convertToTensor(x, "x", "log", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Log, inputs);
    }
    var log = /* @__PURE__ */ op({ log_ });
    function pow_(base, exp2) {
      var _a2;
      var $base = convertToTensor(base, "base", "pow");
      var $exp = convertToTensor(exp2, "exp", "pow");
      _a2 = __read(makeTypesMatch($base, $exp), 2), $base = _a2[0], $exp = _a2[1];
      var inputs = { a: $base, b: $exp };
      return ENGINE.runKernel(Pow, inputs);
    }
    var pow = /* @__PURE__ */ op({ pow_ });
    var powGradConfig = {
      kernelName: Pow,
      inputsToSave: ["a", "b"],
      outputsToSave: [true],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 3), a = _a2[0], b = _a2[1], y = _a2[2];
        var base = a;
        var exp2 = b;
        var outShape = assertAndGetBroadcastShape(base.shape, exp2.shape);
        var derBase = function() {
          var expFloat = cast(exp2, "float32");
          var res = mul(dy, mul(expFloat, pow(base, sub(expFloat, scalar(1)))));
          var reduceAxes = getReductionAxes(base.shape, outShape);
          if (reduceAxes.length > 0) {
            res = sum(res, reduceAxes);
          }
          return reshape$1(res, base.shape);
        };
        var derExp = function() {
          var condition = greater$1(base, 0);
          var logBase = where(condition, log(base), zerosLike(base));
          var res = mul(dy, mul(y, logBase));
          var reduceAxes = getReductionAxes(exp2.shape, outShape);
          if (reduceAxes.length > 0) {
            res = sum(res, reduceAxes);
          }
          return reshape$1(res, exp2.shape);
        };
        return { a: derBase, b: derExp };
      }
    };
    var preluGradConfig = {
      kernelName: Prelu,
      inputsToSave: ["x", "alpha"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 2), x = _a2[0], alpha = _a2[1];
        var mask = greater$1(x, 0);
        return {
          x: function() {
            return where(mask, dy, mul(dy, alpha));
          },
          alpha: function() {
            var res = where(mask, zerosLike(dy), mul(dy, x));
            var reduceAxes = getReductionAxes(alpha.shape, dy.shape);
            if (reduceAxes.length > 0) {
              res = sum(res, reduceAxes);
            }
            return reshape$1(res, alpha.shape);
          }
        };
      }
    };
    function isBrowser() {
      return typeof window !== "undefined" && window.document != null || //@ts-ignore
      typeof WorkerGlobalScope !== "undefined";
    }
    var ENV = env();
    ENV.registerFlag("DEBUG", function() {
      return false;
    }, function(debugValue) {
      if (debugValue) {
        console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.");
      }
    });
    ENV.registerFlag("IS_BROWSER", function() {
      return isBrowser();
    });
    ENV.registerFlag("IS_NODE", function() {
      return typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined";
    });
    ENV.registerFlag("IS_CHROME", function() {
      return typeof navigator !== "undefined" && navigator != null && navigator.userAgent != null && /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
    });
    ENV.registerFlag("IS_SAFARI", function() {
      return typeof navigator !== "undefined" && navigator != null && navigator.userAgent != null && /Safari/.test(navigator.userAgent) && /Apple/.test(navigator.vendor);
    });
    ENV.registerFlag("PROD", function() {
      return false;
    });
    ENV.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY", function() {
      return ENV.getBool("DEBUG");
    });
    ENV.registerFlag("DEPRECATION_WARNINGS_ENABLED", function() {
      return true;
    });
    ENV.registerFlag("IS_TEST", function() {
      return false;
    });
    ENV.registerFlag("CHECK_COMPUTATION_FOR_ERRORS", function() {
      return ENV.getBool("DEBUG");
    });
    ENV.registerFlag("WRAP_TO_IMAGEBITMAP", function() {
      return false;
    });
    ENV.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU", function() {
      return false;
    });
    ENV.registerFlag("USE_SETTIMEOUTCUSTOM", function() {
      return false;
    });
    var CompositeArrayBuffer = (
      /** @class */
      function() {
        function CompositeArrayBuffer2(buffers) {
          this.shards = [];
          this.previousShardIndex = 0;
          if (buffers == null) {
            return;
          }
          if (!(buffers instanceof Array)) {
            buffers = [buffers];
          }
          buffers = buffers.map(function(bufferOrTypedArray) {
            if (isTypedArray(bufferOrTypedArray)) {
              return bufferOrTypedArray.buffer;
            }
            return bufferOrTypedArray;
          });
          if (buffers.length === 0) {
            return;
          }
          this.bufferUniformSize = buffers[0].byteLength;
          var start = 0;
          for (var i = 0; i < buffers.length; i++) {
            var buffer = buffers[i];
            if (i !== buffers.length - 1 && buffer.byteLength !== this.bufferUniformSize) {
              this.bufferUniformSize = void 0;
            }
            var end = start + buffer.byteLength;
            this.shards.push({ buffer, start, end });
            start = end;
          }
          if (this.shards.length === 0) {
            this.byteLength = 0;
          }
          this.byteLength = this.shards[this.shards.length - 1].end;
        }
        CompositeArrayBuffer2.join = function(buffers) {
          return new CompositeArrayBuffer2(buffers).slice();
        };
        CompositeArrayBuffer2.prototype.slice = function(start, end) {
          if (start === void 0) {
            start = 0;
          }
          if (end === void 0) {
            end = this.byteLength;
          }
          if (this.shards.length === 0) {
            return new ArrayBuffer(0);
          }
          start = isNaN(Number(start)) ? 0 : start;
          end = isNaN(Number(end)) ? 0 : end;
          start = Math.max(0, start);
          end = Math.min(this.byteLength, end);
          if (end <= start) {
            return new ArrayBuffer(0);
          }
          var startShardIndex = this.findShardForByte(start);
          if (startShardIndex === -1) {
            throw new Error("Could not find start shard for byte ".concat(start));
          }
          var size = end - start;
          var outputBuffer = new ArrayBuffer(size);
          var outputArray = new Uint8Array(outputBuffer);
          var sliced = 0;
          for (var i = startShardIndex; i < this.shards.length; i++) {
            var shard = this.shards[i];
            var globalStart = start + sliced;
            var localStart = globalStart - shard.start;
            var outputStart = sliced;
            var globalEnd = Math.min(end, shard.end);
            var localEnd = globalEnd - shard.start;
            var outputSlice = new Uint8Array(shard.buffer, localStart, localEnd - localStart);
            outputArray.set(outputSlice, outputStart);
            sliced += outputSlice.length;
            if (end < shard.end) {
              break;
            }
          }
          return outputBuffer;
        };
        CompositeArrayBuffer2.prototype.findShardForByte = function(byteIndex) {
          if (this.shards.length === 0 || byteIndex < 0 || byteIndex >= this.byteLength) {
            return -1;
          }
          if (this.bufferUniformSize != null) {
            this.previousShardIndex = Math.floor(byteIndex / this.bufferUniformSize);
            return this.previousShardIndex;
          }
          function check(shard) {
            if (byteIndex < shard.start) {
              return -1;
            }
            if (byteIndex >= shard.end) {
              return 1;
            }
            return 0;
          }
          if (check(this.shards[this.previousShardIndex]) === 0) {
            return this.previousShardIndex;
          }
          var index = search(this.shards, check);
          if (index === -1) {
            return -1;
          }
          this.previousShardIndex = index;
          return this.previousShardIndex;
        };
        return CompositeArrayBuffer2;
      }()
    );
    function search(sortedArray, compare) {
      var min2 = 0;
      var max2 = sortedArray.length;
      while (min2 <= max2) {
        var middle = Math.floor((max2 - min2) / 2) + min2;
        var side = compare(sortedArray[middle]);
        if (side === 0) {
          return middle;
        } else if (side < 0) {
          max2 = middle;
        } else {
          min2 = middle + 1;
        }
      }
      return -1;
    }
    var useNodeBuffer = typeof Buffer !== "undefined" && (typeof Blob === "undefined" || typeof atob === "undefined" || typeof btoa === "undefined");
    function stringByteLength(str) {
      if (useNodeBuffer) {
        return Buffer.byteLength(str, "utf8");
      }
      return new Blob([str]).size;
    }
    function arrayBufferToBase64String(buffer) {
      if (useNodeBuffer) {
        return Buffer.from(buffer).toString("base64");
      }
      var buf = new Uint8Array(buffer);
      var s = "";
      for (var i = 0, l = buf.length; i < l; i++) {
        s += String.fromCharCode(buf[i]);
      }
      return btoa(s);
    }
    function base64StringToArrayBuffer(str) {
      if (useNodeBuffer) {
        var buf = Buffer.from(str, "base64");
        return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
      }
      var s = atob(str);
      var buffer = new Uint8Array(s.length);
      for (var i = 0; i < s.length; ++i) {
        buffer.set([s.charCodeAt(i)], i);
      }
      return buffer.buffer;
    }
    function getModelJSONForModelArtifacts(artifacts, manifest) {
      var result = {
        modelTopology: artifacts.modelTopology,
        format: artifacts.format,
        generatedBy: artifacts.generatedBy,
        convertedBy: artifacts.convertedBy,
        weightsManifest: manifest
      };
      if (artifacts.signature != null) {
        result.signature = artifacts.signature;
      }
      if (artifacts.userDefinedMetadata != null) {
        result.userDefinedMetadata = artifacts.userDefinedMetadata;
      }
      if (artifacts.modelInitializer != null) {
        result.modelInitializer = artifacts.modelInitializer;
      }
      if (artifacts.initializerSignature != null) {
        result.initializerSignature = artifacts.initializerSignature;
      }
      if (artifacts.trainingConfig != null) {
        result.trainingConfig = artifacts.trainingConfig;
      }
      return result;
    }
    function getModelArtifactsForJSONSync(modelJSON, weightSpecs, weightData) {
      var modelArtifacts = {
        modelTopology: modelJSON.modelTopology,
        format: modelJSON.format,
        generatedBy: modelJSON.generatedBy,
        convertedBy: modelJSON.convertedBy
      };
      if (modelJSON.trainingConfig != null) {
        modelArtifacts.trainingConfig = modelJSON.trainingConfig;
      }
      if (modelJSON.weightsManifest != null) {
        if (!weightSpecs) {
          throw new Error("modelJSON has weightsManifest but weightSpecs is null");
        }
        if (!weightData) {
          throw new Error("modelJSON has weightsManifest but weightData is null");
        }
        modelArtifacts.weightSpecs = weightSpecs;
        modelArtifacts.weightData = weightData;
      }
      if (modelJSON.signature != null) {
        modelArtifacts.signature = modelJSON.signature;
      }
      if (modelJSON.userDefinedMetadata != null) {
        modelArtifacts.userDefinedMetadata = modelJSON.userDefinedMetadata;
      }
      if (modelJSON.modelInitializer != null) {
        modelArtifacts.modelInitializer = modelJSON.modelInitializer;
      }
      if (modelJSON.initializerSignature != null) {
        modelArtifacts.initializerSignature = modelJSON.initializerSignature;
      }
      return modelArtifacts;
    }
    function getModelArtifactsForJSON(modelJSON, loadWeights) {
      return __awaiter(this, void 0, void 0, function() {
        var weightSpecs, weightData;
        var _a2;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              if (!(modelJSON.weightsManifest != null)) return [3, 2];
              return [4, loadWeights(modelJSON.weightsManifest)];
            case 1:
              _a2 = __read.apply(void 0, [_b.sent(), 2]), weightSpecs = _a2[0], weightData = _a2[1];
              _b.label = 2;
            case 2:
              return [2, getModelArtifactsForJSONSync(modelJSON, weightSpecs, weightData)];
          }
        });
      });
    }
    function getModelArtifactsInfoForJSON(modelArtifacts) {
      if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
        throw new Error("Expected JSON model topology, received ArrayBuffer.");
      }
      return {
        dateSaved: /* @__PURE__ */ new Date(),
        modelTopologyType: "JSON",
        modelTopologyBytes: modelArtifacts.modelTopology == null ? 0 : stringByteLength(JSON.stringify(modelArtifacts.modelTopology)),
        weightSpecsBytes: modelArtifacts.weightSpecs == null ? 0 : stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)),
        weightDataBytes: modelArtifacts.weightData == null ? 0 : new CompositeArrayBuffer(modelArtifacts.weightData).byteLength
      };
    }
    function getWeightSpecs(weightsManifest) {
      var e_3, _a2;
      var weightSpecs = [];
      try {
        for (var weightsManifest_1 = __values(weightsManifest), weightsManifest_1_1 = weightsManifest_1.next(); !weightsManifest_1_1.done; weightsManifest_1_1 = weightsManifest_1.next()) {
          var entry = weightsManifest_1_1.value;
          weightSpecs.push.apply(weightSpecs, __spreadArray([], __read(entry.weights), false));
        }
      } catch (e_3_1) {
        e_3 = { error: e_3_1 };
      } finally {
        try {
          if (weightsManifest_1_1 && !weightsManifest_1_1.done && (_a2 = weightsManifest_1.return)) _a2.call(weightsManifest_1);
        } finally {
          if (e_3) throw e_3.error;
        }
      }
      return weightSpecs;
    }
    var IORouterRegistry = (
      /** @class */
      function() {
        function IORouterRegistry2() {
          this.saveRouters = [];
          this.loadRouters = [];
        }
        IORouterRegistry2.getInstance = function() {
          if (IORouterRegistry2.instance == null) {
            IORouterRegistry2.instance = new IORouterRegistry2();
          }
          return IORouterRegistry2.instance;
        };
        IORouterRegistry2.registerSaveRouter = function(saveRouter) {
          IORouterRegistry2.getInstance().saveRouters.push(saveRouter);
        };
        IORouterRegistry2.registerLoadRouter = function(loadRouter) {
          IORouterRegistry2.getInstance().loadRouters.push(loadRouter);
        };
        IORouterRegistry2.getSaveHandlers = function(url) {
          return IORouterRegistry2.getHandlers(url, "save");
        };
        IORouterRegistry2.getLoadHandlers = function(url, loadOptions) {
          return IORouterRegistry2.getHandlers(url, "load", loadOptions);
        };
        IORouterRegistry2.getHandlers = function(url, handlerType, loadOptions) {
          var validHandlers = [];
          var routers = handlerType === "load" ? IORouterRegistry2.getInstance().loadRouters : IORouterRegistry2.getInstance().saveRouters;
          routers.forEach(function(router) {
            var handler = router(url, loadOptions);
            if (handler !== null) {
              validHandlers.push(handler);
            }
          });
          return validHandlers;
        };
        return IORouterRegistry2;
      }()
    );
    var DATABASE_NAME = "tensorflowjs";
    var DATABASE_VERSION = 1;
    var MODEL_STORE_NAME = "models_store";
    var INFO_STORE_NAME = "model_info_store";
    function getIndexedDBFactory() {
      if (!env().getBool("IS_BROWSER")) {
        throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");
      }
      var theWindow = typeof window === "undefined" ? self : window;
      var factory = theWindow.indexedDB || theWindow.mozIndexedDB || theWindow.webkitIndexedDB || theWindow.msIndexedDB || theWindow.shimIndexedDB;
      if (factory == null) {
        throw new Error("The current browser does not appear to support IndexedDB.");
      }
      return factory;
    }
    function setUpDatabase(openRequest) {
      var db = openRequest.result;
      db.createObjectStore(MODEL_STORE_NAME, { keyPath: "modelPath" });
      db.createObjectStore(INFO_STORE_NAME, { keyPath: "modelPath" });
    }
    var BrowserIndexedDB = (
      /** @class */
      function() {
        function BrowserIndexedDB2(modelPath) {
          this.indexedDB = getIndexedDBFactory();
          if (modelPath == null || !modelPath) {
            throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");
          }
          this.modelPath = modelPath;
        }
        BrowserIndexedDB2.prototype.save = function(modelArtifacts) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
                throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");
              }
              return [2, this.databaseAction(this.modelPath, modelArtifacts)];
            });
          });
        };
        BrowserIndexedDB2.prototype.load = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              return [2, this.databaseAction(this.modelPath)];
            });
          });
        };
        BrowserIndexedDB2.prototype.databaseAction = function(modelPath, modelArtifacts) {
          var _this = this;
          return new Promise(function(resolve, reject) {
            var openRequest = _this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
            openRequest.onupgradeneeded = function() {
              return setUpDatabase(openRequest);
            };
            openRequest.onsuccess = function() {
              var db = openRequest.result;
              if (modelArtifacts == null) {
                var modelTx = db.transaction(MODEL_STORE_NAME, "readonly");
                var modelStore = modelTx.objectStore(MODEL_STORE_NAME);
                var getRequest_1 = modelStore.get(_this.modelPath);
                getRequest_1.onsuccess = function() {
                  if (getRequest_1.result == null) {
                    db.close();
                    return reject(new Error("Cannot find model with path '".concat(_this.modelPath, "' ") + "in IndexedDB."));
                  } else {
                    resolve(getRequest_1.result.modelArtifacts);
                  }
                };
                getRequest_1.onerror = function(error) {
                  db.close();
                  return reject(getRequest_1.error);
                };
                modelTx.oncomplete = function() {
                  return db.close();
                };
              } else {
                modelArtifacts.weightData = CompositeArrayBuffer.join(modelArtifacts.weightData);
                var modelArtifactsInfo_1 = getModelArtifactsInfoForJSON(modelArtifacts);
                var infoTx_1 = db.transaction(INFO_STORE_NAME, "readwrite");
                var infoStore_1 = infoTx_1.objectStore(INFO_STORE_NAME);
                var putInfoRequest_1;
                try {
                  putInfoRequest_1 = infoStore_1.put({ modelPath: _this.modelPath, modelArtifactsInfo: modelArtifactsInfo_1 });
                } catch (error) {
                  return reject(error);
                }
                var modelTx_1;
                putInfoRequest_1.onsuccess = function() {
                  modelTx_1 = db.transaction(MODEL_STORE_NAME, "readwrite");
                  var modelStore2 = modelTx_1.objectStore(MODEL_STORE_NAME);
                  var putModelRequest;
                  try {
                    putModelRequest = modelStore2.put({
                      modelPath: _this.modelPath,
                      modelArtifacts,
                      modelArtifactsInfo: modelArtifactsInfo_1
                    });
                  } catch (error) {
                    return reject(error);
                  }
                  putModelRequest.onsuccess = function() {
                    return resolve({ modelArtifactsInfo: modelArtifactsInfo_1 });
                  };
                  putModelRequest.onerror = function(error) {
                    infoStore_1 = infoTx_1.objectStore(INFO_STORE_NAME);
                    var deleteInfoRequest = infoStore_1.delete(_this.modelPath);
                    deleteInfoRequest.onsuccess = function() {
                      db.close();
                      return reject(putModelRequest.error);
                    };
                    deleteInfoRequest.onerror = function(error2) {
                      db.close();
                      return reject(putModelRequest.error);
                    };
                  };
                };
                putInfoRequest_1.onerror = function(error) {
                  db.close();
                  return reject(putInfoRequest_1.error);
                };
                infoTx_1.oncomplete = function() {
                  if (modelTx_1 == null) {
                    db.close();
                  } else {
                    modelTx_1.oncomplete = function() {
                      return db.close();
                    };
                  }
                };
              }
            };
            openRequest.onerror = function(error) {
              return reject(openRequest.error);
            };
          });
        };
        return BrowserIndexedDB2;
      }()
    );
    BrowserIndexedDB.URL_SCHEME = "indexeddb://";
    var indexedDBRouter = function(url) {
      if (!env().getBool("IS_BROWSER")) {
        return null;
      } else {
        if (!Array.isArray(url) && url.startsWith(BrowserIndexedDB.URL_SCHEME)) {
          return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length));
        } else {
          return null;
        }
      }
    };
    IORouterRegistry.registerSaveRouter(indexedDBRouter);
    IORouterRegistry.registerLoadRouter(indexedDBRouter);
    function browserIndexedDB(modelPath) {
      return new BrowserIndexedDB(modelPath);
    }
    var PATH_SEPARATOR = "/";
    var PATH_PREFIX = "tensorflowjs_models";
    var INFO_SUFFIX = "info";
    var MODEL_TOPOLOGY_SUFFIX = "model_topology";
    var WEIGHT_SPECS_SUFFIX = "weight_specs";
    var WEIGHT_DATA_SUFFIX = "weight_data";
    var MODEL_METADATA_SUFFIX = "model_metadata";
    function getModelKeys(path) {
      return {
        info: [PATH_PREFIX, path, INFO_SUFFIX].join(PATH_SEPARATOR),
        topology: [PATH_PREFIX, path, MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR),
        weightSpecs: [PATH_PREFIX, path, WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR),
        weightData: [PATH_PREFIX, path, WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR),
        modelMetadata: [PATH_PREFIX, path, MODEL_METADATA_SUFFIX].join(PATH_SEPARATOR)
      };
    }
    function removeItems(keys) {
      var e_12, _a2;
      try {
        for (var _b = __values(Object.values(keys)), _c = _b.next(); !_c.done; _c = _b.next()) {
          var key = _c.value;
          window.localStorage.removeItem(key);
        }
      } catch (e_1_1) {
        e_12 = { error: e_1_1 };
      } finally {
        try {
          if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
        } finally {
          if (e_12) throw e_12.error;
        }
      }
    }
    var BrowserLocalStorage = (
      /** @class */
      function() {
        function BrowserLocalStorage2(modelPath) {
          if (!env().getBool("IS_BROWSER") || typeof window === "undefined" || typeof window.localStorage === "undefined") {
            throw new Error("The current environment does not support local storage.");
          }
          this.LS = window.localStorage;
          if (modelPath == null || !modelPath) {
            throw new Error("For local storage, modelPath must not be null, undefined or empty.");
          }
          this.modelPath = modelPath;
          this.keys = getModelKeys(this.modelPath);
        }
        BrowserLocalStorage2.prototype.save = function(modelArtifacts) {
          return __awaiter(this, void 0, void 0, function() {
            var topology, weightSpecs, modelArtifactsInfo, weightBuffer, metadata;
            return __generator(this, function(_a2) {
              if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
                throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");
              } else {
                topology = JSON.stringify(modelArtifacts.modelTopology);
                weightSpecs = JSON.stringify(modelArtifacts.weightSpecs);
                modelArtifactsInfo = getModelArtifactsInfoForJSON(modelArtifacts);
                weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);
                try {
                  this.LS.setItem(this.keys.info, JSON.stringify(modelArtifactsInfo));
                  this.LS.setItem(this.keys.topology, topology);
                  this.LS.setItem(this.keys.weightSpecs, weightSpecs);
                  this.LS.setItem(this.keys.weightData, arrayBufferToBase64String(weightBuffer));
                  metadata = {
                    format: modelArtifacts.format,
                    generatedBy: modelArtifacts.generatedBy,
                    convertedBy: modelArtifacts.convertedBy,
                    signature: modelArtifacts.signature != null ? modelArtifacts.signature : void 0,
                    userDefinedMetadata: modelArtifacts.userDefinedMetadata != null ? modelArtifacts.userDefinedMetadata : void 0,
                    modelInitializer: modelArtifacts.modelInitializer != null ? modelArtifacts.modelInitializer : void 0,
                    initializerSignature: modelArtifacts.initializerSignature != null ? modelArtifacts.initializerSignature : void 0,
                    trainingConfig: modelArtifacts.trainingConfig != null ? modelArtifacts.trainingConfig : void 0
                  };
                  this.LS.setItem(this.keys.modelMetadata, JSON.stringify(metadata));
                  return [2, { modelArtifactsInfo }];
                } catch (err) {
                  removeItems(this.keys);
                  throw new Error("Failed to save model '".concat(this.modelPath, "' to local storage: ") + "size quota being exceeded is a possible cause of this failure: " + "modelTopologyBytes=".concat(modelArtifactsInfo.modelTopologyBytes, ", ") + "weightSpecsBytes=".concat(modelArtifactsInfo.weightSpecsBytes, ", ") + "weightDataBytes=".concat(modelArtifactsInfo.weightDataBytes, "."));
                }
              }
              return [
                2
                /*return*/
              ];
            });
          });
        };
        BrowserLocalStorage2.prototype.load = function() {
          return __awaiter(this, void 0, void 0, function() {
            var info, out, topology, weightSpecs, metadataString, metadata, weightDataBase64;
            return __generator(this, function(_a2) {
              info = JSON.parse(this.LS.getItem(this.keys.info));
              if (info == null) {
                throw new Error("In local storage, there is no model with name '".concat(this.modelPath, "'"));
              }
              if (info.modelTopologyType !== "JSON") {
                throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");
              }
              out = {};
              topology = JSON.parse(this.LS.getItem(this.keys.topology));
              if (topology == null) {
                throw new Error("In local storage, the topology of model '".concat(this.modelPath, "' ") + "is missing.");
              }
              out.modelTopology = topology;
              weightSpecs = JSON.parse(this.LS.getItem(this.keys.weightSpecs));
              if (weightSpecs == null) {
                throw new Error("In local storage, the weight specs of model '".concat(this.modelPath, "' ") + "are missing.");
              }
              out.weightSpecs = weightSpecs;
              metadataString = this.LS.getItem(this.keys.modelMetadata);
              if (metadataString != null) {
                metadata = JSON.parse(metadataString);
                out.format = metadata.format;
                out.generatedBy = metadata.generatedBy;
                out.convertedBy = metadata.convertedBy;
                if (metadata.signature != null) {
                  out.signature = metadata.signature;
                }
                if (metadata.userDefinedMetadata != null) {
                  out.userDefinedMetadata = metadata.userDefinedMetadata;
                }
                if (metadata.modelInitializer != null) {
                  out.modelInitializer = metadata.modelInitializer;
                }
                if (metadata.initializerSignature != null) {
                  out.initializerSignature = metadata.initializerSignature;
                }
                if (metadata.trainingConfig != null) {
                  out.trainingConfig = metadata.trainingConfig;
                }
              }
              weightDataBase64 = this.LS.getItem(this.keys.weightData);
              if (weightDataBase64 == null) {
                throw new Error("In local storage, the binary weight values of model " + "'".concat(this.modelPath, "' are missing."));
              }
              out.weightData = base64StringToArrayBuffer(weightDataBase64);
              return [2, out];
            });
          });
        };
        return BrowserLocalStorage2;
      }()
    );
    BrowserLocalStorage.URL_SCHEME = "localstorage://";
    var localStorageRouter = function(url) {
      if (!env().getBool("IS_BROWSER")) {
        return null;
      } else {
        if (!Array.isArray(url) && url.startsWith(BrowserLocalStorage.URL_SCHEME)) {
          return browserLocalStorage(url.slice(BrowserLocalStorage.URL_SCHEME.length));
        } else {
          return null;
        }
      }
    };
    IORouterRegistry.registerSaveRouter(localStorageRouter);
    IORouterRegistry.registerLoadRouter(localStorageRouter);
    function browserLocalStorage(modelPath) {
      return new BrowserLocalStorage(modelPath);
    }
    var DEFAULT_FILE_NAME_PREFIX = "model";
    var DEFAULT_JSON_EXTENSION_NAME = ".json";
    var DEFAULT_WEIGHT_DATA_EXTENSION_NAME = ".weights.bin";
    function defer(f) {
      return new Promise(function(resolve) {
        return setTimeout(resolve);
      }).then(f);
    }
    var BrowserDownloads = (
      /** @class */
      function() {
        function BrowserDownloads2(fileNamePrefix) {
          if (!env().getBool("IS_BROWSER")) {
            throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");
          }
          if (fileNamePrefix.startsWith(BrowserDownloads2.URL_SCHEME)) {
            fileNamePrefix = fileNamePrefix.slice(BrowserDownloads2.URL_SCHEME.length);
          }
          if (fileNamePrefix == null || fileNamePrefix.length === 0) {
            fileNamePrefix = DEFAULT_FILE_NAME_PREFIX;
          }
          this.modelJsonFileName = fileNamePrefix + DEFAULT_JSON_EXTENSION_NAME;
          this.weightDataFileName = fileNamePrefix + DEFAULT_WEIGHT_DATA_EXTENSION_NAME;
        }
        BrowserDownloads2.prototype.save = function(modelArtifacts) {
          return __awaiter(this, void 0, void 0, function() {
            var weightBuffer, weightsURL, weightsManifest, modelJSON, modelJsonURL, jsonAnchor_1, weightDataAnchor_1;
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  if (typeof document === "undefined") {
                    throw new Error("Browser downloads are not supported in this environment since `document` is not present");
                  }
                  weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);
                  weightsURL = window.URL.createObjectURL(new Blob([weightBuffer], { type: "application/octet-stream" }));
                  if (!(modelArtifacts.modelTopology instanceof ArrayBuffer)) return [3, 1];
                  throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");
                case 1:
                  weightsManifest = [{
                    paths: ["./" + this.weightDataFileName],
                    weights: modelArtifacts.weightSpecs
                  }];
                  modelJSON = getModelJSONForModelArtifacts(modelArtifacts, weightsManifest);
                  modelJsonURL = window.URL.createObjectURL(new Blob([JSON.stringify(modelJSON)], { type: "application/json" }));
                  jsonAnchor_1 = this.modelJsonAnchor == null ? document.createElement("a") : this.modelJsonAnchor;
                  jsonAnchor_1.download = this.modelJsonFileName;
                  jsonAnchor_1.href = modelJsonURL;
                  return [4, defer(function() {
                    return jsonAnchor_1.dispatchEvent(new MouseEvent("click"));
                  })];
                case 2:
                  _a2.sent();
                  if (!(modelArtifacts.weightData != null)) return [3, 4];
                  weightDataAnchor_1 = this.weightDataAnchor == null ? document.createElement("a") : this.weightDataAnchor;
                  weightDataAnchor_1.download = this.weightDataFileName;
                  weightDataAnchor_1.href = weightsURL;
                  return [4, defer(function() {
                    return weightDataAnchor_1.dispatchEvent(new MouseEvent("click"));
                  })];
                case 3:
                  _a2.sent();
                  _a2.label = 4;
                case 4:
                  return [2, { modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts) }];
              }
            });
          });
        };
        return BrowserDownloads2;
      }()
    );
    BrowserDownloads.URL_SCHEME = "downloads://";
    var browserDownloadsRouter = function(url) {
      if (!env().getBool("IS_BROWSER")) {
        return null;
      } else {
        if (!Array.isArray(url) && url.startsWith(BrowserDownloads.URL_SCHEME)) {
          return browserDownloads(url.slice(BrowserDownloads.URL_SCHEME.length));
        } else {
          return null;
        }
      }
    };
    IORouterRegistry.registerSaveRouter(browserDownloadsRouter);
    function browserDownloads(fileNamePrefix) {
      if (fileNamePrefix === void 0) {
        fileNamePrefix = "model";
      }
      return new BrowserDownloads(fileNamePrefix);
    }
    function monitorPromisesProgress(promises, onProgress, startFraction, endFraction) {
      checkPromises(promises);
      startFraction = startFraction == null ? 0 : startFraction;
      endFraction = endFraction == null ? 1 : endFraction;
      checkFraction(startFraction, endFraction);
      var resolvedPromise = 0;
      var registerMonitor = function(promise) {
        promise.then(function(value) {
          var fraction = startFraction + ++resolvedPromise / promises.length * (endFraction - startFraction);
          onProgress(fraction);
          return value;
        });
        return promise;
      };
      function checkPromises(promises2) {
        assert(promises2 != null && Array.isArray(promises2) && promises2.length > 0, function() {
          return "promises must be a none empty array";
        });
      }
      function checkFraction(startFraction2, endFraction2) {
        assert(startFraction2 >= 0 && startFraction2 <= 1, function() {
          return "Progress fraction must be in range [0, 1], but " + "got startFraction ".concat(startFraction2);
        });
        assert(endFraction2 >= 0 && endFraction2 <= 1, function() {
          return "Progress fraction must be in range [0, 1], but " + "got endFraction ".concat(endFraction2);
        });
        assert(endFraction2 >= startFraction2, function() {
          return "startFraction must be no more than endFraction, but " + "got startFraction ".concat(startFraction2, " and endFraction ") + "".concat(endFraction2);
        });
      }
      return Promise.all(promises.map(registerMonitor));
    }
    function loadWeightsAsArrayBuffer(fetchURLs, loadOptions) {
      return __awaiter(this, void 0, void 0, function() {
        var fetchFunc, requests, fetchStartFraction, fetchEndFraction, responses, _b, bufferPromises, bufferStartFraction, bufferEndFraction, buffers, _c;
        return __generator(this, function(_d) {
          switch (_d.label) {
            case 0:
              if (loadOptions == null) {
                loadOptions = {};
              }
              fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch : loadOptions.fetchFunc;
              requests = fetchURLs.map(function(fetchURL) {
                return fetchFunc(fetchURL, loadOptions.requestInit, { isBinary: true });
              });
              fetchStartFraction = 0;
              fetchEndFraction = 0.5;
              if (!(loadOptions.onProgress == null)) return [3, 2];
              return [4, Promise.all(requests)];
            case 1:
              _b = _d.sent();
              return [3, 4];
            case 2:
              return [4, monitorPromisesProgress(requests, loadOptions.onProgress, fetchStartFraction, fetchEndFraction)];
            case 3:
              _b = _d.sent();
              _d.label = 4;
            case 4:
              responses = _b;
              bufferPromises = responses.map(function(response) {
                return response.arrayBuffer();
              });
              bufferStartFraction = 0.5;
              bufferEndFraction = 1;
              if (!(loadOptions.onProgress == null)) return [3, 6];
              return [4, Promise.all(bufferPromises)];
            case 5:
              _c = _d.sent();
              return [3, 8];
            case 6:
              return [4, monitorPromisesProgress(bufferPromises, loadOptions.onProgress, bufferStartFraction, bufferEndFraction)];
            case 7:
              _c = _d.sent();
              _d.label = 8;
            case 8:
              buffers = _c;
              return [2, buffers];
          }
        });
      });
    }
    function streamWeights(fetchURLs, loadOptions) {
      var _this = this;
      var _a2;
      var fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch : loadOptions.fetchFunc;
      var fetchIndex = 0;
      var chunkReader;
      (_a2 = loadOptions.onProgress) === null || _a2 === void 0 ? void 0 : _a2.call(loadOptions, 0);
      return new ReadableStream({
        pull: function(controller) {
          return __awaiter(_this, void 0, void 0, function() {
            var _a3, body, _b, done, value;
            return __generator(this, function(_c) {
              switch (_c.label) {
                case 0:
                  if (!(fetchIndex < fetchURLs.length)) return [3, 4];
                  if (!!chunkReader) return [3, 2];
                  return [4, fetchFunc(fetchURLs[fetchIndex], loadOptions.requestInit, { isBinary: true })];
                case 1:
                  body = _c.sent().body;
                  chunkReader = body.getReader();
                  _c.label = 2;
                case 2:
                  return [4, chunkReader.read()];
                case 3:
                  _b = _c.sent(), done = _b.done, value = _b.value;
                  if (done) {
                    fetchIndex++;
                    chunkReader = void 0;
                    (_a3 = loadOptions.onProgress) === null || _a3 === void 0 ? void 0 : _a3.call(loadOptions, fetchIndex / fetchURLs.length);
                    return [3, 0];
                  }
                  controller.enqueue(value);
                  return [
                    2
                    /*return*/
                  ];
                case 4:
                  controller.close();
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        }
      });
    }
    var OCTET_STREAM_MIME_TYPE = "application/octet-stream";
    var JSON_TYPE = "application/json";
    var HTTPRequest = (
      /** @class */
      function() {
        function HTTPRequest2(path, loadOptions) {
          this.DEFAULT_METHOD = "POST";
          if (loadOptions == null) {
            loadOptions = {};
          }
          this.weightPathPrefix = loadOptions.weightPathPrefix;
          this.weightUrlConverter = loadOptions.weightUrlConverter;
          if (loadOptions.fetchFunc != null) {
            assert(typeof loadOptions.fetchFunc === "function", function() {
              return "Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)";
            });
            this.fetch = loadOptions.fetchFunc;
          } else {
            this.fetch = env().platform.fetch;
          }
          assert(path != null && path.length > 0, function() {
            return "URL path for http must not be null, undefined or empty.";
          });
          if (Array.isArray(path)) {
            assert(path.length === 2, function() {
              return "URL paths for http must have a length of 2, " + "(actual length is ".concat(path.length, ").");
            });
          }
          this.path = path;
          if (loadOptions.requestInit != null && loadOptions.requestInit.body != null) {
            throw new Error("requestInit is expected to have no pre-existing body, but has one.");
          }
          this.requestInit = loadOptions.requestInit || {};
          this.loadOptions = loadOptions;
        }
        HTTPRequest2.prototype.save = function(modelArtifacts) {
          return __awaiter(this, void 0, void 0, function() {
            var init, weightsManifest, modelTopologyAndWeightManifest, weightBuffer, response;
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
                    throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");
                  }
                  init = Object.assign({ method: this.DEFAULT_METHOD }, this.requestInit);
                  init.body = new FormData();
                  weightsManifest = [{
                    paths: ["./model.weights.bin"],
                    weights: modelArtifacts.weightSpecs
                  }];
                  modelTopologyAndWeightManifest = getModelJSONForModelArtifacts(modelArtifacts, weightsManifest);
                  init.body.append("model.json", new Blob([JSON.stringify(modelTopologyAndWeightManifest)], { type: JSON_TYPE }), "model.json");
                  if (modelArtifacts.weightData != null) {
                    weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);
                    init.body.append("model.weights.bin", new Blob([weightBuffer], { type: OCTET_STREAM_MIME_TYPE }), "model.weights.bin");
                  }
                  return [4, this.fetch(this.path, init)];
                case 1:
                  response = _a2.sent();
                  if (response.ok) {
                    return [2, {
                      modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts),
                      responses: [response]
                    }];
                  } else {
                    throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status " + "".concat(response.status, "."));
                  }
              }
            });
          });
        };
        HTTPRequest2.prototype.loadModelJSON = function() {
          return __awaiter(this, void 0, void 0, function() {
            var modelConfigRequest, modelJSON, message, modelTopology, weightsManifest;
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  return [4, this.fetch(this.path, this.requestInit)];
                case 1:
                  modelConfigRequest = _a2.sent();
                  if (!modelConfigRequest.ok) {
                    throw new Error("Request to ".concat(this.path, " failed with status code ") + "".concat(modelConfigRequest.status, ". Please verify this URL points to ") + "the model JSON of the model to load.");
                  }
                  _a2.label = 2;
                case 2:
                  _a2.trys.push([2, 4, , 5]);
                  return [4, modelConfigRequest.json()];
                case 3:
                  modelJSON = _a2.sent();
                  return [3, 5];
                case 4:
                  _a2.sent();
                  message = "Failed to parse model JSON of response from ".concat(this.path, ".");
                  if (this.path.endsWith(".pb")) {
                    message += " 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.";
                  } else {
                    message += " Please make sure the server is serving valid JSON for this request.";
                  }
                  throw new Error(message);
                case 5:
                  modelTopology = modelJSON.modelTopology;
                  weightsManifest = modelJSON.weightsManifest;
                  if (modelTopology == null && weightsManifest == null) {
                    throw new Error("The JSON from HTTP path ".concat(this.path, " contains neither model ") + "topology or manifest for weights.");
                  }
                  return [2, modelJSON];
              }
            });
          });
        };
        HTTPRequest2.prototype.load = function() {
          return __awaiter(this, void 0, void 0, function() {
            var modelJSON;
            var _this = this;
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  if (this.loadOptions.streamWeights) {
                    return [2, this.loadStream()];
                  }
                  return [4, this.loadModelJSON()];
                case 1:
                  modelJSON = _a2.sent();
                  return [2, getModelArtifactsForJSON(modelJSON, function(weightsManifest) {
                    return _this.loadWeights(weightsManifest);
                  })];
              }
            });
          });
        };
        HTTPRequest2.prototype.loadStream = function() {
          return __awaiter(this, void 0, void 0, function() {
            var modelJSON, fetchURLs, weightSpecs, stream;
            var _this = this;
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  return [4, this.loadModelJSON()];
                case 1:
                  modelJSON = _a2.sent();
                  return [4, this.getWeightUrls(modelJSON.weightsManifest)];
                case 2:
                  fetchURLs = _a2.sent();
                  weightSpecs = getWeightSpecs(modelJSON.weightsManifest);
                  stream = function() {
                    return streamWeights(fetchURLs, _this.loadOptions);
                  };
                  return [2, Object.assign(Object.assign({}, modelJSON), { weightSpecs, getWeightStream: stream })];
              }
            });
          });
        };
        HTTPRequest2.prototype.getWeightUrls = function(weightsManifest) {
          return __awaiter(this, void 0, void 0, function() {
            var weightPath, _a2, prefix, suffix, pathPrefix, fetchURLs, urlPromises, weightsManifest_1, weightsManifest_1_1, weightsGroup, _b, _c, path, _d, _e, _f, _g;
            var e_2, _h, e_3, _j;
            return __generator(this, function(_k) {
              switch (_k.label) {
                case 0:
                  weightPath = Array.isArray(this.path) ? this.path[1] : this.path;
                  _a2 = __read(parseUrl(weightPath), 2), prefix = _a2[0], suffix = _a2[1];
                  pathPrefix = this.weightPathPrefix || prefix;
                  fetchURLs = [];
                  urlPromises = [];
                  try {
                    for (weightsManifest_1 = __values(weightsManifest), weightsManifest_1_1 = weightsManifest_1.next(); !weightsManifest_1_1.done; weightsManifest_1_1 = weightsManifest_1.next()) {
                      weightsGroup = weightsManifest_1_1.value;
                      try {
                        for (_b = (e_3 = void 0, __values(weightsGroup.paths)), _c = _b.next(); !_c.done; _c = _b.next()) {
                          path = _c.value;
                          if (this.weightUrlConverter != null) {
                            urlPromises.push(this.weightUrlConverter(path));
                          } else {
                            fetchURLs.push(pathPrefix + path + suffix);
                          }
                        }
                      } catch (e_3_1) {
                        e_3 = { error: e_3_1 };
                      } finally {
                        try {
                          if (_c && !_c.done && (_j = _b.return)) _j.call(_b);
                        } finally {
                          if (e_3) throw e_3.error;
                        }
                      }
                    }
                  } catch (e_2_1) {
                    e_2 = { error: e_2_1 };
                  } finally {
                    try {
                      if (weightsManifest_1_1 && !weightsManifest_1_1.done && (_h = weightsManifest_1.return)) _h.call(weightsManifest_1);
                    } finally {
                      if (e_2) throw e_2.error;
                    }
                  }
                  if (!this.weightUrlConverter) return [3, 2];
                  _e = (_d = fetchURLs.push).apply;
                  _f = [fetchURLs];
                  _g = [[]];
                  return [4, Promise.all(urlPromises)];
                case 1:
                  _e.apply(_d, _f.concat([__spreadArray.apply(void 0, _g.concat([__read.apply(void 0, [_k.sent()]), false]))]));
                  _k.label = 2;
                case 2:
                  return [2, fetchURLs];
              }
            });
          });
        };
        HTTPRequest2.prototype.loadWeights = function(weightsManifest) {
          return __awaiter(this, void 0, void 0, function() {
            var fetchURLs, weightSpecs, buffers;
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  return [4, this.getWeightUrls(weightsManifest)];
                case 1:
                  fetchURLs = _a2.sent();
                  weightSpecs = getWeightSpecs(weightsManifest);
                  return [4, loadWeightsAsArrayBuffer(fetchURLs, this.loadOptions)];
                case 2:
                  buffers = _a2.sent();
                  return [2, [weightSpecs, buffers]];
              }
            });
          });
        };
        return HTTPRequest2;
      }()
    );
    HTTPRequest.URL_SCHEME_REGEX = /^https?:\/\//;
    function parseUrl(url) {
      var lastSlash = url.lastIndexOf("/");
      var lastSearchParam = url.lastIndexOf("?");
      var prefix = url.substring(0, lastSlash);
      var suffix = lastSearchParam > lastSlash ? url.substring(lastSearchParam) : "";
      return [prefix + "/", suffix];
    }
    function isHTTPScheme(url) {
      return url.match(HTTPRequest.URL_SCHEME_REGEX) != null;
    }
    var httpRouter = function(url, loadOptions) {
      if (typeof fetch === "undefined" && (loadOptions == null || loadOptions.fetchFunc == null)) {
        return null;
      } else {
        var isHTTP = true;
        if (Array.isArray(url)) {
          isHTTP = url.every(function(urlItem) {
            return isHTTPScheme(urlItem);
          });
        } else {
          isHTTP = isHTTPScheme(url);
        }
        if (isHTTP) {
          return http(url, loadOptions);
        }
      }
      return null;
    };
    IORouterRegistry.registerSaveRouter(httpRouter);
    IORouterRegistry.registerLoadRouter(httpRouter);
    function http(path, loadOptions) {
      return new HTTPRequest(path, loadOptions);
    }
    function validateUpdateShape(shape, indices, updates) {
      var sliceDim = indices.rank > 1 ? indices.shape[indices.rank - 1] : 1;
      var batchDim = indices.rank > 1 ? indices.rank - 1 : 1;
      var shapeError = "Must have updates.shape = indices.shape[:batchDim] + " + "shape[sliceDim:], got updates.shape: ".concat(updates.shape) + ", indices.shape: ".concat(indices.shape, ", shape: ").concat(shape) + ", sliceDim: ".concat(sliceDim, ", and batchDim: ").concat(batchDim, ".");
      if (updates.rank < batchDim) {
        throw new Error(shapeError + " update.rank < ".concat(batchDim, ". "));
      }
      if (shape.length < sliceDim + (updates.rank - batchDim)) {
        throw new Error(shapeError + " Output shape length < ".concat(sliceDim + (updates.rank - batchDim)));
      }
      if (updates.rank !== batchDim + shape.length - sliceDim) {
        throw new Error(shapeError + " update.rank != ".concat(batchDim + shape.length - sliceDim));
      }
      for (var d = 0; d < batchDim; ++d) {
        if (updates.shape[d] !== indices.shape[d]) {
          throw new Error(shapeError + " updates.shape[".concat(d, "] (").concat(updates.shape[d], ") != indices.shape[").concat(d, "] (").concat(indices.shape[d], ")."));
        }
      }
      for (var d = 0; d < updates.rank - batchDim; ++d) {
        if (updates.shape[d + batchDim] !== shape[d + sliceDim]) {
          throw new Error(shapeError + " updates.shape[".concat(d + batchDim, "] (").concat(updates.shape[d + batchDim], ") != shape[").concat(d + batchDim, "] (").concat(shape[d + batchDim], ")"));
        }
      }
    }
    function validateInput(updates, indices, shape) {
      if (indices.rank < 1) {
        throw new Error("tf.scatterND() expects the indices to be rank 1 or higher," + " but the rank was ".concat(indices.rank, "."));
      }
      if (updates.rank < 1) {
        throw new Error("tf.scatterND() expects the updates to be rank 1 or higher," + " but the rank was ".concat(updates.rank, "."));
      }
      if (indices.dtype !== "int32") {
        throw new Error("The dtype of 'indices' should be int32, but got dtype: ".concat(indices.dtype));
      }
      if (shape.length < 1) {
        throw new Error("Output rank must be greater or equal to 1, but got shape: ".concat(shape));
      }
      if (shape.length === 0) {
        if (indices.size === 0) {
          throw new Error("Indices specified for empty output. indices shape: ".concat(indices.shape));
        }
        if (updates.size === 0) {
          throw new Error("Updates specified for empty output. updates shape: ".concat(updates.shape));
        }
      }
      validateUpdateShape(shape, indices, updates);
    }
    function parseSliceParams(x, begin, size) {
      var begin_;
      var xRank = x.shape.length;
      if (typeof begin === "number") {
        begin_ = __spreadArray([begin], __read(new Array(xRank - 1).fill(0)), false);
      } else if (begin.length < xRank) {
        begin_ = begin.concat(new Array(xRank - begin.length).fill(0));
      } else {
        begin_ = begin.slice();
      }
      begin_.forEach(function(d) {
        assert(d !== -1, function() {
          return "slice() does not support negative begin indexing.";
        });
      });
      var size_;
      if (size == null) {
        size_ = new Array(xRank).fill(-1);
      } else if (typeof size === "number") {
        size_ = __spreadArray([size], __read(new Array(xRank - 1).fill(-1)), false);
      } else if (size.length < xRank) {
        size_ = size.concat(new Array(xRank - size.length).fill(-1));
      } else {
        size_ = size;
      }
      size_ = size_.map(function(d, i) {
        if (d >= 0) {
          return d;
        } else {
          assert(d === -1, function() {
            return "Negative size values should be exactly -1 but got " + "".concat(d, " for the slice() size at index ").concat(i, ".");
          });
          return x.shape[i] - begin_[i];
        }
      });
      return [begin_, size_];
    }
    var Serializable = (
      /** @class */
      function() {
        function Serializable2() {
        }
        Serializable2.prototype.getClassName = function() {
          return this.constructor.className;
        };
        Serializable2.fromConfig = function(cls, config) {
          return new cls(config);
        };
        return Serializable2;
      }()
    );
    function abs_(x) {
      var $x = convertToTensor(x, "x", "abs");
      if ($x.dtype === "complex64") {
        var inputs = { x: $x };
        return ENGINE.runKernel(ComplexAbs, inputs);
      } else {
        var inputs = { x: $x };
        return ENGINE.runKernel(Abs, inputs);
      }
    }
    var abs = /* @__PURE__ */ op({ abs_ });
    function concat_(tensors, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      assert(tensors.length >= 1, function() {
        return "Pass at least one tensor to concat";
      });
      var $tensors = convertToTensorArray(tensors, "tensors", "concat", "string_or_numeric");
      if ($tensors[0].dtype === "complex64") {
        $tensors.forEach(function(tensor) {
          if (tensor.dtype !== "complex64") {
            throw new Error("Cannot concatenate complex64 tensors with a tensor\n          with dtype ".concat(tensor.dtype, ". "));
          }
        });
      }
      if ($tensors.length === 1) {
        return clone($tensors[0]);
      }
      var inputs = $tensors;
      var attr = { axis };
      return ENGINE.runKernel(Concat, inputs, attr);
    }
    var concat = /* @__PURE__ */ op({ concat_ });
    function sigmoid_(x) {
      var $x = convertToTensor(x, "x", "sigmoid", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Sigmoid$1, inputs);
    }
    var sigmoid = /* @__PURE__ */ op({ sigmoid_ });
    function batchToSpaceND_(x, blockShape, crops) {
      var $x = convertToTensor(x, "x", "batchToSpaceND");
      var prod = blockShape.reduce(function(a, b) {
        return a * b;
      });
      assert($x.rank >= 1 + blockShape.length, function() {
        return "input rank is ".concat($x.rank, " but should be > than blockShape.length ").concat(blockShape.length);
      });
      assert(crops.length === blockShape.length, function() {
        return "crops.length is ".concat(crops.length, " but should be equal to blockShape.length  ").concat(blockShape.length);
      });
      assert($x.shape[0] % prod === 0, function() {
        return "input tensor batch is ".concat($x.shape[0], " but is not divisible by the product of ") + "the elements of blockShape ".concat(blockShape.join(" * "), " === ").concat(prod);
      });
      var inputs = { x: $x };
      var attrs = { blockShape, crops };
      return ENGINE.runKernel(BatchToSpaceND, inputs, attrs);
    }
    var batchToSpaceND = /* @__PURE__ */ op({ batchToSpaceND_ });
    function fill(shape, value, dtype) {
      assertNonNegativeIntegerDimensions(shape);
      dtype = dtype || inferDtype(value);
      var attrs = { shape, value, dtype };
      return ENGINE.runKernel(Fill, {}, attrs);
    }
    function cos_(x) {
      var $x = convertToTensor(x, "x", "cos", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Cos, inputs);
    }
    var cos = /* @__PURE__ */ op({ cos_ });
    function cosh_(x) {
      var $x = convertToTensor(x, "x", "cosh", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Cosh, inputs);
    }
    var cosh = /* @__PURE__ */ op({ cosh_ });
    function cumprod_(x, axis, exclusive, reverse2) {
      if (axis === void 0) {
        axis = 0;
      }
      if (exclusive === void 0) {
        exclusive = false;
      }
      if (reverse2 === void 0) {
        reverse2 = false;
      }
      var $x = convertToTensor(x, "x", "cumprod");
      var inputs = { x: $x };
      var attrs = { axis, exclusive, reverse: reverse2 };
      return ENGINE.runKernel(Cumprod, inputs, attrs);
    }
    var cumprod = /* @__PURE__ */ op({ cumprod_ });
    function expandDims_(x, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $x = convertToTensor(x, "x", "expandDims", "string_or_numeric");
      assert(axis <= $x.rank, function() {
        return "Axis must be <= rank of the tensor";
      });
      var inputs = { input: $x };
      var attrs = { dim: axis };
      return ENGINE.runKernel(ExpandDims, inputs, attrs);
    }
    var expandDims = /* @__PURE__ */ op({ expandDims_ });
    function gather_(x, indices, axis, batchDims) {
      if (axis === void 0) {
        axis = 0;
      }
      if (batchDims === void 0) {
        batchDims = 0;
      }
      var $x = convertToTensor(x, "x", "gather");
      var $indices = convertToTensor(indices, "indices", "gather", "int32");
      var inputs = { x: $x, indices: $indices };
      var attrs = { axis, batchDims };
      return ENGINE.runKernel(GatherV2, inputs, attrs);
    }
    var gather = /* @__PURE__ */ op({ gather_ });
    function variableGrads(f, varList) {
      assert(isFunction(f), function() {
        return "The f passed in variableGrads(f) must be a function";
      });
      assert(varList == null || Array.isArray(varList) && varList.every(function(v) {
        return v instanceof Variable;
      }), function() {
        return "The varList passed in variableGrads(f, varList) must be an array of variables";
      });
      var specifiedVarList = varList != null;
      if (!specifiedVarList) {
        varList = [];
        for (var varName in ENGINE.registeredVariables) {
          varList.push(ENGINE.registeredVariables[varName]);
        }
      }
      var specifiedNonTrainable = specifiedVarList ? varList.filter(function(variable) {
        return !variable.trainable;
      }) : null;
      var originalVarCount = varList.length;
      varList = varList.filter(function(variable) {
        return variable.trainable;
      });
      assert(varList.length > 0, function() {
        return "variableGrads() expects at least one of the input variables to " + "be trainable, but none of the ".concat(originalVarCount, " variables is ") + "trainable.";
      });
      var allowNoGradients = true;
      var _a2 = ENGINE.gradients(f, varList, null, allowNoGradients), value = _a2.value, grads = _a2.grads;
      assert(grads.some(function(g) {
        return g != null;
      }), function() {
        return "Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize().";
      });
      assert(value.rank === 0, function() {
        return "The f passed in variableGrads(f) must return a scalar, but it " + "returned a rank-".concat(value.rank, " tensor");
      });
      var namedGrads = {};
      varList.forEach(function(v, i) {
        if (grads[i] != null) {
          namedGrads[v.name] = grads[i];
        }
      });
      if (specifiedNonTrainable != null) {
        specifiedNonTrainable.forEach(function(v) {
          return namedGrads[v.name] = null;
        });
      }
      return { value, grads: namedGrads };
    }
    function logicalNot_(x) {
      var $x = convertToTensor(x, "x", "logicalNot", "bool");
      var inputs = { x: $x };
      return ENGINE.runKernel(LogicalNot, inputs);
    }
    var logicalNot = /* @__PURE__ */ op({ logicalNot_ });
    function maximum_(a, b) {
      var _a2;
      var $a = convertToTensor(a, "a", "maximum");
      var $b = convertToTensor(b, "b", "maximum");
      _a2 = __read(makeTypesMatch($a, $b), 2), $a = _a2[0], $b = _a2[1];
      if ($a.dtype === "bool") {
        $a = cast($a, "int32");
        $b = cast($b, "int32");
      }
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Maximum$1, inputs);
    }
    var maximum$1 = /* @__PURE__ */ op({ maximum_ });
    function pad_(x, paddings, constantValue) {
      if (constantValue === void 0) {
        constantValue = 0;
      }
      var $x = convertToTensor(x, "x", "pad");
      if ($x.rank === 0) {
        throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");
      }
      var attrs = { paddings, constantValue };
      var inputs = { x: $x };
      return ENGINE.runKernel(PadV2, inputs, attrs);
    }
    var pad = /* @__PURE__ */ op({ pad_ });
    var alea$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function Alea(seed) {
          var me = this, mash = Mash();
          me.next = function() {
            var t = 2091639 * me.s0 + me.c * 23283064365386963e-26;
            me.s0 = me.s1;
            me.s1 = me.s2;
            return me.s2 = t - (me.c = t | 0);
          };
          me.c = 1;
          me.s0 = mash(" ");
          me.s1 = mash(" ");
          me.s2 = mash(" ");
          me.s0 -= mash(seed);
          if (me.s0 < 0) {
            me.s0 += 1;
          }
          me.s1 -= mash(seed);
          if (me.s1 < 0) {
            me.s1 += 1;
          }
          me.s2 -= mash(seed);
          if (me.s2 < 0) {
            me.s2 += 1;
          }
          mash = null;
        }
        function copy(f, t) {
          t.c = f.c;
          t.s0 = f.s0;
          t.s1 = f.s1;
          t.s2 = f.s2;
          return t;
        }
        function impl(seed, opts) {
          var xg = new Alea(seed), state = opts && opts.state, prng = xg.next;
          prng.int32 = function() {
            return xg.next() * 4294967296 | 0;
          };
          prng.double = function() {
            return prng() + (prng() * 2097152 | 0) * 11102230246251565e-32;
          };
          prng.quick = prng;
          if (state) {
            if (typeof state == "object")
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        function Mash() {
          var n = 4022871197;
          var mash = function(data) {
            data = String(data);
            for (var i = 0; i < data.length; i++) {
              n += data.charCodeAt(i);
              var h = 0.02519603282416938 * n;
              n = h >>> 0;
              h -= n;
              h *= n;
              n = h >>> 0;
              h -= n;
              n += h * 4294967296;
            }
            return (n >>> 0) * 23283064365386963e-26;
          };
          return mash;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.alea = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(alea$1);
    var aleaExports = alea$1.exports;
    var xor128$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this, strseed = "";
          me.x = 0;
          me.y = 0;
          me.z = 0;
          me.w = 0;
          me.next = function() {
            var t = me.x ^ me.x << 11;
            me.x = me.y;
            me.y = me.z;
            me.z = me.w;
            return me.w ^= me.w >>> 19 ^ t ^ t >>> 8;
          };
          if (seed === (seed | 0)) {
            me.x = seed;
          } else {
            strseed += seed;
          }
          for (var k = 0; k < strseed.length + 64; k++) {
            me.x ^= strseed.charCodeAt(k) | 0;
            me.next();
          }
        }
        function copy(f, t) {
          t.x = f.x;
          t.y = f.y;
          t.z = f.z;
          t.w = f.w;
          return t;
        }
        function impl(seed, opts) {
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (typeof state == "object")
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xor128 = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xor128$1);
    var xor128Exports = xor128$1.exports;
    var xorwow$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this, strseed = "";
          me.next = function() {
            var t = me.x ^ me.x >>> 2;
            me.x = me.y;
            me.y = me.z;
            me.z = me.w;
            me.w = me.v;
            return (me.d = me.d + 362437 | 0) + (me.v = me.v ^ me.v << 4 ^ (t ^ t << 1)) | 0;
          };
          me.x = 0;
          me.y = 0;
          me.z = 0;
          me.w = 0;
          me.v = 0;
          if (seed === (seed | 0)) {
            me.x = seed;
          } else {
            strseed += seed;
          }
          for (var k = 0; k < strseed.length + 64; k++) {
            me.x ^= strseed.charCodeAt(k) | 0;
            if (k == strseed.length) {
              me.d = me.x << 10 ^ me.x >>> 4;
            }
            me.next();
          }
        }
        function copy(f, t) {
          t.x = f.x;
          t.y = f.y;
          t.z = f.z;
          t.w = f.w;
          t.v = f.v;
          t.d = f.d;
          return t;
        }
        function impl(seed, opts) {
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (typeof state == "object")
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xorwow = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xorwow$1);
    var xorwowExports = xorwow$1.exports;
    var xorshift7$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this;
          me.next = function() {
            var X = me.x, i = me.i, t, v;
            t = X[i];
            t ^= t >>> 7;
            v = t ^ t << 24;
            t = X[i + 1 & 7];
            v ^= t ^ t >>> 10;
            t = X[i + 3 & 7];
            v ^= t ^ t >>> 3;
            t = X[i + 4 & 7];
            v ^= t ^ t << 7;
            t = X[i + 7 & 7];
            t = t ^ t << 13;
            v ^= t ^ t << 9;
            X[i] = v;
            me.i = i + 1 & 7;
            return v;
          };
          function init(me2, seed2) {
            var j, X = [];
            if (seed2 === (seed2 | 0)) {
              X[0] = seed2;
            } else {
              seed2 = "" + seed2;
              for (j = 0; j < seed2.length; ++j) {
                X[j & 7] = X[j & 7] << 15 ^ seed2.charCodeAt(j) + X[j + 1 & 7] << 13;
              }
            }
            while (X.length < 8)
              X.push(0);
            for (j = 0; j < 8 && X[j] === 0; ++j)
              ;
            if (j == 8)
              X[7] = -1;
            else
              X[j];
            me2.x = X;
            me2.i = 0;
            for (j = 256; j > 0; --j) {
              me2.next();
            }
          }
          init(me, seed);
        }
        function copy(f, t) {
          t.x = f.x.slice();
          t.i = f.i;
          return t;
        }
        function impl(seed, opts) {
          if (seed == null)
            seed = +/* @__PURE__ */ new Date();
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (state.x)
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xorshift7 = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xorshift7$1);
    var xorshift7Exports = xorshift7$1.exports;
    var xor4096$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this;
          me.next = function() {
            var w = me.w, X = me.X, i = me.i, t, v;
            me.w = w = w + 1640531527 | 0;
            v = X[i + 34 & 127];
            t = X[i = i + 1 & 127];
            v ^= v << 13;
            t ^= t << 17;
            v ^= v >>> 15;
            t ^= t >>> 12;
            v = X[i] = v ^ t;
            me.i = i;
            return v + (w ^ w >>> 16) | 0;
          };
          function init(me2, seed2) {
            var t, v, i, j, w, X = [], limit = 128;
            if (seed2 === (seed2 | 0)) {
              v = seed2;
              seed2 = null;
            } else {
              seed2 = seed2 + "\0";
              v = 0;
              limit = Math.max(limit, seed2.length);
            }
            for (i = 0, j = -32; j < limit; ++j) {
              if (seed2)
                v ^= seed2.charCodeAt((j + 32) % seed2.length);
              if (j === 0)
                w = v;
              v ^= v << 10;
              v ^= v >>> 15;
              v ^= v << 4;
              v ^= v >>> 13;
              if (j >= 0) {
                w = w + 1640531527 | 0;
                t = X[j & 127] ^= v + w;
                i = 0 == t ? i + 1 : 0;
              }
            }
            if (i >= 128) {
              X[(seed2 && seed2.length || 0) & 127] = -1;
            }
            i = 127;
            for (j = 4 * 128; j > 0; --j) {
              v = X[i + 34 & 127];
              t = X[i = i + 1 & 127];
              v ^= v << 13;
              t ^= t << 17;
              v ^= v >>> 15;
              t ^= t >>> 12;
              X[i] = v ^ t;
            }
            me2.w = w;
            me2.X = X;
            me2.i = i;
          }
          init(me, seed);
        }
        function copy(f, t) {
          t.i = f.i;
          t.w = f.w;
          t.X = f.X.slice();
          return t;
        }
        function impl(seed, opts) {
          if (seed == null)
            seed = +/* @__PURE__ */ new Date();
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (state.X)
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xor4096 = impl;
        }
      })(
        commonjsGlobal,
        // window object or global
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xor4096$1);
    var xor4096Exports = xor4096$1.exports;
    var tychei$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this, strseed = "";
          me.next = function() {
            var b = me.b, c = me.c, d = me.d, a = me.a;
            b = b << 25 ^ b >>> 7 ^ c;
            c = c - d | 0;
            d = d << 24 ^ d >>> 8 ^ a;
            a = a - b | 0;
            me.b = b = b << 20 ^ b >>> 12 ^ c;
            me.c = c = c - d | 0;
            me.d = d << 16 ^ c >>> 16 ^ a;
            return me.a = a - b | 0;
          };
          me.a = 0;
          me.b = 0;
          me.c = 2654435769 | 0;
          me.d = 1367130551;
          if (seed === Math.floor(seed)) {
            me.a = seed / 4294967296 | 0;
            me.b = seed | 0;
          } else {
            strseed += seed;
          }
          for (var k = 0; k < strseed.length + 20; k++) {
            me.b ^= strseed.charCodeAt(k) | 0;
            me.next();
          }
        }
        function copy(f, t) {
          t.a = f.a;
          t.b = f.b;
          t.c = f.c;
          t.d = f.d;
          return t;
        }
        function impl(seed, opts) {
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (typeof state == "object")
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.tychei = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(tychei$1);
    var tycheiExports = tychei$1.exports;
    var seedrandom = { exports: {} };
    var _nodeResolve_empty = {};
    var _nodeResolve_empty$1 = {
      __proto__: null,
      default: _nodeResolve_empty
    };
    var require$$0 = /* @__PURE__ */ getAugmentedNamespace(_nodeResolve_empty$1);
    (function(module3) {
      (function(global2, pool, math) {
        var width = 256, chunks = 6, digits = 52, rngname = "random", startdenom = math.pow(width, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask = width - 1, nodecrypto;
        function seedrandom2(seed, options, callback) {
          var key = [];
          options = options == true ? { entropy: true } : options || {};
          var shortseed = mixkey(flatten2(options.entropy ? [seed, tostring(pool)] : seed == null ? autoseed() : seed, 3), key);
          var arc4 = new ARC4(key);
          var prng = function() {
            var n = arc4.g(chunks), d = startdenom, x = 0;
            while (n < significance) {
              n = (n + x) * width;
              d *= width;
              x = arc4.g(1);
            }
            while (n >= overflow) {
              n /= 2;
              d /= 2;
              x >>>= 1;
            }
            return (n + x) / d;
          };
          prng.int32 = function() {
            return arc4.g(4) | 0;
          };
          prng.quick = function() {
            return arc4.g(4) / 4294967296;
          };
          prng.double = prng;
          mixkey(tostring(arc4.S), pool);
          return (options.pass || callback || function(prng2, seed2, is_math_call, state) {
            if (state) {
              if (state.S) {
                copy(state, arc4);
              }
              prng2.state = function() {
                return copy(arc4, {});
              };
            }
            if (is_math_call) {
              math[rngname] = prng2;
              return seed2;
            } else
              return prng2;
          })(prng, shortseed, "global" in options ? options.global : this == math, options.state);
        }
        function ARC4(key) {
          var t, keylen = key.length, me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
          if (!keylen) {
            key = [keylen++];
          }
          while (i < width) {
            s[i] = i++;
          }
          for (i = 0; i < width; i++) {
            s[i] = s[j = mask & j + key[i % keylen] + (t = s[i])];
            s[j] = t;
          }
          (me.g = function(count2) {
            var t2, r = 0, i2 = me.i, j2 = me.j, s2 = me.S;
            while (count2--) {
              t2 = s2[i2 = mask & i2 + 1];
              r = r * width + s2[mask & (s2[i2] = s2[j2 = mask & j2 + t2]) + (s2[j2] = t2)];
            }
            me.i = i2;
            me.j = j2;
            return r;
          })(width);
        }
        function copy(f, t) {
          t.i = f.i;
          t.j = f.j;
          t.S = f.S.slice();
          return t;
        }
        function flatten2(obj, depth) {
          var result = [], typ = typeof obj, prop;
          if (depth && typ == "object") {
            for (prop in obj) {
              try {
                result.push(flatten2(obj[prop], depth - 1));
              } catch (e) {
              }
            }
          }
          return result.length ? result : typ == "string" ? obj : obj + "\0";
        }
        function mixkey(seed, key) {
          var stringseed = seed + "", smear, j = 0;
          while (j < stringseed.length) {
            key[mask & j] = mask & (smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++);
          }
          return tostring(key);
        }
        function autoseed() {
          try {
            var out;
            if (nodecrypto && (out = nodecrypto.randomBytes)) {
              out = out(width);
            } else {
              out = new Uint8Array(width);
              (global2.crypto || global2.msCrypto).getRandomValues(out);
            }
            return tostring(out);
          } catch (e) {
            var browser = global2.navigator, plugins = browser && browser.plugins;
            return [+/* @__PURE__ */ new Date(), global2, plugins, global2.screen, tostring(pool)];
          }
        }
        function tostring(a) {
          return String.fromCharCode.apply(0, a);
        }
        mixkey(math.random(), pool);
        if (module3.exports) {
          module3.exports = seedrandom2;
          try {
            nodecrypto = require$$0;
          } catch (ex) {
          }
        } else {
          math["seed" + rngname] = seedrandom2;
        }
      })(
        // global: `self` in browsers (including strict mode and web workers),
        // otherwise `this` in Node and other environments
        typeof self !== "undefined" ? self : commonjsGlobal,
        [],
        // pool: entropy pool starts empty
        Math
        // math: package containing random, pow, and seedrandom
      );
    })(seedrandom);
    var seedrandomExports = seedrandom.exports;
    var alea = aleaExports;
    var xor128 = xor128Exports;
    var xorwow = xorwowExports;
    var xorshift7 = xorshift7Exports;
    var xor4096 = xor4096Exports;
    var tychei = tycheiExports;
    var sr = seedrandomExports;
    sr.alea = alea;
    sr.xor128 = xor128;
    sr.xorwow = xorwow;
    sr.xorshift7 = xorshift7;
    sr.xor4096 = xor4096;
    sr.tychei = tychei;
    function reverse_(x, axis) {
      var $x = convertToTensor(x, "x", "reverse");
      var inputs = { x: $x };
      var attrs = { dims: axis };
      return ENGINE.runKernel(Reverse, inputs, attrs);
    }
    var reverse = /* @__PURE__ */ op({ reverse_ });
    function tensorScatterUpdate_(tensor, indices, updates) {
      var $tensor = convertToTensor(tensor, "tensor", "tensorScatterupdate");
      var $indices = convertToTensor(indices, "indices", "tensorScatterupdate", "int32");
      var $updates = convertToTensor(updates, "updates", "tensorScatterupdate");
      validateInput($updates, $indices, $tensor.shape);
      if ($tensor.dtype !== $updates.dtype) {
        throw new Error("tensor and updates must have the same dtype, instead they are ".concat($tensor.dtype, " and ").concat($updates.dtype, "."));
      }
      var inputs = {
        tensor: $tensor,
        indices: $indices,
        updates: $updates
      };
      var attrs = {};
      return ENGINE.runKernel(TensorScatterUpdate, inputs, attrs);
    }
    op({ tensorScatterUpdate_ });
    var Reduction;
    (function(Reduction2) {
      Reduction2[Reduction2["NONE"] = 0] = "NONE";
      Reduction2[Reduction2["MEAN"] = 1] = "MEAN";
      Reduction2[Reduction2["SUM"] = 2] = "SUM";
      Reduction2[Reduction2["SUM_BY_NONZERO_WEIGHTS"] = 3] = "SUM_BY_NONZERO_WEIGHTS";
    })(Reduction || (Reduction = {}));
    var Optimizer = (
      /** @class */
      function(_super) {
        __extends(Optimizer2, _super);
        function Optimizer2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Optimizer2.prototype.minimize = function(f, returnCost, varList) {
          if (returnCost === void 0) {
            returnCost = false;
          }
          var _a2 = this.computeGradients(f, varList), value = _a2.value, grads = _a2.grads;
          if (varList != null) {
            var gradArray = varList.map(function(v) {
              return { name: v.name, tensor: grads[v.name] };
            });
            this.applyGradients(gradArray);
          } else {
            this.applyGradients(grads);
          }
          dispose(grads);
          if (returnCost) {
            return value;
          } else {
            value.dispose();
            return null;
          }
        };
        Object.defineProperty(Optimizer2.prototype, "iterations", {
          /**
           * The number of iterations that this optimizer instance has been invoked for.
           */
          get: function() {
            if (this.iterations_ == null) {
              this.iterations_ = 0;
            }
            return this.iterations_;
          },
          enumerable: false,
          configurable: true
        });
        Optimizer2.prototype.incrementIterations = function() {
          this.iterations_ = this.iterations + 1;
        };
        Optimizer2.prototype.computeGradients = function(f, varList) {
          return variableGrads(f, varList);
        };
        Optimizer2.prototype.dispose = function() {
          if (this.iterations_ != null) {
            dispose(this.iterations_);
          }
        };
        Optimizer2.prototype.saveIterations = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              if (this.iterations_ == null) {
                this.iterations_ = 0;
              }
              return [2, {
                name: "iter",
                // TODO(cais): Use 'int64' type when available.
                tensor: scalar(this.iterations_, "int32")
              }];
            });
          });
        };
        Optimizer2.prototype.getWeights = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              throw new Error("getWeights() is not implemented for this optimizer yet.");
            });
          });
        };
        Optimizer2.prototype.setWeights = function(weightValues) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              throw new Error("setWeights() is not implemented for this optimizer class " + "".concat(this.getClassName()));
            });
          });
        };
        Optimizer2.prototype.extractIterations = function(weightValues) {
          return __awaiter(this, void 0, void 0, function() {
            var _a2;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  _a2 = this;
                  return [4, weightValues[0].tensor.data()];
                case 1:
                  _a2.iterations_ = _b.sent()[0];
                  return [2, weightValues.slice(1)];
              }
            });
          });
        };
        return Optimizer2;
      }(Serializable)
    );
    Object.defineProperty(Optimizer, Symbol.hasInstance, {
      value: function(instance) {
        return instance.minimize != null && instance.computeGradients != null && instance.applyGradients != null;
      }
    });
    (function(_super) {
      __extends(AdadeltaOptimizer, _super);
      function AdadeltaOptimizer(learningRate, rho, epsilon2) {
        if (epsilon2 === void 0) {
          epsilon2 = null;
        }
        var _this = _super.call(this) || this;
        _this.learningRate = learningRate;
        _this.rho = rho;
        _this.epsilon = epsilon2;
        _this.accumulatedGrads = [];
        _this.accumulatedUpdates = [];
        if (epsilon2 == null) {
          _this.epsilon = ENGINE.backend.epsilon();
        }
        return _this;
      }
      Object.defineProperty(AdadeltaOptimizer, "className", {
        /** @nocollapse */
        get: function() {
          return "Adadelta";
        },
        enumerable: false,
        configurable: true
      });
      AdadeltaOptimizer.prototype.applyGradients = function(variableGradients) {
        var _this = this;
        var variableNames = Array.isArray(variableGradients) ? variableGradients.map(function(item) {
          return item.name;
        }) : Object.keys(variableGradients);
        variableNames.forEach(function(name, i) {
          var value = ENGINE.registeredVariables[name];
          var trainable = false;
          if (_this.accumulatedGrads[i] == null) {
            _this.accumulatedGrads[i] = {
              originalName: "".concat(name, "/accum_grad"),
              variable: tidy(function() {
                return zerosLike(value).variable(trainable);
              })
            };
          }
          if (_this.accumulatedUpdates[i] == null) {
            _this.accumulatedUpdates[i] = {
              originalName: "".concat(name, "/accum_var"),
              variable: tidy(function() {
                return zerosLike(value).variable(trainable);
              })
            };
          }
          var gradient = Array.isArray(variableGradients) ? variableGradients[i].tensor : variableGradients[name];
          if (gradient == null) {
            return;
          }
          var accumulatedGrad = _this.accumulatedGrads[i].variable;
          var accumulatedUpdate = _this.accumulatedUpdates[i].variable;
          tidy(function() {
            var newAccumulatedGrad = add$1(mul(accumulatedGrad, _this.rho), mul(square(gradient), 1 - _this.rho));
            var updates = mul(div(sqrt(add$1(accumulatedUpdate, _this.epsilon)), sqrt(add$1(accumulatedGrad, _this.epsilon))), gradient);
            var newAccumulatedUpdate = add$1(mul(accumulatedUpdate, _this.rho), mul(square(updates), 1 - _this.rho));
            accumulatedGrad.assign(newAccumulatedGrad);
            accumulatedUpdate.assign(newAccumulatedUpdate);
            var newValue = add$1(mul(updates, -_this.learningRate), value);
            value.assign(newValue);
          });
        });
        this.incrementIterations();
      };
      AdadeltaOptimizer.prototype.dispose = function() {
        if (this.accumulatedUpdates != null) {
          dispose(this.accumulatedGrads.map(function(v) {
            return v.variable;
          }));
          dispose(this.accumulatedUpdates.map(function(v) {
            return v.variable;
          }));
        }
      };
      AdadeltaOptimizer.prototype.getWeights = function() {
        return __awaiter(this, void 0, void 0, function() {
          var variables;
          return __generator(this, function(_a2) {
            switch (_a2.label) {
              case 0:
                variables = __spreadArray(__spreadArray([], __read(this.accumulatedGrads), false), __read(this.accumulatedUpdates), false);
                return [4, this.saveIterations()];
              case 1:
                return [2, [_a2.sent()].concat(variables.map(function(v) {
                  return { name: v.originalName, tensor: v.variable };
                }))];
            }
          });
        });
      };
      AdadeltaOptimizer.prototype.setWeights = function(weightValues) {
        return __awaiter(this, void 0, void 0, function() {
          var variableCount, trainable;
          return __generator(this, function(_a2) {
            switch (_a2.label) {
              case 0:
                return [4, this.extractIterations(weightValues)];
              case 1:
                weightValues = _a2.sent();
                variableCount = weightValues.length / 2;
                trainable = false;
                this.accumulatedGrads = weightValues.slice(0, variableCount).map(function(v) {
                  return {
                    originalName: v.name,
                    variable: v.tensor.variable(trainable)
                  };
                });
                this.accumulatedUpdates = weightValues.slice(variableCount, variableCount * 2).map(function(v) {
                  return {
                    originalName: v.name,
                    variable: v.tensor.variable(trainable)
                  };
                });
                return [
                  2
                  /*return*/
                ];
            }
          });
        });
      };
      AdadeltaOptimizer.prototype.getConfig = function() {
        return {
          "learningRate": this.learningRate,
          "rho": this.rho,
          "epsilon": this.epsilon
        };
      };
      AdadeltaOptimizer.fromConfig = function(cls, config) {
        return new cls(config["learningRate"], config["rho"], config["epsilon"]);
      };
      return AdadeltaOptimizer;
    })(Optimizer);
    (function(_super) {
      __extends(AdagradOptimizer, _super);
      function AdagradOptimizer(learningRate, initialAccumulatorValue) {
        if (initialAccumulatorValue === void 0) {
          initialAccumulatorValue = 0.1;
        }
        var _this = _super.call(this) || this;
        _this.learningRate = learningRate;
        _this.initialAccumulatorValue = initialAccumulatorValue;
        _this.accumulatedGrads = [];
        return _this;
      }
      Object.defineProperty(AdagradOptimizer, "className", {
        /** @nocollapse */
        get: function() {
          return "Adagrad";
        },
        enumerable: false,
        configurable: true
      });
      AdagradOptimizer.prototype.applyGradients = function(variableGradients) {
        var _this = this;
        var variableNames = Array.isArray(variableGradients) ? variableGradients.map(function(item) {
          return item.name;
        }) : Object.keys(variableGradients);
        variableNames.forEach(function(name, i) {
          var value = ENGINE.registeredVariables[name];
          if (_this.accumulatedGrads[i] == null) {
            var trainable_1 = false;
            _this.accumulatedGrads[i] = {
              originalName: "".concat(name, "/accumulator"),
              variable: tidy(function() {
                return fill(value.shape, _this.initialAccumulatorValue).variable(trainable_1);
              })
            };
          }
          var gradient = Array.isArray(variableGradients) ? variableGradients[i].tensor : variableGradients[name];
          if (gradient == null) {
            return;
          }
          var accumulatedGrad = _this.accumulatedGrads[i].variable;
          tidy(function() {
            var newAccumulatedGrad = add$1(accumulatedGrad, square(gradient));
            accumulatedGrad.assign(newAccumulatedGrad);
            var newValue = add$1(mul(div(gradient, sqrt(add$1(newAccumulatedGrad, ENGINE.backend.epsilon()))), -_this.learningRate), value);
            value.assign(newValue);
          });
        });
        this.incrementIterations();
      };
      AdagradOptimizer.prototype.dispose = function() {
        if (this.accumulatedGrads != null) {
          dispose(this.accumulatedGrads.map(function(v) {
            return v.variable;
          }));
        }
      };
      AdagradOptimizer.prototype.getWeights = function() {
        return __awaiter(this, void 0, void 0, function() {
          return __generator(this, function(_a2) {
            switch (_a2.label) {
              case 0:
                return [4, this.saveIterations()];
              case 1:
                return [2, [_a2.sent()].concat(this.accumulatedGrads.map(function(v) {
                  return { name: v.originalName, tensor: v.variable };
                }))];
            }
          });
        });
      };
      AdagradOptimizer.prototype.setWeights = function(weightValues) {
        return __awaiter(this, void 0, void 0, function() {
          var trainable;
          return __generator(this, function(_a2) {
            switch (_a2.label) {
              case 0:
                return [4, this.extractIterations(weightValues)];
              case 1:
                weightValues = _a2.sent();
                trainable = false;
                this.accumulatedGrads = weightValues.map(function(v) {
                  return { originalName: v.name, variable: v.tensor.variable(trainable) };
                });
                return [
                  2
                  /*return*/
                ];
            }
          });
        });
      };
      AdagradOptimizer.prototype.getConfig = function() {
        return {
          "learningRate": this.learningRate,
          "initialAccumulatorValue": this.initialAccumulatorValue
        };
      };
      AdagradOptimizer.fromConfig = function(cls, config) {
        return new cls(config["learningRate"], config["initialAccumulatorValue"]);
      };
      return AdagradOptimizer;
    })(Optimizer);
    (function(_super) {
      __extends(AdamOptimizer, _super);
      function AdamOptimizer(learningRate, beta1, beta2, epsilon2) {
        if (epsilon2 === void 0) {
          epsilon2 = null;
        }
        var _this = _super.call(this) || this;
        _this.learningRate = learningRate;
        _this.beta1 = beta1;
        _this.beta2 = beta2;
        _this.epsilon = epsilon2;
        _this.accumulatedFirstMoment = [];
        _this.accumulatedSecondMoment = [];
        tidy(function() {
          _this.accBeta1 = scalar(beta1).variable();
          _this.accBeta2 = scalar(beta2).variable();
        });
        if (epsilon2 == null) {
          _this.epsilon = ENGINE.backend.epsilon();
        }
        return _this;
      }
      Object.defineProperty(AdamOptimizer, "className", {
        /** @nocollapse */
        get: function() {
          return "Adam";
        },
        enumerable: false,
        configurable: true
      });
      AdamOptimizer.prototype.applyGradients = function(variableGradients) {
        var _this = this;
        var varNames = Array.isArray(variableGradients) ? variableGradients.map(function(v) {
          return v.name;
        }) : Object.keys(variableGradients);
        tidy(function() {
          var oneMinusAccBeta1 = sub(1, _this.accBeta1);
          var oneMinusAccBeta2 = sub(1, _this.accBeta2);
          varNames.forEach(function(name, i) {
            var value = ENGINE.registeredVariables[name];
            var trainable = false;
            if (_this.accumulatedFirstMoment[i] == null) {
              _this.accumulatedFirstMoment[i] = {
                originalName: "".concat(name, "/m"),
                variable: tidy(function() {
                  return zerosLike(value).variable(trainable);
                })
              };
            }
            if (_this.accumulatedSecondMoment[i] == null) {
              _this.accumulatedSecondMoment[i] = {
                originalName: "".concat(name, "/v"),
                variable: tidy(function() {
                  return zerosLike(value).variable(trainable);
                })
              };
            }
            var gradient = Array.isArray(variableGradients) ? variableGradients[i].tensor : variableGradients[name];
            if (gradient == null) {
              return;
            }
            var firstMoment = _this.accumulatedFirstMoment[i].variable;
            var secondMoment = _this.accumulatedSecondMoment[i].variable;
            var newFirstMoment = add$1(mul(firstMoment, _this.beta1), mul(gradient, 1 - _this.beta1));
            var newSecondMoment = add$1(mul(secondMoment, _this.beta2), mul(square(gradient), 1 - _this.beta2));
            var biasCorrectedFirstMoment = div(newFirstMoment, oneMinusAccBeta1);
            var biasCorrectedSecondMoment = div(newSecondMoment, oneMinusAccBeta2);
            firstMoment.assign(newFirstMoment);
            secondMoment.assign(newSecondMoment);
            var newValue = add$1(mul(div(biasCorrectedFirstMoment, add$1(sqrt(biasCorrectedSecondMoment), _this.epsilon)), -_this.learningRate), value);
            value.assign(newValue);
          });
          _this.accBeta1.assign(mul(_this.accBeta1, _this.beta1));
          _this.accBeta2.assign(mul(_this.accBeta2, _this.beta2));
        });
        this.incrementIterations();
      };
      AdamOptimizer.prototype.dispose = function() {
        this.accBeta1.dispose();
        this.accBeta2.dispose();
        if (this.accumulatedFirstMoment != null) {
          dispose(this.accumulatedFirstMoment.map(function(v) {
            return v.variable;
          }));
        }
        if (this.accumulatedSecondMoment != null) {
          dispose(this.accumulatedSecondMoment.map(function(v) {
            return v.variable;
          }));
        }
      };
      AdamOptimizer.prototype.getWeights = function() {
        return __awaiter(this, void 0, void 0, function() {
          var variables;
          return __generator(this, function(_a2) {
            switch (_a2.label) {
              case 0:
                variables = __spreadArray(__spreadArray([], __read(this.accumulatedFirstMoment), false), __read(this.accumulatedSecondMoment), false);
                return [4, this.saveIterations()];
              case 1:
                return [2, [_a2.sent()].concat(variables.map(function(v) {
                  return { name: v.originalName, tensor: v.variable };
                }))];
            }
          });
        });
      };
      AdamOptimizer.prototype.setWeights = function(weightValues) {
        return __awaiter(this, void 0, void 0, function() {
          var variableCount, trainable;
          var _this = this;
          return __generator(this, function(_a2) {
            switch (_a2.label) {
              case 0:
                return [4, this.extractIterations(weightValues)];
              case 1:
                weightValues = _a2.sent();
                tidy(function() {
                  _this.accBeta1.assign(pow(_this.beta1, _this.iterations_ + 1));
                  _this.accBeta2.assign(pow(_this.beta2, _this.iterations_ + 1));
                });
                variableCount = weightValues.length / 2;
                trainable = false;
                this.accumulatedFirstMoment = weightValues.slice(0, variableCount).map(function(v) {
                  return {
                    originalName: v.name,
                    variable: v.tensor.variable(trainable)
                  };
                });
                this.accumulatedSecondMoment = weightValues.slice(variableCount, variableCount * 2).map(function(v) {
                  return {
                    originalName: v.name,
                    variable: v.tensor.variable(trainable)
                  };
                });
                return [
                  2
                  /*return*/
                ];
            }
          });
        });
      };
      AdamOptimizer.prototype.getConfig = function() {
        return {
          "learningRate": this.learningRate,
          "beta1": this.beta1,
          "beta2": this.beta2,
          "epsilon": this.epsilon
        };
      };
      AdamOptimizer.fromConfig = function(cls, config) {
        return new cls(config["learningRate"], config["beta1"], config["beta2"], config["epsilon"]);
      };
      return AdamOptimizer;
    })(Optimizer);
    (function(_super) {
      __extends(AdamaxOptimizer, _super);
      function AdamaxOptimizer(learningRate, beta1, beta2, epsilon2, decay) {
        if (epsilon2 === void 0) {
          epsilon2 = null;
        }
        if (decay === void 0) {
          decay = 0;
        }
        var _this = _super.call(this) || this;
        _this.learningRate = learningRate;
        _this.beta1 = beta1;
        _this.beta2 = beta2;
        _this.epsilon = epsilon2;
        _this.decay = decay;
        _this.accumulatedFirstMoment = [];
        _this.accumulatedWeightedInfNorm = [];
        tidy(function() {
          _this.iteration = scalar(0).variable();
          _this.accBeta1 = scalar(beta1).variable();
        });
        if (epsilon2 == null) {
          _this.epsilon = ENGINE.backend.epsilon();
        }
        return _this;
      }
      Object.defineProperty(AdamaxOptimizer, "className", {
        /** @nocollapse */
        get: function() {
          return "Adamax";
        },
        enumerable: false,
        configurable: true
      });
      AdamaxOptimizer.prototype.applyGradients = function(variableGradients) {
        var _this = this;
        var variableNames = Array.isArray(variableGradients) ? variableGradients.map(function(item) {
          return item.name;
        }) : Object.keys(variableGradients);
        tidy(function() {
          var oneMinusAccBeta1 = sub(1, _this.accBeta1);
          var lr = div(-_this.learningRate, add$1(mul(_this.iteration, _this.decay), 1));
          variableNames.forEach(function(name, i) {
            var value = ENGINE.registeredVariables[name];
            var trainable = false;
            if (_this.accumulatedFirstMoment[i] == null) {
              _this.accumulatedFirstMoment[i] = {
                originalName: "".concat(name, "/m"),
                variable: zerosLike(value).variable(trainable)
              };
            }
            if (_this.accumulatedWeightedInfNorm[i] == null) {
              _this.accumulatedWeightedInfNorm[i] = {
                originalName: "".concat(name, "/v"),
                variable: zerosLike(value).variable(trainable)
              };
            }
            var gradient = Array.isArray(variableGradients) ? variableGradients[i].tensor : variableGradients[name];
            if (gradient == null) {
              return;
            }
            var firstMoment = _this.accumulatedFirstMoment[i].variable;
            var weightedInfNorm = _this.accumulatedWeightedInfNorm[i].variable;
            var newFirstMoment = add$1(mul(firstMoment, _this.beta1), mul(gradient, 1 - _this.beta1));
            var ut0 = mul(weightedInfNorm, _this.beta2);
            var ut1 = abs(gradient);
            var newWeightedInfNorm = maximum$1(ut0, ut1);
            firstMoment.assign(newFirstMoment);
            weightedInfNorm.assign(newWeightedInfNorm);
            var newValue = add$1(mul(div(lr, oneMinusAccBeta1), div(newFirstMoment, add$1(newWeightedInfNorm, _this.epsilon))), value);
            value.assign(newValue);
          });
          _this.iteration.assign(add$1(_this.iteration, 1));
          _this.accBeta1.assign(mul(_this.accBeta1, _this.beta1));
        });
        this.incrementIterations();
      };
      AdamaxOptimizer.prototype.dispose = function() {
        this.accBeta1.dispose();
        this.iteration.dispose();
        if (this.accumulatedFirstMoment != null) {
          dispose(this.accumulatedFirstMoment.map(function(v) {
            return v.variable;
          }));
        }
        if (this.accumulatedWeightedInfNorm != null) {
          dispose(this.accumulatedWeightedInfNorm.map(function(v) {
            return v.variable;
          }));
        }
      };
      AdamaxOptimizer.prototype.getWeights = function() {
        return __awaiter(this, void 0, void 0, function() {
          return __generator(this, function(_a2) {
            throw new Error("getWeights() is not implemented for Adamax yet.");
          });
        });
      };
      AdamaxOptimizer.prototype.setWeights = function(weightValues) {
        return __awaiter(this, void 0, void 0, function() {
          return __generator(this, function(_a2) {
            throw new Error("setWeights() is not implemented for Adamax yet.");
          });
        });
      };
      AdamaxOptimizer.prototype.getConfig = function() {
        return {
          "learningRate": this.learningRate,
          "beta1": this.beta1,
          "beta2": this.beta2,
          "epsilon": this.epsilon,
          "decay": this.decay
        };
      };
      AdamaxOptimizer.fromConfig = function(cls, config) {
        return new cls(config["learningRate"], config["beta1"], config["beta2"], config["epsilon"], config["decay"]);
      };
      return AdamaxOptimizer;
    })(Optimizer);
    var SGDOptimizer = (
      /** @class */
      function(_super) {
        __extends(SGDOptimizer2, _super);
        function SGDOptimizer2(learningRate) {
          var _this = _super.call(this) || this;
          _this.learningRate = learningRate;
          _this.setLearningRate(learningRate);
          return _this;
        }
        Object.defineProperty(SGDOptimizer2, "className", {
          /** @nocollapse */
          get: function() {
            return "SGD";
          },
          enumerable: false,
          configurable: true
        });
        SGDOptimizer2.prototype.applyGradients = function(variableGradients) {
          var _this = this;
          var varNames = Array.isArray(variableGradients) ? variableGradients.map(function(v) {
            return v.name;
          }) : Object.keys(variableGradients);
          varNames.forEach(function(name, i) {
            var gradient = Array.isArray(variableGradients) ? variableGradients[i].tensor : variableGradients[name];
            if (gradient == null) {
              return;
            }
            var value = ENGINE.registeredVariables[name];
            tidy(function() {
              var newValue = add$1(mul(_this.c, gradient), value);
              value.assign(newValue);
            });
          });
          this.incrementIterations();
        };
        SGDOptimizer2.prototype.setLearningRate = function(learningRate) {
          this.learningRate = learningRate;
          if (this.c != null) {
            this.c.dispose();
          }
          this.c = keep(scalar(-learningRate));
        };
        SGDOptimizer2.prototype.dispose = function() {
          this.c.dispose();
        };
        SGDOptimizer2.prototype.getWeights = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  return [4, this.saveIterations()];
                case 1:
                  return [2, [_a2.sent()]];
              }
            });
          });
        };
        SGDOptimizer2.prototype.setWeights = function(weightValues) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  return [4, this.extractIterations(weightValues)];
                case 1:
                  weightValues = _a2.sent();
                  if (weightValues.length !== 0) {
                    throw new Error("SGD optimizer does not have settable weights.");
                  }
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        SGDOptimizer2.prototype.getConfig = function() {
          return { "learningRate": this.learningRate };
        };
        SGDOptimizer2.fromConfig = function(cls, config) {
          return new cls(config["learningRate"]);
        };
        return SGDOptimizer2;
      }(Optimizer)
    );
    (function(_super) {
      __extends(MomentumOptimizer, _super);
      function MomentumOptimizer(learningRate, momentum, useNesterov) {
        if (useNesterov === void 0) {
          useNesterov = false;
        }
        var _this = _super.call(this, learningRate) || this;
        _this.learningRate = learningRate;
        _this.momentum = momentum;
        _this.useNesterov = useNesterov;
        _this.accumulations = [];
        _this.m = scalar(_this.momentum);
        return _this;
      }
      Object.defineProperty(MomentumOptimizer, "className", {
        /** @nocollapse */
        // Name matters for Python compatibility.
        get: function() {
          return "Momentum";
        },
        enumerable: false,
        configurable: true
      });
      MomentumOptimizer.prototype.applyGradients = function(variableGradients) {
        var _this = this;
        var variableNames = Array.isArray(variableGradients) ? variableGradients.map(function(item) {
          return item.name;
        }) : Object.keys(variableGradients);
        variableNames.forEach(function(name, i) {
          var value = ENGINE.registeredVariables[name];
          if (_this.accumulations[i] == null) {
            var trainable_1 = false;
            _this.accumulations[i] = {
              originalName: "".concat(name, "/momentum"),
              variable: tidy(function() {
                return zerosLike(value).variable(trainable_1);
              })
            };
          }
          var accumulation = _this.accumulations[i].variable;
          var gradient = Array.isArray(variableGradients) ? variableGradients[i].tensor : variableGradients[name];
          if (gradient == null) {
            return;
          }
          tidy(function() {
            var newValue;
            var newAccumulation = add$1(mul(_this.m, accumulation), gradient);
            if (_this.useNesterov) {
              newValue = add$1(mul(_this.c, add$1(gradient, mul(newAccumulation, _this.m))), value);
            } else {
              newValue = add$1(mul(_this.c, newAccumulation), value);
            }
            accumulation.assign(newAccumulation);
            value.assign(newValue);
          });
        });
        this.incrementIterations();
      };
      MomentumOptimizer.prototype.dispose = function() {
        this.m.dispose();
        if (this.accumulations != null) {
          dispose(this.accumulations.map(function(v) {
            return v.variable;
          }));
        }
      };
      MomentumOptimizer.prototype.setMomentum = function(momentum) {
        this.momentum = momentum;
      };
      MomentumOptimizer.prototype.getWeights = function() {
        return __awaiter(this, void 0, void 0, function() {
          return __generator(this, function(_a2) {
            switch (_a2.label) {
              case 0:
                return [4, this.saveIterations()];
              case 1:
                return [2, [_a2.sent()].concat(this.accumulations.map(function(v) {
                  return { name: v.originalName, tensor: v.variable };
                }))];
            }
          });
        });
      };
      MomentumOptimizer.prototype.setWeights = function(weightValues) {
        return __awaiter(this, void 0, void 0, function() {
          var trainable;
          return __generator(this, function(_a2) {
            switch (_a2.label) {
              case 0:
                return [4, this.extractIterations(weightValues)];
              case 1:
                weightValues = _a2.sent();
                trainable = false;
                this.accumulations = weightValues.map(function(v) {
                  return { originalName: v.name, variable: v.tensor.variable(trainable) };
                });
                return [
                  2
                  /*return*/
                ];
            }
          });
        });
      };
      MomentumOptimizer.prototype.getConfig = function() {
        return {
          "learningRate": this.learningRate,
          "momentum": this.momentum,
          "useNesterov": this.useNesterov
        };
      };
      MomentumOptimizer.fromConfig = function(cls, config) {
        return new cls(config["learningRate"], config["momentum"], config["useNesterov"]);
      };
      return MomentumOptimizer;
    })(SGDOptimizer);
    (function(_super) {
      __extends(RMSPropOptimizer, _super);
      function RMSPropOptimizer(learningRate, decay, momentum, epsilon2, centered) {
        if (decay === void 0) {
          decay = 0.9;
        }
        if (momentum === void 0) {
          momentum = 0;
        }
        if (epsilon2 === void 0) {
          epsilon2 = null;
        }
        if (centered === void 0) {
          centered = false;
        }
        var _this = _super.call(this) || this;
        _this.learningRate = learningRate;
        _this.decay = decay;
        _this.momentum = momentum;
        _this.epsilon = epsilon2;
        _this.accumulatedMeanSquares = [];
        _this.accumulatedMoments = [];
        _this.accumulatedMeanGrads = [];
        _this.centered = centered;
        if (epsilon2 == null) {
          _this.epsilon = ENGINE.backend.epsilon();
        }
        if (learningRate == null) {
          throw new Error("learningRate for RMSPropOptimizer must be defined.");
        }
        return _this;
      }
      Object.defineProperty(RMSPropOptimizer, "className", {
        /** @nocollapse */
        get: function() {
          return "RMSProp";
        },
        enumerable: false,
        configurable: true
      });
      RMSPropOptimizer.prototype.applyGradients = function(variableGradients) {
        var _this = this;
        var variableNames = Array.isArray(variableGradients) ? variableGradients.map(function(item) {
          return item.name;
        }) : Object.keys(variableGradients);
        variableNames.forEach(function(name, i) {
          var value = ENGINE.registeredVariables[name];
          var trainable = false;
          if (_this.accumulatedMeanSquares[i] == null) {
            _this.accumulatedMeanSquares[i] = {
              originalName: "".concat(name, "/rms"),
              variable: tidy(function() {
                return zerosLike(value).variable(trainable);
              })
            };
          }
          if (_this.accumulatedMoments[i] == null) {
            _this.accumulatedMoments[i] = {
              originalName: "".concat(name, "/momentum"),
              variable: tidy(function() {
                return zerosLike(value).variable(trainable);
              })
            };
          }
          if (_this.accumulatedMeanGrads[i] == null && _this.centered) {
            _this.accumulatedMeanGrads[i] = {
              originalName: "".concat(name, "/mg"),
              variable: tidy(function() {
                return zerosLike(value).variable(trainable);
              })
            };
          }
          var gradient = Array.isArray(variableGradients) ? variableGradients[i].tensor : variableGradients[name];
          if (gradient == null) {
            return;
          }
          var accumulatedMeanSquare = _this.accumulatedMeanSquares[i].variable;
          var accumulatedMoments = _this.accumulatedMoments[i].variable;
          tidy(function() {
            var newAccumulatedMeanSquare = add$1(mul(accumulatedMeanSquare, _this.decay), mul(square(gradient), 1 - _this.decay));
            if (_this.centered) {
              var accumulatedMeanGrad = _this.accumulatedMeanGrads[i].variable;
              var newAccumulatedMeanGrad = add$1(mul(accumulatedMeanGrad, _this.decay), mul(gradient, 1 - _this.decay));
              var gradContribution = div(mul(gradient, _this.learningRate), sqrt(sub(newAccumulatedMeanSquare, add$1(square(newAccumulatedMeanGrad), _this.epsilon))));
              var newAccumulatedMoments = add$1(mul(accumulatedMoments, _this.momentum), gradContribution);
              accumulatedMeanSquare.assign(newAccumulatedMeanSquare);
              accumulatedMeanGrad.assign(newAccumulatedMeanGrad);
              accumulatedMoments.assign(newAccumulatedMoments);
              var newValue = sub(value, newAccumulatedMoments);
              value.assign(newValue);
            } else {
              var newAccumulatedMeanSquare_1 = add$1(mul(accumulatedMeanSquare, _this.decay), mul(square(gradient), 1 - _this.decay));
              var newAccumulatedMoments = add$1(mul(accumulatedMoments, _this.momentum), div(mul(gradient, _this.learningRate), sqrt(add$1(newAccumulatedMeanSquare_1, _this.epsilon))));
              accumulatedMeanSquare.assign(newAccumulatedMeanSquare_1);
              accumulatedMoments.assign(newAccumulatedMoments);
              var newValue = sub(value, newAccumulatedMoments);
              value.assign(newValue);
            }
          });
        });
        this.incrementIterations();
      };
      RMSPropOptimizer.prototype.dispose = function() {
        if (this.accumulatedMeanSquares != null) {
          dispose(this.accumulatedMeanSquares.map(function(v) {
            return v.variable;
          }));
        }
        if (this.accumulatedMeanGrads != null && this.centered) {
          dispose(this.accumulatedMeanGrads.map(function(v) {
            return v.variable;
          }));
        }
        if (this.accumulatedMoments != null) {
          dispose(this.accumulatedMoments.map(function(v) {
            return v.variable;
          }));
        }
      };
      RMSPropOptimizer.prototype.getWeights = function() {
        return __awaiter(this, void 0, void 0, function() {
          var variables;
          return __generator(this, function(_a2) {
            switch (_a2.label) {
              case 0:
                variables = __spreadArray(__spreadArray([], __read(this.accumulatedMeanSquares), false), __read(this.accumulatedMoments), false);
                if (this.centered) {
                  variables.push.apply(variables, __spreadArray([], __read(this.accumulatedMeanGrads), false));
                }
                return [4, this.saveIterations()];
              case 1:
                return [2, [_a2.sent()].concat(variables.map(function(v) {
                  return { name: v.originalName, tensor: v.variable };
                }))];
            }
          });
        });
      };
      RMSPropOptimizer.prototype.setWeights = function(weightValues) {
        return __awaiter(this, void 0, void 0, function() {
          var variableCount, trainable;
          return __generator(this, function(_a2) {
            switch (_a2.label) {
              case 0:
                return [4, this.extractIterations(weightValues)];
              case 1:
                weightValues = _a2.sent();
                variableCount = this.centered ? weightValues.length / 3 : weightValues.length / 2;
                trainable = false;
                this.accumulatedMeanSquares = weightValues.slice(0, variableCount).map(function(v) {
                  return {
                    originalName: v.name,
                    variable: v.tensor.variable(trainable)
                  };
                });
                this.accumulatedMoments = weightValues.slice(variableCount, variableCount * 2).map(function(v) {
                  return {
                    originalName: v.name,
                    variable: v.tensor.variable(trainable)
                  };
                });
                if (this.centered) {
                  this.accumulatedMeanGrads = weightValues.slice(variableCount * 2, variableCount * 3).map(function(v) {
                    return {
                      originalName: v.name,
                      variable: v.tensor.variable(trainable)
                    };
                  });
                }
                return [
                  2
                  /*return*/
                ];
            }
          });
        });
      };
      RMSPropOptimizer.prototype.getConfig = function() {
        return {
          "learningRate": this.learningRate,
          "decay": this.decay,
          "momentum": this.momentum,
          "epsilon": this.epsilon,
          "centered": this.centered
        };
      };
      RMSPropOptimizer.fromConfig = function(cls, config) {
        return new cls(config["learningRate"], config["decay"], config["momentum"], config["epsilon"], config["centered"]);
      };
      return RMSPropOptimizer;
    })(Optimizer);
    (function() {
      if (typeof requestAnimationFrame !== "undefined") {
        return requestAnimationFrame;
      } else if (typeof setImmediate !== "undefined") {
        return setImmediate;
      }
      return function(f) {
        return f();
      };
    })();
    var RowPartitionType;
    (function(RowPartitionType2) {
      RowPartitionType2[RowPartitionType2["FIRST_DIM_SIZE"] = 0] = "FIRST_DIM_SIZE";
      RowPartitionType2[RowPartitionType2["VALUE_ROWIDS"] = 1] = "VALUE_ROWIDS";
      RowPartitionType2[RowPartitionType2["ROW_LENGTHS"] = 2] = "ROW_LENGTHS";
      RowPartitionType2[RowPartitionType2["ROW_SPLITS"] = 3] = "ROW_SPLITS";
      RowPartitionType2[RowPartitionType2["ROW_LIMITS"] = 4] = "ROW_LIMITS";
      RowPartitionType2[RowPartitionType2["ROW_STARTS"] = 5] = "ROW_STARTS";
    })(RowPartitionType || (RowPartitionType = {}));
    var SELU_SCALEALPHA = 1.7580993408473768;
    var SELU_SCALE = 1.0507009873554805;
    function prodGradFn_(x, dy, axis) {
      var expandedYShape = x.shape.slice();
      expandedYShape[axis] = 1;
      var expandedDy = reshape$1(dy, expandedYShape);
      var xCumProd = cumprod(x, axis, true, false);
      var xCumRevProd = cumprod(x, axis, true, true);
      var dx = mul(xCumProd, xCumRevProd);
      return mul(expandedDy, dx);
    }
    function prodsGradFn_(x, dy, axis) {
      var xRank = x.shape.length;
      var finalProdAxis = xRank - axis.length;
      var xPermutation = getAxesPermutation(axis, xRank);
      var permutedX = x;
      if (xPermutation != null) {
        permutedX = transpose(x, xPermutation);
      }
      var newShape = permutedX.shape.slice();
      var removedShape = newShape.splice(xRank - axis.length, axis.length);
      var endPartShape = removedShape.reduce(function(p, c) {
        return p * c;
      }, 1);
      newShape.push(endPartShape);
      var reshapedPermutedX = permutedX.reshape(newShape);
      var prodGrad = prodGradFn_(reshapedPermutedX, dy, finalProdAxis);
      prodGrad = prodGrad.reshape(permutedX.shape);
      if (xPermutation != null) {
        var undoPermutation = getUndoAxesPermutation(xPermutation);
        prodGrad = transpose(prodGrad, undoPermutation);
      }
      return prodGrad;
    }
    var prodGradConfig = {
      kernelName: Prod,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 1), x = _a2[0];
        var axis = attrs.axis;
        var axisArr = [];
        if (axis === void 0 || axis === null) {
          axisArr = x.shape.map(function(_, i) {
            return i;
          });
        } else if (typeof axis === "number") {
          axisArr = [axis];
        } else {
          axisArr = axis;
        }
        return { x: function() {
          return prodsGradFn_(x, dy, axisArr);
        } };
      }
    };
    var divGradConfig = {
      kernelName: RealDiv,
      inputsToSave: ["a", "b"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 2), a = _a2[0], b = _a2[1];
        var outShape = assertAndGetBroadcastShape(a.shape, b.shape);
        var derA = function() {
          var res = div(dy, cast(b, "float32"));
          var reduceAxes = getReductionAxes(a.shape, outShape);
          if (reduceAxes.length > 0) {
            return reshape$1(sum(res, reduceAxes), a.shape);
          }
          return res;
        };
        var derB = function() {
          var res = mul(dy, cast(a, "float32"));
          var reduceAxes = getReductionAxes(b.shape, outShape);
          if (reduceAxes.length > 0) {
            res = reshape$1(sum(res, reduceAxes), b.shape);
          }
          var tmp = square(b);
          return neg(div(res, cast(tmp, "float32")));
        };
        return { a: derA, b: derB };
      }
    };
    var reciprocalGradConfig = {
      kernelName: Reciprocal,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return div(dy, neg(square(x)));
        } };
      }
    };
    var relu6GradConfig = {
      kernelName: Relu6$1,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        var mask = mul(lessEqual(x, 6), step(x));
        return { x: function() {
          return mul(dy, cast(mask, "float32"));
        } };
      }
    };
    var reluGradConfig = {
      kernelName: Relu$1,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return mul(dy, cast(step(x), "float32"));
        } };
      }
    };
    var reshapeGradConfig = {
      kernelName: Reshape$1,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return reshape$1(dy, x.shape);
        } };
      }
    };
    var resizeBilinearGradConfig = {
      kernelName: ResizeBilinear,
      inputsToSave: ["images"],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 1), images = _a2[0];
        var inputs = { dy, images };
        var imagesDer = function() {
          return ENGINE.runKernel(ResizeBilinearGrad, inputs, attrs);
        };
        return { images: imagesDer };
      }
    };
    var resizeNearestNeighborGradConfig = {
      kernelName: ResizeNearestNeighbor,
      inputsToSave: ["images"],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 1), images = _a2[0];
        var inputs = { dy, images };
        var imagesDer = function() {
          return ENGINE.runKernel(ResizeNearestNeighborGrad, inputs, attrs);
        };
        return { images: imagesDer };
      }
    };
    var reverseGradConfig = {
      kernelName: Reverse,
      gradFunc: function(dy, saved, attrs) {
        var dims = attrs.dims;
        var axes = parseAxisParam(dims, dy.shape);
        return { x: function() {
          return reverse(dy, axes);
        } };
      }
    };
    var roundGradConfig = {
      kernelName: Round,
      gradFunc: function(dy) {
        return { x: function() {
          return zerosLike(dy);
        } };
      }
    };
    var rsqrtGradConfig = {
      kernelName: Rsqrt,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return neg(div(dy, mul(pow(x, 1.5), 2)));
        } };
      }
    };
    var selectGradConfig = {
      kernelName: Select,
      inputsToSave: ["condition"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), condition = _a2[0];
        return {
          // TODO(julianoks): Return null for condition gradient
          // when backprop supports it.
          condition: function() {
            return cast(zerosLike(condition), "float32");
          },
          t: function() {
            return mul(dy, cast(condition, dy.dtype));
          },
          e: function() {
            return mul(dy, cast(logicalNot(condition), dy.dtype));
          }
        };
      }
    };
    var seluGradConfig = {
      kernelName: Selu$1,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return {
          x: function() {
            var mask = greater$1(x, scalar(0));
            var scaleAlpha = scalar(SELU_SCALEALPHA);
            var scale = scalar(SELU_SCALE);
            var greaterThanZeroDer = mul(dy, scale);
            var lessEqualZeroDer = mul(mul(dy, scaleAlpha), exp(cast(x, "float32")));
            return where(mask, greaterThanZeroDer, lessEqualZeroDer);
          }
        };
      }
    };
    var sigmoidGradConfig = {
      kernelName: Sigmoid$1,
      outputsToSave: [true],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), y = _a2[0];
        return { x: function() {
          return mul(dy, mul(y, sub(scalar(1), y)));
        } };
      }
    };
    var signGradConfig = {
      kernelName: Sign,
      gradFunc: function(dy) {
        return { x: function() {
          return zerosLike(dy);
        } };
      }
    };
    var sinGradConfig = {
      kernelName: Sin,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return mul(cos(cast(x, "float32")), dy);
        } };
      }
    };
    var sinhGradConfig = {
      kernelName: Sinh,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return mul(cosh(cast(x, "float32")), dy);
        } };
      }
    };
    var sliceGradConfig = {
      kernelName: Slice,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 1), x = _a2[0];
        var begin = attrs.begin, size = attrs.size;
        var inputShape = x.shape;
        var _b = __read(parseSliceParams(x, begin, size), 2), begin_ = _b[0], size_ = _b[1];
        var paddings = [];
        for (var i = 0; i < dy.rank; i++) {
          paddings.push([begin_[i], inputShape[i] - begin_[i] - size_[i]]);
        }
        return { x: function() {
          return pad(dy, paddings);
        } };
      }
    };
    var softmaxGradConfig = {
      kernelName: Softmax$2,
      outputsToSave: [true],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 1), y = _a2[0];
        var dim = attrs.dim;
        var keepDims = true;
        var dyTimesY = mul(dy, y);
        return {
          logits: function() {
            return sub(dyTimesY, mul(sum(dyTimesY, [dim], keepDims), y));
          }
        };
      }
    };
    var softplusGradConfig = {
      kernelName: Softplus$1,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return mul(dy, sigmoid(x));
        } };
      }
    };
    var spaceToBatchNDGradConfig = {
      kernelName: SpaceToBatchND,
      gradFunc: function(dy, saved, attrs) {
        var blockShape = attrs.blockShape, paddings = attrs.paddings;
        return { x: function() {
          return batchToSpaceND(dy, blockShape, paddings);
        } };
      }
    };
    var splitVGradConfig = {
      kernelName: SplitV,
      gradFunc: function(dy, saved, attrs) {
        var axis = attrs.axis;
        return { x: function() {
          return concat(dy, axis);
        } };
      }
    };
    var sqrtGradConfig = {
      kernelName: Sqrt,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return div(dy, mul(sqrt(cast(x, "float32")), 2));
        } };
      }
    };
    var squareGradConfig = {
      kernelName: Square,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return mul(dy, mul(cast(x, "float32"), 2));
        } };
      }
    };
    var squaredDifferenceGradConfig = {
      kernelName: SquaredDifference,
      inputsToSave: ["a", "b"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 2), a = _a2[0], b = _a2[1];
        var two = scalar(2);
        var derA = function() {
          return mul(dy, mul(two, sub(a, b)));
        };
        var derB = function() {
          return mul(dy, mul(two, sub(b, a)));
        };
        return { a: derA, b: derB };
      }
    };
    var stepGradConfig = {
      kernelName: Step,
      gradFunc: function(dy) {
        return { x: function() {
          return zerosLike(dy);
        } };
      }
    };
    var subGradConfig = {
      kernelName: Sub,
      inputsToSave: ["a", "b"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 2), a = _a2[0], b = _a2[1];
        var outShape = assertAndGetBroadcastShape(a.shape, b.shape);
        var derA = function() {
          var res = dy;
          var reduceAxes = getReductionAxes(a.shape, outShape);
          if (reduceAxes.length > 0) {
            res = sum(res, reduceAxes);
          }
          return reshape$1(res, a.shape);
        };
        var derB = function() {
          var res = dy;
          var reduceAxes = getReductionAxes(b.shape, outShape);
          if (reduceAxes.length > 0) {
            res = sum(res, reduceAxes);
          }
          return reshape$1(neg(res), b.shape);
        };
        return { a: derA, b: derB };
      }
    };
    var sumGradConfig = {
      kernelName: Sum,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 1), x = _a2[0];
        var expandedDyShape = x.shape.slice();
        var axis = attrs.axis;
        var axes = parseAxisParam(axis, x.shape);
        axes.forEach(function(axis2) {
          expandedDyShape[axis2] = 1;
        });
        var expandedDy = reshape$1(dy, expandedDyShape);
        var derX = mul(expandedDy, ones$1(x.shape, "float32"));
        return { x: function() {
          return derX;
        } };
      }
    };
    var tanGradConfig = {
      kernelName: Tan,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), x = _a2[0];
        return { x: function() {
          return div(dy, square(cos(x)));
        } };
      }
    };
    var tanhGradConfig = {
      kernelName: Tanh$1,
      outputsToSave: [true],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), y = _a2[0];
        return { x: function() {
          return mul(sub(scalar(1), square(y)), dy);
        } };
      }
    };
    var tileGradConfig = {
      kernelName: Tile,
      inputsToSave: ["x"],
      gradFunc: function(dy, saved, attrs) {
        var _a2 = __read(saved, 1), x = _a2[0];
        var reps = attrs.reps;
        var derX = function() {
          var xGrad = zerosLike(x);
          if (x.rank === 1) {
            for (var i = 0; i < reps[0]; ++i) {
              xGrad = add$1(xGrad, slice(dy, [i * x.shape[0]], [x.shape[0]]));
            }
          } else if (x.rank === 2) {
            for (var i = 0; i < reps[0]; ++i) {
              for (var j = 0; j < reps[1]; ++j) {
                xGrad = add$1(xGrad, slice(dy, [i * x.shape[0], j * x.shape[1]], [
                  x.shape[0],
                  x.shape[1]
                ]));
              }
            }
          } else if (x.rank === 3) {
            for (var i = 0; i < reps[0]; ++i) {
              for (var j = 0; j < reps[1]; ++j) {
                for (var k = 0; k < reps[2]; ++k) {
                  xGrad = add$1(xGrad, slice(dy, [i * x.shape[0], j * x.shape[1], k * x.shape[2]], [x.shape[0], x.shape[1], x.shape[2]]));
                }
              }
            }
          } else if (x.rank === 4) {
            for (var i = 0; i < reps[0]; ++i) {
              for (var j = 0; j < reps[1]; ++j) {
                for (var k = 0; k < reps[2]; ++k) {
                  for (var l = 0; l < reps[3]; ++l) {
                    xGrad = add$1(xGrad, slice(dy, [
                      i * x.shape[0],
                      j * x.shape[1],
                      k * x.shape[2],
                      l * x.shape[3]
                    ], [x.shape[0], x.shape[1], x.shape[2], x.shape[3]]));
                  }
                }
              }
            }
          } else {
            throw new Error("Gradient for tile operation is not implemented for rank-" + "".concat(x.rank, " tensors yet."));
          }
          return xGrad;
        };
        return { x: derX };
      }
    };
    var transposeGradConfig = {
      kernelName: Transpose,
      gradFunc: function(dy, saved, attrs) {
        var transposeAttrs = attrs;
        var perm = transposeAttrs.perm;
        var undoPerm = getUndoAxesPermutation(perm);
        return { x: function() {
          return transpose(dy, undoPerm);
        } };
      }
    };
    var unpackGradConfig = {
      kernelName: Unpack,
      gradFunc: function(dy, saved, attrs) {
        var unpackAttrs = attrs;
        var axis = unpackAttrs.axis;
        return { value: function() {
          return stack(dy, axis);
        } };
      }
    };
    var unsortedSegmentSumGradConfig = {
      kernelName: UnsortedSegmentSum,
      inputsToSave: ["segmentIds"],
      gradFunc: function(dy, saved) {
        var _a2 = __read(saved, 1), segmentIds = _a2[0];
        var derX = function() {
          return gatherDropNegatives(dy, segmentIds);
        };
        return { x: derX };
      }
    };
    function gatherDropNegatives(x, indices) {
      var zeroClippedIndices = maximum$1(indices, zerosLike(indices));
      var gathered = gather(x, zeroClippedIndices);
      var isPositive = greaterEqual(indices, scalar(0, "int32"));
      var numIters = gathered.rank - isPositive.rank;
      for (var i = 0; i < numIters; ++i) {
        isPositive = expandDims(isPositive, i + 1);
      }
      isPositive = logicalAnd(isPositive, ones$1(gathered.shape, "bool"));
      var zeroSlice = zerosLike(gathered);
      return where(isPositive, gathered, zeroSlice);
    }
    var zerosLikeGradConfig = {
      kernelName: ZerosLike,
      gradFunc: function(dy) {
        return { x: function() {
          return zerosLike(dy);
        } };
      }
    };
    var e_1;
    var _a;
    var gradConfigs = [
      absGradConfig,
      acosGradConfig,
      acoshGradConfig,
      addGradConfig,
      addNGradConfig,
      argMaxGradConfig,
      argMinGradConfig,
      asinGradConfig,
      asinhGradConfig,
      atan2GradConfig,
      atanGradConfig,
      atanhGradConfig,
      avgPool3DGradConfig,
      avgPoolGradConfig,
      batchMatMulGradConfig,
      batchToSpaceNDGradConfig,
      broadcastToGradConfig,
      castGradConfig,
      ceilGradConfig,
      clipByValueGradConfig,
      complexAbsGradConfig,
      concatGradConfig,
      conv2DBackpropInputGradConfig,
      conv2DGradConfig,
      conv3DGradConfig,
      cosGradConfig,
      coshGradConfig,
      cumsumGradConfig,
      depthwiseConv2dNativeGradConfig,
      dilation2dGradConfig,
      divGradConfig,
      eluGradConfig,
      erfGradConfig,
      expGradConfig,
      expandDimsGradConfig,
      expm1GradConfig,
      floorDivGradConfig,
      floorGradConfig,
      fusedBatchNormGradConfig,
      gatherGradConfig,
      greaterEqualGradConfig,
      identityGradConfig,
      isFiniteGradConfig,
      isInfGradConfig,
      isNanGradConfig,
      leakyReluGradConfig,
      log1pGradConfig,
      logGradConfig,
      logSoftmaxGradConfig,
      lrnGradConfig,
      maxGradConfig,
      maxGradConfig,
      maximumGradConfig,
      maxPool3DGradConfig,
      maxPoolGradConfig,
      meanGradConfig,
      minGradConfig,
      minimumGradConfig,
      mirrorPadGradConfig,
      modGradConfig,
      multiplyGradConfig,
      negGradConfig,
      oneHotGradConfig,
      onesLikeGradConfig,
      packGradConfig,
      padV2GradConfig,
      padV2GradConfig,
      powGradConfig,
      preluGradConfig,
      prodGradConfig,
      reciprocalGradConfig,
      relu6GradConfig,
      reluGradConfig,
      reshapeGradConfig,
      resizeBilinearGradConfig,
      resizeNearestNeighborGradConfig,
      reverseGradConfig,
      roundGradConfig,
      rsqrtGradConfig,
      selectGradConfig,
      seluGradConfig,
      sigmoidGradConfig,
      signGradConfig,
      sinGradConfig,
      sinhGradConfig,
      sliceGradConfig,
      softmaxGradConfig,
      softplusGradConfig,
      spaceToBatchNDGradConfig,
      spaceToBatchNDGradConfig,
      splitVGradConfig,
      splitVGradConfig,
      sqrtGradConfig,
      squaredDifferenceGradConfig,
      squareGradConfig,
      stepGradConfig,
      subGradConfig,
      sumGradConfig,
      tanGradConfig,
      tanhGradConfig,
      tileGradConfig,
      transposeGradConfig,
      unpackGradConfig,
      unsortedSegmentSumGradConfig,
      zerosLikeGradConfig
    ];
    try {
      for (gradConfigs_1 = __values(gradConfigs), gradConfigs_1_1 = gradConfigs_1.next(); !gradConfigs_1_1.done; gradConfigs_1_1 = gradConfigs_1.next()) {
        gradientConfig = gradConfigs_1_1.value;
        registerGradient(gradientConfig);
      }
    } catch (e_1_1) {
      e_1 = { error: e_1_1 };
    } finally {
      try {
        if (gradConfigs_1_1 && !gradConfigs_1_1.done && (_a = gradConfigs_1.return)) _a.call(gradConfigs_1);
      } finally {
        if (e_1) throw e_1.error;
      }
    }
    var gradientConfig;
    var gradConfigs_1;
    var gradConfigs_1_1;
    function calcL2Norms(w, axis) {
      return tfc.tidy(function() {
        return tfc__namespace.sqrt(tfc__namespace.sum(tfc__namespace.mul(w, w), axis, true));
      });
    }
    var Constraint = (
      /** @class */
      function(_super) {
        __extends(Constraint2, _super);
        function Constraint2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Constraint2.prototype.getConfig = function() {
          return {};
        };
        return Constraint2;
      }(tfc.serialization.Serializable)
    );
    var MaxNorm = (
      /** @class */
      function(_super) {
        __extends(MaxNorm2, _super);
        function MaxNorm2(args) {
          var _this = _super.call(this) || this;
          _this.defaultMaxValue = 2;
          _this.defaultAxis = 0;
          _this.maxValue = args.maxValue != null ? args.maxValue : _this.defaultMaxValue;
          _this.axis = args.axis != null ? args.axis : _this.defaultAxis;
          return _this;
        }
        MaxNorm2.prototype.apply = function(w) {
          var _this = this;
          return tfc.tidy(function() {
            var norms = calcL2Norms(w, _this.axis);
            var desired = tfc__namespace.clipByValue(norms, 0, _this.maxValue);
            return tfc__namespace.mul(w, tfc__namespace.div(desired, tfc__namespace.add(epsilon(), norms)));
          });
        };
        MaxNorm2.prototype.getConfig = function() {
          return { maxValue: this.maxValue, axis: this.axis };
        };
        return MaxNorm2;
      }(Constraint)
    );
    MaxNorm.className = "MaxNorm";
    tfc.serialization.registerClass(MaxNorm);
    var UnitNorm = (
      /** @class */
      function(_super) {
        __extends(UnitNorm2, _super);
        function UnitNorm2(args) {
          var _this = _super.call(this) || this;
          _this.defaultAxis = 0;
          _this.axis = args.axis != null ? args.axis : _this.defaultAxis;
          return _this;
        }
        UnitNorm2.prototype.apply = function(w) {
          var _this = this;
          return tfc.tidy(function() {
            return tfc__namespace.div(w, tfc__namespace.add(epsilon(), calcL2Norms(w, _this.axis)));
          });
        };
        UnitNorm2.prototype.getConfig = function() {
          return { axis: this.axis };
        };
        return UnitNorm2;
      }(Constraint)
    );
    UnitNorm.className = "UnitNorm";
    tfc.serialization.registerClass(UnitNorm);
    var NonNeg = (
      /** @class */
      function(_super) {
        __extends(NonNeg2, _super);
        function NonNeg2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        NonNeg2.prototype.apply = function(w) {
          return tfc__namespace.relu(w);
        };
        return NonNeg2;
      }(Constraint)
    );
    NonNeg.className = "NonNeg";
    tfc.serialization.registerClass(NonNeg);
    var MinMaxNorm = (
      /** @class */
      function(_super) {
        __extends(MinMaxNorm2, _super);
        function MinMaxNorm2(args) {
          var _this = _super.call(this) || this;
          _this.defaultMinValue = 0;
          _this.defaultMaxValue = 1;
          _this.defaultRate = 1;
          _this.defaultAxis = 0;
          _this.minValue = args.minValue != null ? args.minValue : _this.defaultMinValue;
          _this.maxValue = args.maxValue != null ? args.maxValue : _this.defaultMaxValue;
          _this.rate = args.rate != null ? args.rate : _this.defaultRate;
          _this.axis = args.axis != null ? args.axis : _this.defaultAxis;
          return _this;
        }
        MinMaxNorm2.prototype.apply = function(w) {
          var _this = this;
          return tfc.tidy(function() {
            var norms = calcL2Norms(w, _this.axis);
            var desired = tfc__namespace.add(tfc__namespace.mul(_this.rate, tfc__namespace.clipByValue(norms, _this.minValue, _this.maxValue)), tfc__namespace.mul(1 - _this.rate, norms));
            return tfc__namespace.mul(w, tfc__namespace.div(desired, tfc__namespace.add(epsilon(), norms)));
          });
        };
        MinMaxNorm2.prototype.getConfig = function() {
          return {
            minValue: this.minValue,
            maxValue: this.maxValue,
            rate: this.rate,
            axis: this.axis
          };
        };
        return MinMaxNorm2;
      }(Constraint)
    );
    MinMaxNorm.className = "MinMaxNorm";
    tfc.serialization.registerClass(MinMaxNorm);
    var CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP = {
      "maxNorm": "MaxNorm",
      "minMaxNorm": "MinMaxNorm",
      "nonNeg": "NonNeg",
      "unitNorm": "UnitNorm"
    };
    function serializeConstraint(constraint) {
      return serializeKerasObject(constraint);
    }
    function deserializeConstraint(config, customObjects) {
      if (customObjects === void 0) {
        customObjects = {};
      }
      return deserializeKerasObject(config, tfc.serialization.SerializationMap.getMap().classNameMap, customObjects, "constraint");
    }
    function getConstraint(identifier) {
      if (identifier == null) {
        return null;
      }
      if (typeof identifier === "string") {
        var className = identifier in CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP ? CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP[identifier] : identifier;
        var config = { className, config: {} };
        return deserializeConstraint(config);
      } else if (identifier instanceof Constraint) {
        return identifier;
      } else {
        return deserializeConstraint(identifier);
      }
    }
    function maxNorm(args) {
      return new MaxNorm(args);
    }
    function unitNorm(args) {
      return new UnitNorm(args);
    }
    function nonNeg() {
      return new NonNeg();
    }
    function minMaxNorm(config) {
      return new MinMaxNorm(config);
    }
    var exports_constraints = {
      __proto__: null,
      maxNorm,
      minMaxNorm,
      nonNeg,
      unitNorm
    };
    function zeros() {
      return new Zeros();
    }
    function ones() {
      return new Ones();
    }
    function constant(args) {
      return new Constant(args);
    }
    function randomUniform(args) {
      return new RandomUniform(args);
    }
    function randomNormal(args) {
      return new RandomNormal(args);
    }
    function truncatedNormal(args) {
      return new TruncatedNormal(args);
    }
    function identity(args) {
      return new Identity$1(args);
    }
    function varianceScaling(config) {
      return new VarianceScaling(config);
    }
    function glorotUniform(args) {
      return new GlorotUniform(args);
    }
    function glorotNormal(args) {
      return new GlorotNormal(args);
    }
    function heNormal(args) {
      return new HeNormal(args);
    }
    function heUniform(args) {
      return new HeUniform(args);
    }
    function leCunNormal(args) {
      return new LeCunNormal(args);
    }
    function leCunUniform(args) {
      return new LeCunUniform(args);
    }
    function orthogonal(args) {
      return new Orthogonal(args);
    }
    var exports_initializers = {
      __proto__: null,
      constant,
      glorotNormal,
      glorotUniform,
      heNormal,
      heUniform,
      identity,
      leCunNormal,
      leCunUniform,
      ones,
      orthogonal,
      randomNormal,
      randomUniform,
      truncatedNormal,
      varianceScaling,
      zeros
    };
    function resolveScalarsInLogs(logs) {
      return __awaiter(this, void 0, void 0, function() {
        var promises, keys, scalarsToDispose, key, value, valueScalar, values, i;
        return __generator(this, function(_a2) {
          switch (_a2.label) {
            case 0:
              if (logs == null) {
                return [
                  2
                  /*return*/
                ];
              }
              promises = [];
              keys = [];
              scalarsToDispose = [];
              for (key in logs) {
                value = logs[key];
                if (typeof value !== "number") {
                  valueScalar = value;
                  promises.push(valueScalar.data());
                  keys.push(key);
                  scalarsToDispose.push(valueScalar);
                }
              }
              if (!(promises.length > 0)) return [3, 2];
              return [4, Promise.all(promises)];
            case 1:
              values = _a2.sent();
              for (i = 0; i < values.length; ++i) {
                logs[keys[i]] = values[i][0];
              }
              tfc.dispose(scalarsToDispose);
              _a2.label = 2;
            case 2:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    }
    function disposeTensorsInLogs(logs) {
      if (logs == null) {
        return;
      }
      for (var key in logs) {
        var value = logs[key];
        if (typeof value !== "number") {
          value.dispose();
        }
      }
    }
    var ModelLoggingVerbosity;
    (function(ModelLoggingVerbosity2) {
      ModelLoggingVerbosity2[ModelLoggingVerbosity2["SILENT"] = 0] = "SILENT";
      ModelLoggingVerbosity2[ModelLoggingVerbosity2["VERBOSE"] = 1] = "VERBOSE";
    })(ModelLoggingVerbosity || (ModelLoggingVerbosity = {}));
    var DEFAULT_YIELD_EVERY_MS = 125;
    var BaseCallback = (
      /** @class */
      function() {
        function BaseCallback2() {
          this.validationData = null;
        }
        BaseCallback2.prototype.setParams = function(params) {
          this.params = params;
        };
        BaseCallback2.prototype.onEpochBegin = function(epoch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              return [
                2
                /*return*/
              ];
            });
          });
        };
        BaseCallback2.prototype.onEpochEnd = function(epoch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              return [
                2
                /*return*/
              ];
            });
          });
        };
        BaseCallback2.prototype.onBatchBegin = function(batch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              return [
                2
                /*return*/
              ];
            });
          });
        };
        BaseCallback2.prototype.onBatchEnd = function(batch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              return [
                2
                /*return*/
              ];
            });
          });
        };
        BaseCallback2.prototype.onTrainBegin = function(logs) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              return [
                2
                /*return*/
              ];
            });
          });
        };
        BaseCallback2.prototype.onTrainEnd = function(logs) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              return [
                2
                /*return*/
              ];
            });
          });
        };
        BaseCallback2.prototype.setModel = function(model2) {
        };
        return BaseCallback2;
      }()
    );
    var CallbackList = (
      /** @class */
      function() {
        function CallbackList2(callbacks2, queueLength) {
          if (queueLength === void 0) {
            queueLength = 10;
          }
          if (callbacks2 == null) {
            callbacks2 = [];
          }
          this.callbacks = callbacks2;
          this.queueLength = queueLength;
        }
        CallbackList2.prototype.append = function(callback) {
          this.callbacks.push(callback);
        };
        CallbackList2.prototype.setParams = function(params) {
          var e_12, _a2;
          try {
            for (var _b = __values(this.callbacks), _c = _b.next(); !_c.done; _c = _b.next()) {
              var callback = _c.value;
              callback.setParams(params);
            }
          } catch (e_1_1) {
            e_12 = { error: e_1_1 };
          } finally {
            try {
              if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
            } finally {
              if (e_12) throw e_12.error;
            }
          }
        };
        CallbackList2.prototype.setModel = function(model2) {
          var e_2, _a2;
          try {
            for (var _b = __values(this.callbacks), _c = _b.next(); !_c.done; _c = _b.next()) {
              var callback = _c.value;
              callback.setModel(model2);
            }
          } catch (e_2_1) {
            e_2 = { error: e_2_1 };
          } finally {
            try {
              if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
            } finally {
              if (e_2) throw e_2.error;
            }
          }
        };
        CallbackList2.prototype.onEpochBegin = function(epoch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            var _a2, _b, callback, e_3_1;
            var e_3, _c;
            return __generator(this, function(_d) {
              switch (_d.label) {
                case 0:
                  if (logs == null) {
                    logs = {};
                  }
                  _d.label = 1;
                case 1:
                  _d.trys.push([1, 6, 7, 8]);
                  _a2 = __values(this.callbacks), _b = _a2.next();
                  _d.label = 2;
                case 2:
                  if (!!_b.done) return [3, 5];
                  callback = _b.value;
                  return [4, callback.onEpochBegin(epoch, logs)];
                case 3:
                  _d.sent();
                  _d.label = 4;
                case 4:
                  _b = _a2.next();
                  return [3, 2];
                case 5:
                  return [3, 8];
                case 6:
                  e_3_1 = _d.sent();
                  e_3 = { error: e_3_1 };
                  return [3, 8];
                case 7:
                  try {
                    if (_b && !_b.done && (_c = _a2.return)) _c.call(_a2);
                  } finally {
                    if (e_3) throw e_3.error;
                  }
                  return [
                    7
                    /*endfinally*/
                  ];
                case 8:
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        CallbackList2.prototype.onEpochEnd = function(epoch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            var _a2, _b, callback, e_4_1;
            var e_4, _c;
            return __generator(this, function(_d) {
              switch (_d.label) {
                case 0:
                  if (logs == null) {
                    logs = {};
                  }
                  _d.label = 1;
                case 1:
                  _d.trys.push([1, 6, 7, 8]);
                  _a2 = __values(this.callbacks), _b = _a2.next();
                  _d.label = 2;
                case 2:
                  if (!!_b.done) return [3, 5];
                  callback = _b.value;
                  return [4, callback.onEpochEnd(epoch, logs)];
                case 3:
                  _d.sent();
                  _d.label = 4;
                case 4:
                  _b = _a2.next();
                  return [3, 2];
                case 5:
                  return [3, 8];
                case 6:
                  e_4_1 = _d.sent();
                  e_4 = { error: e_4_1 };
                  return [3, 8];
                case 7:
                  try {
                    if (_b && !_b.done && (_c = _a2.return)) _c.call(_a2);
                  } finally {
                    if (e_4) throw e_4.error;
                  }
                  return [
                    7
                    /*endfinally*/
                  ];
                case 8:
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        CallbackList2.prototype.onBatchBegin = function(batch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            var _a2, _b, callback, e_5_1;
            var e_5, _c;
            return __generator(this, function(_d) {
              switch (_d.label) {
                case 0:
                  if (logs == null) {
                    logs = {};
                  }
                  _d.label = 1;
                case 1:
                  _d.trys.push([1, 6, 7, 8]);
                  _a2 = __values(this.callbacks), _b = _a2.next();
                  _d.label = 2;
                case 2:
                  if (!!_b.done) return [3, 5];
                  callback = _b.value;
                  return [4, callback.onBatchBegin(batch, logs)];
                case 3:
                  _d.sent();
                  _d.label = 4;
                case 4:
                  _b = _a2.next();
                  return [3, 2];
                case 5:
                  return [3, 8];
                case 6:
                  e_5_1 = _d.sent();
                  e_5 = { error: e_5_1 };
                  return [3, 8];
                case 7:
                  try {
                    if (_b && !_b.done && (_c = _a2.return)) _c.call(_a2);
                  } finally {
                    if (e_5) throw e_5.error;
                  }
                  return [
                    7
                    /*endfinally*/
                  ];
                case 8:
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        CallbackList2.prototype.onBatchEnd = function(batch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            var _a2, _b, callback, e_6_1;
            var e_6, _c;
            return __generator(this, function(_d) {
              switch (_d.label) {
                case 0:
                  if (logs == null) {
                    logs = {};
                  }
                  _d.label = 1;
                case 1:
                  _d.trys.push([1, 6, 7, 8]);
                  _a2 = __values(this.callbacks), _b = _a2.next();
                  _d.label = 2;
                case 2:
                  if (!!_b.done) return [3, 5];
                  callback = _b.value;
                  return [4, callback.onBatchEnd(batch, logs)];
                case 3:
                  _d.sent();
                  _d.label = 4;
                case 4:
                  _b = _a2.next();
                  return [3, 2];
                case 5:
                  return [3, 8];
                case 6:
                  e_6_1 = _d.sent();
                  e_6 = { error: e_6_1 };
                  return [3, 8];
                case 7:
                  try {
                    if (_b && !_b.done && (_c = _a2.return)) _c.call(_a2);
                  } finally {
                    if (e_6) throw e_6.error;
                  }
                  return [
                    7
                    /*endfinally*/
                  ];
                case 8:
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        CallbackList2.prototype.onTrainBegin = function(logs) {
          return __awaiter(this, void 0, void 0, function() {
            var _a2, _b, callback, e_7_1;
            var e_7, _c;
            return __generator(this, function(_d) {
              switch (_d.label) {
                case 0:
                  if (logs == null) {
                    logs = {};
                  }
                  _d.label = 1;
                case 1:
                  _d.trys.push([1, 6, 7, 8]);
                  _a2 = __values(this.callbacks), _b = _a2.next();
                  _d.label = 2;
                case 2:
                  if (!!_b.done) return [3, 5];
                  callback = _b.value;
                  return [4, callback.onTrainBegin(logs)];
                case 3:
                  _d.sent();
                  _d.label = 4;
                case 4:
                  _b = _a2.next();
                  return [3, 2];
                case 5:
                  return [3, 8];
                case 6:
                  e_7_1 = _d.sent();
                  e_7 = { error: e_7_1 };
                  return [3, 8];
                case 7:
                  try {
                    if (_b && !_b.done && (_c = _a2.return)) _c.call(_a2);
                  } finally {
                    if (e_7) throw e_7.error;
                  }
                  return [
                    7
                    /*endfinally*/
                  ];
                case 8:
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        CallbackList2.prototype.onTrainEnd = function(logs) {
          return __awaiter(this, void 0, void 0, function() {
            var _a2, _b, callback, e_8_1;
            var e_8, _c;
            return __generator(this, function(_d) {
              switch (_d.label) {
                case 0:
                  if (logs == null) {
                    logs = {};
                  }
                  _d.label = 1;
                case 1:
                  _d.trys.push([1, 6, 7, 8]);
                  _a2 = __values(this.callbacks), _b = _a2.next();
                  _d.label = 2;
                case 2:
                  if (!!_b.done) return [3, 5];
                  callback = _b.value;
                  return [4, callback.onTrainEnd(logs)];
                case 3:
                  _d.sent();
                  _d.label = 4;
                case 4:
                  _b = _a2.next();
                  return [3, 2];
                case 5:
                  return [3, 8];
                case 6:
                  e_8_1 = _d.sent();
                  e_8 = { error: e_8_1 };
                  return [3, 8];
                case 7:
                  try {
                    if (_b && !_b.done && (_c = _a2.return)) _c.call(_a2);
                  } finally {
                    if (e_8) throw e_8.error;
                  }
                  return [
                    7
                    /*endfinally*/
                  ];
                case 8:
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        return CallbackList2;
      }()
    );
    var BaseLogger = (
      /** @class */
      function(_super) {
        __extends(BaseLogger2, _super);
        function BaseLogger2() {
          return _super.call(this) || this;
        }
        BaseLogger2.prototype.onEpochBegin = function(epoch) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              this.seen = 0;
              this.totals = {};
              return [
                2
                /*return*/
              ];
            });
          });
        };
        BaseLogger2.prototype.onBatchEnd = function(batch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            var batchSize, _loop_1, this_1, key;
            var _this = this;
            return __generator(this, function(_a2) {
              if (logs == null) {
                logs = {};
              }
              batchSize = logs["size"] == null ? 0 : logs["size"];
              this.seen += batchSize;
              _loop_1 = function(key2) {
                var value = logs[key2];
                if (typeof value === "number") {
                  if (!this_1.totals.hasOwnProperty(key2)) {
                    this_1.totals[key2] = 0;
                  }
                  this_1.totals[key2] = this_1.totals[key2] + value * batchSize;
                } else {
                  var oldTotalsToDispose = void 0;
                  if (key2 in this_1.totals) {
                    oldTotalsToDispose = this_1.totals[key2];
                  } else {
                    this_1.totals[key2] = 0;
                  }
                  var total = tfc.tidy(function() {
                    return tfc.add(_this.totals[key2], tfc.mul(value, batchSize));
                  });
                  this_1.totals[key2] = total;
                  if (oldTotalsToDispose != null) {
                    oldTotalsToDispose.dispose();
                  }
                }
              };
              this_1 = this;
              for (key in logs) {
                _loop_1(key);
              }
              return [
                2
                /*return*/
              ];
            });
          });
        };
        BaseLogger2.prototype.onEpochEnd = function(epoch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            var _loop_2, this_2, _a2, _b, key;
            var e_9, _c;
            var _this = this;
            return __generator(this, function(_d) {
              if (logs != null) {
                _loop_2 = function(key2) {
                  if (this_2.totals[key2] == null) {
                    return "continue";
                  }
                  if (typeof this_2.totals[key2] === "number") {
                    logs[key2] = this_2.totals[key2] / this_2.seen;
                  } else {
                    tfc.tidy(function() {
                      var log2 = tfc.mul(tfc.div(1, _this.seen), _this.totals[key2]);
                      logs[key2] = log2;
                      _this.totals[key2].dispose();
                      tfc.keep(logs[key2]);
                    });
                  }
                };
                this_2 = this;
                try {
                  for (_a2 = __values(this.params["metrics"]), _b = _a2.next(); !_b.done; _b = _a2.next()) {
                    key = _b.value;
                    _loop_2(key);
                  }
                } catch (e_9_1) {
                  e_9 = { error: e_9_1 };
                } finally {
                  try {
                    if (_b && !_b.done && (_c = _a2.return)) _c.call(_a2);
                  } finally {
                    if (e_9) throw e_9.error;
                  }
                }
              }
              return [
                2
                /*return*/
              ];
            });
          });
        };
        return BaseLogger2;
      }(BaseCallback)
    );
    var History = (
      /** @class */
      function(_super) {
        __extends(History2, _super);
        function History2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        History2.prototype.onTrainBegin = function(logs) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              this.epoch = [];
              this.history = {};
              return [
                2
                /*return*/
              ];
            });
          });
        };
        History2.prototype.onEpochEnd = function(epoch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            var key;
            return __generator(this, function(_a2) {
              if (logs == null) {
                logs = {};
              }
              this.epoch.push(epoch);
              for (key in logs) {
                if (this.history[key] == null) {
                  this.history[key] = [];
                }
                this.history[key].push(logs[key]);
              }
              return [
                2
                /*return*/
              ];
            });
          });
        };
        History2.prototype.syncData = function() {
          return __awaiter(this, void 0, void 0, function() {
            var promises, keys, indices, key, valueArray, i, valueScalar, values, n, tensorToDispose;
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  promises = [];
                  keys = [];
                  indices = [];
                  for (key in this.history) {
                    valueArray = this.history[key];
                    for (i = 0; i < valueArray.length; ++i) {
                      if (typeof valueArray[i] !== "number") {
                        valueScalar = valueArray[i];
                        promises.push(valueScalar.data());
                        keys.push(key);
                        indices.push(i);
                      }
                    }
                  }
                  return [4, Promise.all(promises)];
                case 1:
                  values = _a2.sent();
                  for (n = 0; n < values.length; ++n) {
                    tensorToDispose = this.history[keys[n]][indices[n]];
                    tensorToDispose.dispose();
                    this.history[keys[n]][indices[n]] = values[n][0];
                  }
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        return History2;
      }(BaseCallback)
    );
    var CustomCallback = (
      /** @class */
      function(_super) {
        __extends(CustomCallback2, _super);
        function CustomCallback2(args, yieldEvery) {
          var _this = _super.call(this) || this;
          _this.currentEpoch = 0;
          _this.nowFunc = args.nowFunc;
          _this.nextFrameFunc = args.nextFrameFunc || tfc.nextFrame;
          _this.yieldEvery = yieldEvery || "auto";
          if (_this.yieldEvery === "auto") {
            _this.yieldEvery = DEFAULT_YIELD_EVERY_MS;
          }
          if (_this.yieldEvery === "never" && args.onYield != null) {
            throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");
          }
          if (tfc.util.isNumber(_this.yieldEvery)) {
            _this.maybeWait = debounce(_this.maybeWait.bind(_this), _this.yieldEvery, _this.nowFunc);
          }
          _this.trainBegin = args.onTrainBegin;
          _this.trainEnd = args.onTrainEnd;
          _this.epochBegin = args.onEpochBegin;
          _this.epochEnd = args.onEpochEnd;
          _this.batchBegin = args.onBatchBegin;
          _this.batchEnd = args.onBatchEnd;
          _this.yield = args.onYield;
          return _this;
        }
        CustomCallback2.prototype.maybeWait = function(epoch, batch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            var ps;
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  ps = [];
                  if (!(this.yield != null)) return [3, 2];
                  return [4, resolveScalarsInLogs(logs)];
                case 1:
                  _a2.sent();
                  ps.push(this.yield(epoch, batch, logs));
                  _a2.label = 2;
                case 2:
                  ps.push(this.nextFrameFunc());
                  return [4, Promise.all(ps)];
                case 3:
                  _a2.sent();
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        CustomCallback2.prototype.onEpochBegin = function(epoch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  this.currentEpoch = epoch;
                  if (!(this.epochBegin != null)) return [3, 3];
                  return [4, resolveScalarsInLogs(logs)];
                case 1:
                  _a2.sent();
                  return [4, this.epochBegin(epoch, logs)];
                case 2:
                  _a2.sent();
                  _a2.label = 3;
                case 3:
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        CustomCallback2.prototype.onEpochEnd = function(epoch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            var ps;
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  ps = [];
                  if (!(this.epochEnd != null)) return [3, 2];
                  return [4, resolveScalarsInLogs(logs)];
                case 1:
                  _a2.sent();
                  ps.push(this.epochEnd(epoch, logs));
                  _a2.label = 2;
                case 2:
                  if (this.yieldEvery === "epoch") {
                    ps.push(this.nextFrameFunc());
                  }
                  return [4, Promise.all(ps)];
                case 3:
                  _a2.sent();
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        CustomCallback2.prototype.onBatchBegin = function(batch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  if (!(this.batchBegin != null)) return [3, 3];
                  return [4, resolveScalarsInLogs(logs)];
                case 1:
                  _a2.sent();
                  return [4, this.batchBegin(batch, logs)];
                case 2:
                  _a2.sent();
                  _a2.label = 3;
                case 3:
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        CustomCallback2.prototype.onBatchEnd = function(batch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            var ps;
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  ps = [];
                  if (!(this.batchEnd != null)) return [3, 2];
                  return [4, resolveScalarsInLogs(logs)];
                case 1:
                  _a2.sent();
                  ps.push(this.batchEnd(batch, logs));
                  _a2.label = 2;
                case 2:
                  if (this.yieldEvery === "batch") {
                    ps.push(this.nextFrameFunc());
                  } else if (tfc.util.isNumber(this.yieldEvery)) {
                    ps.push(this.maybeWait(this.currentEpoch, batch, logs));
                  }
                  return [4, Promise.all(ps)];
                case 3:
                  _a2.sent();
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        CustomCallback2.prototype.onTrainBegin = function(logs) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  if (!(this.trainBegin != null)) return [3, 3];
                  return [4, resolveScalarsInLogs(logs)];
                case 1:
                  _a2.sent();
                  return [4, this.trainBegin(logs)];
                case 2:
                  _a2.sent();
                  _a2.label = 3;
                case 3:
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        CustomCallback2.prototype.onTrainEnd = function(logs) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  if (!(this.trainEnd != null)) return [3, 3];
                  return [4, resolveScalarsInLogs(logs)];
                case 1:
                  _a2.sent();
                  return [4, this.trainEnd(logs)];
                case 2:
                  _a2.sent();
                  _a2.label = 3;
                case 3:
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        return CustomCallback2;
      }(BaseCallback)
    );
    function standardizeCallbacks(callbacks2, yieldEvery) {
      if (callbacks2 == null) {
        callbacks2 = {};
      }
      if (callbacks2 instanceof BaseCallback) {
        return [callbacks2];
      }
      if (Array.isArray(callbacks2) && callbacks2[0] instanceof BaseCallback) {
        return callbacks2;
      }
      var callbackConfigs = toList(callbacks2);
      return callbackConfigs.map(function(callbackConfig) {
        return new CustomCallback(callbackConfig, yieldEvery);
      });
    }
    var CallbackConstructorRegistry = (
      /** @class */
      function() {
        function CallbackConstructorRegistry2() {
        }
        CallbackConstructorRegistry2.registerCallbackConstructor = function(verbosityLevel, callbackConstructor) {
          tfc.util.assert(verbosityLevel >= 0 && Number.isInteger(verbosityLevel), function() {
            return "Verbosity level is expected to be an integer >= 0, " + "but got ".concat(verbosityLevel);
          });
          CallbackConstructorRegistry2.checkForDuplicate(callbackConstructor);
          if (CallbackConstructorRegistry2.constructors[verbosityLevel] == null) {
            CallbackConstructorRegistry2.constructors[verbosityLevel] = [];
          }
          CallbackConstructorRegistry2.constructors[verbosityLevel].push(callbackConstructor);
        };
        CallbackConstructorRegistry2.checkForDuplicate = function(callbackConstructor) {
          for (var levelName in CallbackConstructorRegistry2.constructors) {
            var constructors = CallbackConstructorRegistry2.constructors[+levelName];
            constructors.forEach(function(ctor) {
              if (ctor === callbackConstructor) {
                throw new ValueError("Duplicate callback constructor.");
              }
            });
          }
        };
        CallbackConstructorRegistry2.clear = function() {
          CallbackConstructorRegistry2.constructors = {};
        };
        CallbackConstructorRegistry2.createCallbacks = function(verbosityLevel) {
          var constructors = [];
          for (var levelName in CallbackConstructorRegistry2.constructors) {
            var level = +levelName;
            if (verbosityLevel >= level) {
              constructors.push.apply(constructors, __spreadArray([], __read(CallbackConstructorRegistry2.constructors[level]), false));
            }
          }
          return constructors.map(function(ctor) {
            return new ctor();
          });
        };
        return CallbackConstructorRegistry2;
      }()
    );
    CallbackConstructorRegistry.constructors = {};
    function configureCallbacks(callbacks2, verbose, epochs, initialEpoch, numTrainSamples, stepsPerEpoch, batchSize, doValidation, callbackMetrics) {
      var history = new History();
      var actualCallbacks = __spreadArray([
        new BaseLogger()
      ], __read(CallbackConstructorRegistry.createCallbacks(verbose)), false);
      if (callbacks2 != null) {
        actualCallbacks.push.apply(actualCallbacks, __spreadArray([], __read(callbacks2), false));
      }
      actualCallbacks.push(history);
      var callbackList = new CallbackList(actualCallbacks);
      callbackList.setParams({
        epochs,
        initialEpoch,
        samples: numTrainSamples,
        steps: stepsPerEpoch,
        batchSize,
        verbose,
        doValidation,
        metrics: callbackMetrics
      });
      return { callbackList, history };
    }
    function deserialize(config, customObjects, fastWeightInit) {
      if (customObjects === void 0) {
        customObjects = {};
      }
      if (fastWeightInit === void 0) {
        fastWeightInit = false;
      }
      return deserializeKerasObject(config, tfc.serialization.SerializationMap.getMap().classNameMap, customObjects, "layer", fastWeightInit);
    }
    function l2Normalize(x, axis) {
      return tfc.tidy(function() {
        if (x.dtype !== "float32") {
          x = tfc__namespace.cast(x, "float32");
        }
        var squareSum = tfc__namespace.sum(square$1(x), axis, true);
        var epsilonTensor = tfc__namespace.fill(squareSum.shape, epsilon());
        var norm = tfc__namespace.sqrt(tfc__namespace.maximum(squareSum, epsilonTensor));
        return tfc__namespace.div(x, norm);
      });
    }
    function meanSquaredError$1(yTrue, yPred) {
      return tfc.tidy(function() {
        return tfc__namespace.mean(square$1(tfc__namespace.sub(yPred, yTrue)), -1);
      });
    }
    function meanAbsoluteError$1(yTrue, yPred) {
      return tfc.tidy(function() {
        return tfc__namespace.mean(tfc__namespace.abs(tfc__namespace.sub(yPred, yTrue)), -1);
      });
    }
    function meanAbsolutePercentageError$1(yTrue, yPred) {
      return tfc.tidy(function() {
        var diff = tfc__namespace.sub(yTrue, yPred);
        var clippedTrue = tfc__namespace.clipByValue(tfc__namespace.abs(yTrue), epsilon(), Number.MAX_VALUE);
        var absResult = tfc__namespace.abs(tfc__namespace.div(diff, clippedTrue));
        return tfc__namespace.mul(100, tfc__namespace.mean(absResult, -1));
      });
    }
    function meanSquaredLogarithmicError(yTrue, yPred) {
      return tfc.tidy(function() {
        var clippedPred = tfc__namespace.clipByValue(yPred, epsilon(), Number.MAX_VALUE);
        var firstLog = tfc__namespace.log(tfc__namespace.add(1, clippedPred));
        var clippedTrue = tfc__namespace.clipByValue(yTrue, epsilon(), Number.MAX_VALUE);
        var secondLog = tfc__namespace.log(tfc__namespace.add(1, clippedTrue));
        return tfc__namespace.mean(square$1(tfc__namespace.sub(firstLog, secondLog)), -1);
      });
    }
    function squaredHinge(yTrue, yPred) {
      return tfc.tidy(function() {
        var maxResult = tfc__namespace.maximum(0, tfc__namespace.sub(1, tfc__namespace.mul(yTrue, yPred)));
        return tfc__namespace.mean(square$1(maxResult), -1);
      });
    }
    function hinge(yTrue, yPred) {
      return tfc.tidy(function() {
        var maxResult = tfc__namespace.maximum(0, tfc__namespace.sub(1, tfc__namespace.mul(yTrue, yPred)));
        return tfc__namespace.mean(maxResult, -1);
      });
    }
    function categoricalHinge(yTrue, yPred) {
      return tfc.tidy(function() {
        var pos = tfc__namespace.sum(tfc__namespace.mul(yTrue, yPred), -1);
        var neg2 = tfc__namespace.max(tfc__namespace.mul(tfc__namespace.sub(1, yTrue), yPred), -1);
        return tfc__namespace.maximum(0, tfc__namespace.add(1, tfc__namespace.sub(neg2, pos)));
      });
    }
    function logcosh(yTrue, yPred) {
      return tfc.tidy(function() {
        var log2 = Math.log(2);
        var predictionDiff = tfc__namespace.sub(yPred, yTrue);
        var logcoshResult = tfc__namespace.sub(tfc__namespace.add(predictionDiff, tfc__namespace.softplus(tfc__namespace.mul(-2, predictionDiff))), log2);
        return tfc__namespace.mean(logcoshResult, -1);
      });
    }
    function categoricalCrossentropy$2(target, output, fromLogits) {
      if (fromLogits === void 0) {
        fromLogits = false;
      }
      return tfc.tidy(function() {
        if (fromLogits) {
          output = tfc__namespace.softmax(output);
        } else {
          var outputSum = tfc__namespace.sum(output, output.shape.length - 1, true);
          output = tfc__namespace.div(output, outputSum);
        }
        output = tfc__namespace.clipByValue(output, epsilon(), 1 - epsilon());
        return tfc__namespace.neg(tfc__namespace.sum(tfc__namespace.mul(tfc__namespace.cast(target, "float32"), tfc__namespace.log(output)), output.shape.length - 1));
      });
    }
    function sparseCategoricalCrossentropy$1(target, output, fromLogits) {
      if (fromLogits === void 0) {
        fromLogits = false;
      }
      return tfc.tidy(function() {
        var flatTarget = tfc__namespace.cast(tfc__namespace.floor(flatten$2(target)), "int32");
        output = tfc__namespace.clipByValue(output, epsilon(), 1 - epsilon());
        var outputShape = output.shape;
        var oneHotTarget = tfc__namespace.reshape(tfc__namespace.oneHot(flatTarget, outputShape[outputShape.length - 1]), outputShape);
        return categoricalCrossentropy$2(oneHotTarget, output, fromLogits);
      });
    }
    function sigmoidCrossEntropyWithLogits(labels, logits) {
      if (!tfc.util.arraysEqual(labels.shape, logits.shape)) {
        throw new ValueError("logits and labels must have the same shape, but got shapes " + "".concat(JSON.stringify(labels.shape), " and ").concat(JSON.stringify(logits.shape)));
      }
      return tfc.tidy(function() {
        var reluLogits = tfc__namespace.relu(logits);
        var negAbsLogits = tfc__namespace.neg(tfc__namespace.abs(logits));
        return tfc__namespace.add(tfc__namespace.sub(reluLogits, tfc__namespace.mul(logits, labels)), tfc__namespace.log1p(tfc__namespace.exp(negAbsLogits)));
      });
    }
    function binaryCrossentropy$2(yTrue, yPred) {
      return tfc.tidy(function() {
        var y;
        y = tfc__namespace.clipByValue(yPred, epsilon(), 1 - epsilon());
        y = tfc__namespace.log(tfc__namespace.div(y, tfc__namespace.sub(1, y)));
        return tfc__namespace.mean(sigmoidCrossEntropyWithLogits(yTrue, y), -1);
      });
    }
    function kullbackLeiblerDivergence(yTrue, yPred) {
      return tfc.tidy(function() {
        var clippedTrue = tfc__namespace.clipByValue(yTrue, epsilon(), 1);
        var clippedPred = tfc__namespace.clipByValue(yPred, epsilon(), 1);
        return tfc__namespace.sum(tfc__namespace.mul(yTrue, tfc__namespace.log(tfc__namespace.div(clippedTrue, clippedPred))), -1);
      });
    }
    function poisson(yTrue, yPred) {
      return tfc.tidy(function() {
        var logPred = tfc__namespace.log(tfc__namespace.add(epsilon(), yPred));
        return tfc__namespace.mean(tfc__namespace.sub(yPred, tfc__namespace.mul(yTrue, logPred)), -1);
      });
    }
    function cosineProximity$1(yTrue, yPred) {
      return tfc.tidy(function() {
        var trueNormalized = l2Normalize(yTrue, -1);
        var predNormalized = l2Normalize(yPred, -1);
        var trueXPred = tfc__namespace.mul(trueNormalized, predNormalized);
        return tfc__namespace.neg(tfc__namespace.sum(trueXPred, -1));
      });
    }
    var lossesMap = {
      meanSquaredError: meanSquaredError$1,
      meanAbsoluteError: meanAbsoluteError$1,
      meanAbsolutePercentageError: meanAbsolutePercentageError$1,
      meanSquaredLogarithmicError,
      squaredHinge,
      hinge,
      categoricalHinge,
      logcosh,
      categoricalCrossentropy: categoricalCrossentropy$2,
      sparseCategoricalCrossentropy: sparseCategoricalCrossentropy$1,
      binaryCrossentropy: binaryCrossentropy$2,
      kullbackLeiblerDivergence,
      poisson,
      cosineProximity: cosineProximity$1
    };
    function get$1(identifierOrFn) {
      if (typeof identifierOrFn === "string") {
        if (identifierOrFn in lossesMap) {
          return lossesMap[identifierOrFn];
        }
        var errMsg = "Unknown loss ".concat(identifierOrFn);
        if (identifierOrFn.toLowerCase().includes("softmaxcrossentropy")) {
          errMsg = "Unknown loss ".concat(identifierOrFn, ". ") + 'Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy';
        }
        throw new ValueError(errMsg);
      } else {
        return identifierOrFn;
      }
    }
    function binaryAccuracy$1(yTrue, yPred) {
      return tfc.tidy(function() {
        var threshold = tfc__namespace.mul(0.5, tfc__namespace.onesLike(yPred));
        var yPredThresholded = cast$1(tfc__namespace.greater(yPred, threshold), yTrue.dtype);
        return tfc__namespace.mean(tfc__namespace.equal(yTrue, yPredThresholded), -1);
      });
    }
    function categoricalAccuracy$1(yTrue, yPred) {
      return tfc.tidy(function() {
        return cast$1(tfc__namespace.equal(tfc__namespace.argMax(yTrue, -1), tfc__namespace.argMax(yPred, -1)), "float32");
      });
    }
    function truePositives(yTrue, yPred) {
      return tfc.tidy(function() {
        return tfc__namespace.cast(tfc__namespace.sum(tfc__namespace.logicalAnd(tfc__namespace.equal(yTrue, 1), tfc__namespace.equal(yPred, 1))), "float32");
      });
    }
    function falseNegatives(yTrue, yPred) {
      return tfc.tidy(function() {
        return tfc__namespace.cast(tfc__namespace.sum(tfc__namespace.logicalAnd(tfc__namespace.equal(yTrue, 1), tfc__namespace.equal(yPred, 0))), "float32");
      });
    }
    function falsePositives(yTrue, yPred) {
      return tfc.tidy(function() {
        return tfc__namespace.cast(tfc__namespace.sum(tfc__namespace.logicalAnd(tfc__namespace.equal(yTrue, 0), tfc__namespace.equal(yPred, 1))), "float32");
      });
    }
    function precision$1(yTrue, yPred) {
      return tfc.tidy(function() {
        var tp = truePositives(yTrue, yPred);
        var fp = falsePositives(yTrue, yPred);
        var denominator = tfc__namespace.add(tp, fp);
        return tfc__namespace.cast(tfc__namespace.where(tfc__namespace.greater(denominator, 0), tfc__namespace.div(tp, denominator), 0), "float32");
      });
    }
    function recall$1(yTrue, yPred) {
      return tfc.tidy(function() {
        var tp = truePositives(yTrue, yPred);
        var fn = falseNegatives(yTrue, yPred);
        var denominator = tfc__namespace.add(tp, fn);
        return tfc__namespace.cast(tfc__namespace.where(tfc__namespace.greater(denominator, 0), tfc__namespace.div(tp, denominator), 0), "float32");
      });
    }
    function binaryCrossentropy$1(yTrue, yPred) {
      return binaryCrossentropy$2(yTrue, yPred);
    }
    function sparseCategoricalAccuracy$1(yTrue, yPred) {
      if (yTrue.rank === yPred.rank) {
        yTrue = tfc__namespace.squeeze(yTrue, [yTrue.rank - 1]);
      }
      yPred = tfc__namespace.argMax(yPred, -1);
      if (yPred.dtype !== yTrue.dtype) {
        yPred = tfc__namespace.cast(yPred, yTrue.dtype);
      }
      return tfc__namespace.cast(tfc__namespace.equal(yTrue, yPred), "float32");
    }
    function r2Score$1(yTrue, yPred) {
      return tfc.tidy(function() {
        var sumSquaresResiduals = yTrue.sub(yPred).square().sum();
        var sumSquares = yTrue.sub(yTrue.mean()).square().sum();
        return tfc__namespace.scalar(1).sub(sumSquaresResiduals.div(sumSquares));
      });
    }
    var mse$1 = meanSquaredError$1;
    var MSE$1 = meanSquaredError$1;
    var mae = meanAbsoluteError$1;
    var MAE = meanAbsoluteError$1;
    var mape$1 = meanAbsolutePercentageError$1;
    var MAPE$1 = meanAbsolutePercentageError$1;
    var categoricalCrossentropy$1 = categoricalCrossentropy$2;
    var cosine = cosineProximity$1;
    var sparseCategoricalCrossentropy = sparseCategoricalCrossentropy$1;
    var metricsMap = {
      binaryAccuracy: binaryAccuracy$1,
      categoricalAccuracy: categoricalAccuracy$1,
      precision: precision$1,
      categoricalCrossentropy: categoricalCrossentropy$1,
      sparseCategoricalCrossentropy,
      mse: mse$1,
      MSE: MSE$1,
      mae,
      MAE,
      mape: mape$1,
      MAPE: MAPE$1,
      cosine
    };
    function get(identifier) {
      if (typeof identifier === "string" && identifier in metricsMap) {
        return metricsMap[identifier];
      } else if (typeof identifier !== "string" && identifier != null) {
        return identifier;
      } else {
        throw new ValueError("Unknown metric ".concat(identifier));
      }
    }
    function getLossOrMetricName(fn) {
      var e_12, _a2, e_2, _b;
      assert$1(fn !== null, "Unknown LossOrMetricFn ".concat(fn));
      if (typeof fn === "string") {
        return fn;
      } else {
        var fnName = void 0;
        try {
          for (var _c = __values(Object.keys(lossesMap)), _d = _c.next(); !_d.done; _d = _c.next()) {
            var key = _d.value;
            if (lossesMap[key] === fn) {
              fnName = key;
              break;
            }
          }
        } catch (e_1_1) {
          e_12 = { error: e_1_1 };
        } finally {
          try {
            if (_d && !_d.done && (_a2 = _c.return)) _a2.call(_c);
          } finally {
            if (e_12) throw e_12.error;
          }
        }
        if (fnName !== void 0) {
          return fnName;
        }
        try {
          for (var _e = __values(Object.keys(metricsMap)), _f = _e.next(); !_f.done; _f = _e.next()) {
            var key = _f.value;
            if (metricsMap[key] === fn) {
              fnName = key;
              break;
            }
          }
        } catch (e_2_1) {
          e_2 = { error: e_2_1 };
        } finally {
          try {
            if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
          } finally {
            if (e_2) throw e_2.error;
          }
        }
        if (fnName !== void 0) {
          return fnName;
        }
        return fn.name;
      }
    }
    function getOptimizer(identifier) {
      var optimizerMap = {
        "Adagrad": function() {
          return tfc.train.adagrad(0.01);
        },
        "Adadelta": function() {
          return tfc.train.adadelta(1, 0.95, epsilon());
        },
        "Adam": function() {
          return tfc.train.adam(1e-3, 0.9, 0.999, epsilon());
        },
        "Adamax": function() {
          return tfc.train.adamax(2e-3, 0.9, 0.999, epsilon(), 0);
        },
        "RMSProp": function() {
          return tfc.train.rmsprop(1e-3, 0.9, 0, epsilon());
        },
        "SGD": function() {
          return tfc.train.sgd(0.01);
        }
      };
      optimizerMap["adagrad"] = optimizerMap["Adagrad"];
      optimizerMap["adadelta"] = optimizerMap["Adadelta"];
      optimizerMap["adam"] = optimizerMap["Adam"];
      optimizerMap["adamax"] = optimizerMap["Adamax"];
      optimizerMap["rmsprop"] = optimizerMap["RMSProp"];
      optimizerMap["sgd"] = optimizerMap["SGD"];
      if (identifier in optimizerMap) {
        return optimizerMap[identifier]();
      }
      throw new ValueError("Unknown Optimizer ".concat(identifier));
    }
    var MAX_USER_DEFINED_METADATA_SERIALIZED_LENGTH = 1 * 1024 * 1024;
    function checkUserDefinedMetadata(userDefinedMetadata, modelName, checkSize) {
      if (checkSize === void 0) {
        checkSize = false;
      }
      if (userDefinedMetadata == null || typeof userDefinedMetadata !== "object" || Object.getPrototypeOf(userDefinedMetadata) !== Object.prototype || !plainObjectCheck(userDefinedMetadata)) {
        throw new Error("User-defined metadata is expected to be a JSON object, but is not.");
      }
      if (checkSize) {
        var out = JSON.stringify(userDefinedMetadata);
        if (out.length > MAX_USER_DEFINED_METADATA_SERIALIZED_LENGTH) {
          console.warn('User-defined metadata of model "'.concat(modelName, '" is too large in ') + "size (length=".concat(out.length, " when serialized). It is not ") + "recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= " + "".concat(MAX_USER_DEFINED_METADATA_SERIALIZED_LENGTH, "."));
        }
      }
    }
    function plainObjectCheck(x) {
      var e_12, _a2, e_2, _b;
      if (x === null) {
        return true;
      } else if (typeof x === "object") {
        if (Object.getPrototypeOf(x) === Object.prototype) {
          var keys = Object.keys(x);
          try {
            for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
              var key = keys_1_1.value;
              if (typeof key !== "string") {
                return false;
              }
              if (!plainObjectCheck(x[key])) {
                return false;
              }
            }
          } catch (e_1_1) {
            e_12 = { error: e_1_1 };
          } finally {
            try {
              if (keys_1_1 && !keys_1_1.done && (_a2 = keys_1.return)) _a2.call(keys_1);
            } finally {
              if (e_12) throw e_12.error;
            }
          }
          return true;
        } else {
          if (Array.isArray(x)) {
            try {
              for (var x_1 = __values(x), x_1_1 = x_1.next(); !x_1_1.done; x_1_1 = x_1.next()) {
                var item = x_1_1.value;
                if (!plainObjectCheck(item)) {
                  return false;
                }
              }
            } catch (e_2_1) {
              e_2 = { error: e_2_1 };
            } finally {
              try {
                if (x_1_1 && !x_1_1.done && (_b = x_1.return)) _b.call(x_1);
              } finally {
                if (e_2) throw e_2.error;
              }
            }
            return true;
          } else {
            return false;
          }
        }
      } else {
        var xType = typeof x;
        return xType === "string" || xType === "number" || xType === "boolean";
      }
    }
    function printSummary(model2, lineLength, positions, printFn) {
      if (printFn === void 0) {
        printFn = console.log;
      }
      var sequentialLike = isModelSequentialLike(model2);
      var toDisplay = ["Layer (type)", "Input Shape", "Output shape", "Param #"];
      if (sequentialLike) {
        lineLength = lineLength || 90;
        positions = positions || [0.32, 0.61, 0.89, 1];
      } else {
        lineLength = lineLength || 115;
        positions = positions || [0.24, 0.48, 0.7, 0.8, 1];
      }
      if (positions[positions.length - 1] <= 1) {
        positions = positions.map(function(p) {
          return Math.floor(lineLength * p);
        });
      }
      var relevantNodes;
      if (!sequentialLike) {
        toDisplay.push("Receives inputs");
        relevantNodes = [];
        for (var depth in model2.nodesByDepth) {
          relevantNodes.push.apply(relevantNodes, __spreadArray([], __read(model2.nodesByDepth[depth]), false));
        }
      }
      printFn("_".repeat(lineLength));
      printRow(toDisplay, positions, printFn);
      printFn("=".repeat(lineLength));
      var layers = model2.layers;
      for (var i = 0; i < layers.length; ++i) {
        if (sequentialLike) {
          printLayerSummary(layers[i], positions, printFn);
        } else {
          printLayerSummaryWithConnections(layers[i], positions, relevantNodes, printFn);
        }
        printFn((i === layers.length - 1 ? "=" : "_").repeat(lineLength));
      }
      model2.checkTrainableWeightsConsistency();
      var trainableCount = countTrainableParams(model2);
      var nonTrainableCount = countParamsInWeights(model2.nonTrainableWeights);
      printFn("Total params: ".concat(trainableCount + nonTrainableCount));
      printFn("Trainable params: ".concat(trainableCount));
      printFn("Non-trainable params: ".concat(nonTrainableCount));
      printFn("_".repeat(lineLength));
    }
    function countTrainableParams(model2) {
      var trainableCount;
      if (model2.collectedTrainableWeights != null) {
        trainableCount = countParamsInWeights(model2.collectedTrainableWeights);
      } else {
        trainableCount = countParamsInWeights(model2.trainableWeights);
      }
      return trainableCount;
    }
    function isModelSequentialLike(model2) {
      var e_12, _a2, e_2, _b, e_3, _c;
      var sequentialLike = true;
      var nodesByDepth = [];
      var nodes = [];
      for (var depth in model2.nodesByDepth) {
        nodesByDepth.push(model2.nodesByDepth[depth]);
      }
      try {
        for (var nodesByDepth_1 = __values(nodesByDepth), nodesByDepth_1_1 = nodesByDepth_1.next(); !nodesByDepth_1_1.done; nodesByDepth_1_1 = nodesByDepth_1.next()) {
          var depthNodes = nodesByDepth_1_1.value;
          if (depthNodes.length > 1 || depthNodes.length === 1 && depthNodes[0].inboundLayers.length > 1) {
            sequentialLike = false;
            break;
          }
          nodes.push.apply(nodes, __spreadArray([], __read(depthNodes), false));
        }
      } catch (e_1_1) {
        e_12 = { error: e_1_1 };
      } finally {
        try {
          if (nodesByDepth_1_1 && !nodesByDepth_1_1.done && (_a2 = nodesByDepth_1.return)) _a2.call(nodesByDepth_1);
        } finally {
          if (e_12) throw e_12.error;
        }
      }
      if (sequentialLike) {
        try {
          for (var _d = __values(model2.layers), _e = _d.next(); !_e.done; _e = _d.next()) {
            var layer = _e.value;
            var flag = false;
            try {
              for (var _f = (e_3 = void 0, __values(layer.inboundNodes)), _g = _f.next(); !_g.done; _g = _f.next()) {
                var node = _g.value;
                if (nodes.indexOf(node) !== -1) {
                  if (flag) {
                    sequentialLike = false;
                    break;
                  } else {
                    flag = true;
                  }
                }
              }
            } catch (e_3_1) {
              e_3 = { error: e_3_1 };
            } finally {
              try {
                if (_g && !_g.done && (_c = _f.return)) _c.call(_f);
              } finally {
                if (e_3) throw e_3.error;
              }
            }
            if (!sequentialLike) {
              break;
            }
          }
        } catch (e_2_1) {
          e_2 = { error: e_2_1 };
        } finally {
          try {
            if (_e && !_e.done && (_b = _d.return)) _b.call(_d);
          } finally {
            if (e_2) throw e_2.error;
          }
        }
      }
      return sequentialLike;
    }
    function printRow(fields, positions, printFn) {
      if (printFn === void 0) {
        printFn = console.log;
      }
      var line = "";
      for (var i = 0; i < fields.length; ++i) {
        if (i > 0) {
          line = line.slice(0, line.length - 1) + " ";
        }
        line += fields[i];
        line = line.slice(0, positions[i]);
        line += " ".repeat(positions[i] - line.length);
      }
      printFn(line);
    }
    function printLayerSummary(layer, positions, printFn) {
      var outputShape;
      var inputShape;
      try {
        inputShape = layer.inboundNodes.map(function(x) {
          return JSON.stringify(x.inputShapes);
        }).join(",");
      } catch (err) {
        inputShape = "multiple";
      }
      try {
        outputShape = JSON.stringify(layer.outputShape);
      } catch (err) {
        outputShape = "multiple";
      }
      var name = layer.name;
      var className = layer.getClassName();
      var fields = [
        "".concat(name, " (").concat(className, ")"),
        inputShape,
        outputShape,
        layer.countParams().toString()
      ];
      printRow(fields, positions, printFn);
    }
    function printLayerSummaryWithConnections(layer, positions, relevantNodes, printFn) {
      var e_4, _a2;
      var outputShape;
      var inputShape;
      try {
        inputShape = layer.inboundNodes.map(function(x) {
          return JSON.stringify(x.inputShapes);
        }).join(",");
      } catch (err) {
        inputShape = "multiple";
      }
      try {
        outputShape = JSON.stringify(layer.outputShape);
      } catch (err) {
        outputShape = "multiple";
      }
      var connections = [];
      try {
        for (var _b = __values(layer.inboundNodes), _c = _b.next(); !_c.done; _c = _b.next()) {
          var node = _c.value;
          if (relevantNodes != null && relevantNodes.length > 0 && relevantNodes.indexOf(node) === -1) {
            continue;
          }
          for (var i = 0; i < node.inboundLayers.length; ++i) {
            var inboundLayer = node.inboundLayers[i].name;
            var inboundLayerIndex = node.nodeIndices[i];
            var inboundTensorIndex = node.tensorIndices[i];
            connections.push("".concat(inboundLayer, "[").concat(inboundLayerIndex, "][").concat(inboundTensorIndex, "]"));
          }
        }
      } catch (e_4_1) {
        e_4 = { error: e_4_1 };
      } finally {
        try {
          if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
        } finally {
          if (e_4) throw e_4.error;
        }
      }
      var name = layer.name;
      var className = layer.getClassName();
      var firstConnection = connections.length === 0 ? "" : connections[0];
      var fields = [
        "".concat(name, " (").concat(className, ")"),
        inputShape,
        outputShape,
        layer.countParams().toString(),
        firstConnection
      ];
      printRow(fields, positions, printFn);
      for (var i = 1; i < connections.length; ++i) {
        printRow(["", "", "", "", connections[i]], positions, printFn);
      }
    }
    function isArrayItemInputOrOutputName(key, index, value) {
      return (key === "inboundNodes" || key === "outputLayers" || key === "inputLayers") && index === 0 && typeof value === "string";
    }
    function convertPythonicToTs(pythonicConfig, key) {
      var e_12, _a2;
      if (pythonicConfig === null) {
        return null;
      } else if (typeof pythonicConfig === "string") {
        return toCamelCase(pythonicConfig);
      } else if (typeof pythonicConfig === "number" || typeof pythonicConfig === "boolean") {
        return pythonicConfig;
      } else if (pythonicConfig instanceof Array) {
        var tsArray = [];
        var arrayLength = pythonicConfig.length;
        for (var i = 0; i < arrayLength; ++i) {
          var item = pythonicConfig[i];
          if (isArrayItemInputOrOutputName(key, i, item)) {
            tsArray.push(item);
          } else {
            tsArray.push(convertPythonicToTs(item, key));
          }
        }
        return tsArray;
      } else {
        var tsDict = {};
        try {
          for (var _b = __values(Object.keys(pythonicConfig)), _c = _b.next(); !_c.done; _c = _b.next()) {
            var pythonicKey = _c.value;
            var pythonicValue = pythonicConfig[pythonicKey];
            if (pythonicKey === "name" && typeof pythonicValue === "string") {
              tsDict[pythonicKey] = pythonicValue;
            } else {
              var tsKey = toCamelCase(pythonicKey);
              tsDict[tsKey] = convertPythonicToTs(pythonicValue, tsKey);
            }
          }
        } catch (e_1_1) {
          e_12 = { error: e_1_1 };
        } finally {
          try {
            if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
          } finally {
            if (e_12) throw e_12.error;
          }
        }
        return tsDict;
      }
    }
    function convertTsToPythonic(tsConfig, key) {
      var e_2, _a2;
      if (tsConfig === null || tsConfig === void 0) {
        return null;
      } else if (typeof tsConfig === "string") {
        return toSnakeCase(tsConfig);
      } else if (typeof tsConfig === "number" || typeof tsConfig === "boolean") {
        return tsConfig;
      } else if (tsConfig instanceof Array) {
        var pyArray = [];
        var arrayLength = tsConfig.length;
        for (var i = 0; i < arrayLength; ++i) {
          var item = tsConfig[i];
          if (isArrayItemInputOrOutputName(key, i, item)) {
            pyArray.push(item);
          } else {
            pyArray.push(convertTsToPythonic(item, key));
          }
        }
        return pyArray;
      } else {
        var pyDict = {};
        try {
          for (var _b = __values(Object.keys(tsConfig)), _c = _b.next(); !_c.done; _c = _b.next()) {
            var tsKey = _c.value;
            var tsValue = tsConfig[tsKey];
            var pyKey = toSnakeCase(tsKey);
            if ((tsKey === "name" || tsKey === "className") && typeof tsValue === "string") {
              pyDict[pyKey] = tsValue;
            } else {
              pyDict[pyKey] = convertTsToPythonic(tsValue, tsKey);
            }
          }
        } catch (e_2_1) {
          e_2 = { error: e_2_1 };
        } finally {
          try {
            if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
          } finally {
            if (e_2) throw e_2.error;
          }
        }
        return pyDict;
      }
    }
    var version = "4.22.0";
    var isKerasSavedModelFormat = function(weights) {
      var keys = Object.keys(weights);
      if (keys.length === 0) {
        return false;
      }
      var key = keys[0].split("/");
      return !isNaN(parseInt(key[key.length - 1], 10));
    };
    var Container = (
      /** @class */
      function(_super) {
        __extends(Container2, _super);
        function Container2(args) {
          var e_12, _a2, e_2, _b, e_3, _c, e_4, _d, e_5, _e, e_6, _f, e_7, _g, e_8, _h, e_9, _j, e_10, _k, e_11, _l, e_122, _m;
          var _this = (
            // No args passed to super's constructor.
            _super.call(this, {}) || this
          );
          _this.containerNodes = /* @__PURE__ */ new Set();
          _this.name = args.name;
          if (_this.name == null) {
            var prefix = _this.getClassName().toLowerCase();
            _this.name = getUid(prefix);
          }
          _this.supportsMasking = false;
          _this.trainable_ = true;
          if (Array.isArray(args.inputs)) {
            _this.inputs = args.inputs.slice();
          } else {
            _this.inputs = [args.inputs];
          }
          if (Array.isArray(args.outputs)) {
            _this.outputs = args.outputs.slice();
          } else {
            _this.outputs = [args.outputs];
          }
          if (unique(_this.inputs).length !== _this.inputs.length) {
            throw new ValueError("The list of inputs passed to the model is redundant. All inputs should only appear once. Found: " + "".concat(_this.inputs.map(function(x2) {
              return x2.name;
            })));
          }
          if (unique(_this.outputs).length !== _this.outputs.length) {
            console.warn("The list of outputs passed to the model is redundant. All outputs should only appear once. Found: " + "".concat(_this.outputs.map(function(x2) {
              return x2.name;
            })));
          }
          _this.inputLayers = [];
          _this.inputLayersNodeIndices = [];
          _this.inputLayersTensorIndices = [];
          _this.outputLayers = [];
          _this.outputLayersNodeIndices = [];
          _this.outputLayersTensorIndices = [];
          _this.layers = [];
          _this.internalContainerRefs = [];
          try {
            for (var _o = __values(_this.outputs), _p = _o.next(); !_p.done; _p = _o.next()) {
              var x = _p.value;
              var layer = x.sourceLayer;
              var nodeIndex = x.nodeIndex;
              var tensorIndex = x.tensorIndex;
              _this.outputLayers.push(layer);
              _this.outputLayersNodeIndices.push(nodeIndex);
              _this.outputLayersTensorIndices.push(tensorIndex);
            }
          } catch (e_1_1) {
            e_12 = { error: e_1_1 };
          } finally {
            try {
              if (_p && !_p.done && (_a2 = _o.return)) _a2.call(_o);
            } finally {
              if (e_12) throw e_12.error;
            }
          }
          try {
            for (var _q = __values(_this.inputs), _r = _q.next(); !_r.done; _r = _q.next()) {
              var x = _r.value;
              var layer = x.sourceLayer;
              var nodeIndex = x.nodeIndex;
              var tensorIndex = x.tensorIndex;
              assert$1(nodeIndex === 0, "input layer has >1 nodes");
              assert$1(tensorIndex === 0, "input layer has >1 tensors");
              _this.inputLayers.push(layer);
              _this.inputLayersNodeIndices.push(nodeIndex);
              _this.inputLayersTensorIndices.push(tensorIndex);
            }
          } catch (e_2_1) {
            e_2 = { error: e_2_1 };
          } finally {
            try {
              if (_r && !_r.done && (_b = _q.return)) _b.call(_q);
            } finally {
              if (e_2) throw e_2.error;
            }
          }
          _this.inputNames = [];
          _this.outputNames = [];
          _this.feedInputShapes = [];
          _this.feedInputNames = [];
          _this.feedOutputNames = [];
          for (var i = 0; i < _this.inputLayers.length; i++) {
            var layer = _this.inputLayers[i];
            if (!(layer instanceof InputLayer)) {
              throw new TypeError("Input layers to a LayersModel must be InputLayer objects. " + "Received inputs: ".concat(args.inputs, ". ") + "Input ".concat(i, " (0-based) originates ") + "from layer type ".concat(layer.getClassName(), "."));
            }
            _this.inputNames.push(layer.name);
            _this.feedInputShapes.push(layer.batchInputShape);
            _this.feedInputNames.push(layer.name);
          }
          try {
            for (var _s = __values(_this.outputLayers), _t = _s.next(); !_t.done; _t = _s.next()) {
              var layer = _t.value;
              _this.outputNames.push(layer.name);
            }
          } catch (e_3_1) {
            e_3 = { error: e_3_1 };
          } finally {
            try {
              if (_t && !_t.done && (_c = _s.return)) _c.call(_s);
            } finally {
              if (e_3) throw e_3.error;
            }
          }
          _this.internalInputShapes = _this.inputs.map(function(x2) {
            return x2.shape;
          });
          _this.internalOutputShapes = _this.outputs.map(function(x2) {
            return x2.shape;
          });
          var nodesDepths = {};
          var nodeIDToNode = {};
          var layersDepths = {};
          var layerIDToLayer = {};
          var layerIndices = {};
          var nodesInDecreasingDepth = [];
          var buildMapOfGraph = function(tensor, finishedNodes2, nodesInProgress2, layer2, nodeIndex2, tensorIndex2) {
            if (layer2 == null || nodeIndex2 == null || tensorIndex2 == null) {
              layer2 = tensor.sourceLayer;
              nodeIndex2 = tensor.nodeIndex;
              tensorIndex2 = tensor.tensorIndex;
            }
            var node2 = layer2.inboundNodes[nodeIndex2];
            if (nodesInProgress2.indexOf(node2) !== -1) {
              throw new RuntimeError("The tensor ".concat(tensor.name, ' at layer "').concat(layer2.name, '" ') + "is part of a cycle.");
            }
            if (finishedNodes2.indexOf(node2) !== -1) {
              return;
            }
            _this.containerNodes.add(Container2.nodeKey(layer2, nodeIndex2));
            if (!(layer2.id in layerIndices)) {
              layerIndices[layer2.id] = Object.keys(layerIndices).length;
            }
            if (nodesInProgress2.indexOf(node2) === -1) {
              nodesInProgress2.push(node2);
            }
            var numInboundLayers = node2.inboundLayers.length;
            for (var i2 = 0; i2 < numInboundLayers; i2++) {
              var x2 = node2.inputTensors[i2];
              var layer_1 = node2.inboundLayers[i2];
              var nodeIndex_1 = node2.nodeIndices[i2];
              var tensorIndex_1 = node2.tensorIndices[i2];
              buildMapOfGraph(x2, finishedNodes2, nodesInProgress2, layer_1, nodeIndex_1, tensorIndex_1);
            }
            finishedNodes2.push(node2);
            while (nodesInProgress2.indexOf(node2) >= 0) {
              nodesInProgress2.splice(nodesInProgress2.indexOf(node2), 1);
            }
            nodesInDecreasingDepth.push(node2);
          };
          var finishedNodes = [];
          var nodesInProgress = [];
          try {
            for (var _u = __values(_this.outputs), _v = _u.next(); !_v.done; _v = _u.next()) {
              var x = _v.value;
              buildMapOfGraph(x, finishedNodes, nodesInProgress);
            }
          } catch (e_4_1) {
            e_4 = { error: e_4_1 };
          } finally {
            try {
              if (_v && !_v.done && (_d = _u.return)) _d.call(_u);
            } finally {
              if (e_4) throw e_4.error;
            }
          }
          var reversedNodesInDecreasingDepth = nodesInDecreasingDepth.slice().reverse();
          try {
            for (var reversedNodesInDecreasingDepth_1 = __values(reversedNodesInDecreasingDepth), reversedNodesInDecreasingDepth_1_1 = reversedNodesInDecreasingDepth_1.next(); !reversedNodesInDecreasingDepth_1_1.done; reversedNodesInDecreasingDepth_1_1 = reversedNodesInDecreasingDepth_1.next()) {
              var node = reversedNodesInDecreasingDepth_1_1.value;
              nodeIDToNode[node.id] = node;
              if (!(node.id in nodesDepths)) {
                nodesDepths[node.id] = 0;
              }
              var depth = nodesDepths[node.id];
              var previousDepth = layersDepths[node.outboundLayer.id] == null ? 0 : layersDepths[node.outboundLayer.id];
              depth = Math.max(depth, previousDepth);
              layersDepths[node.outboundLayer.id] = depth;
              layerIDToLayer[node.outboundLayer.id] = node.outboundLayer;
              nodesDepths[node.id] = depth;
              for (var i = 0; i < node.inboundLayers.length; i++) {
                var inboundLayer = node.inboundLayers[i];
                var nodeIndex = node.nodeIndices[i];
                var inboundNode = inboundLayer.inboundNodes[nodeIndex];
                var previousDepth_1 = nodesDepths[inboundNode.id] == null ? 0 : nodesDepths[inboundNode.id];
                nodesDepths[inboundNode.id] = Math.max(depth + 1, previousDepth_1);
                nodeIDToNode[inboundNode.id] = inboundNode;
              }
            }
          } catch (e_5_1) {
            e_5 = { error: e_5_1 };
          } finally {
            try {
              if (reversedNodesInDecreasingDepth_1_1 && !reversedNodesInDecreasingDepth_1_1.done && (_e = reversedNodesInDecreasingDepth_1.return)) _e.call(reversedNodesInDecreasingDepth_1);
            } finally {
              if (e_5) throw e_5.error;
            }
          }
          var nodesByDepth = {};
          for (var nodeID in nodesDepths) {
            var depth = nodesDepths[nodeID];
            if (!(depth in nodesByDepth)) {
              nodesByDepth[depth] = [];
            }
            nodesByDepth[depth].push(nodeIDToNode[nodeID]);
          }
          var layersByDepth = {};
          for (var layerID in layersDepths) {
            var depth = layersDepths[layerID];
            if (!(depth in layersByDepth)) {
              layersByDepth[depth] = [];
            }
            layersByDepth[depth].push(layerIDToLayer[layerID]);
          }
          var depthKeys = Object.keys(layersByDepth).map(function(x2) {
            return parseInt(x2, 10);
          }).sort(reverseNumberCompare);
          _this.layers = [];
          try {
            for (var depthKeys_1 = __values(depthKeys), depthKeys_1_1 = depthKeys_1.next(); !depthKeys_1_1.done; depthKeys_1_1 = depthKeys_1.next()) {
              var depth = depthKeys_1_1.value;
              var layersForDepth = layersByDepth[depth];
              layersForDepth.sort(function(a, b) {
                var aIndex = layerIndices[a.id];
                var bIndex = layerIndices[b.id];
                if (aIndex < bIndex) {
                  return -1;
                }
                if (aIndex > bIndex) {
                  return 1;
                }
                return 0;
              });
              try {
                for (var layersForDepth_1 = (e_7 = void 0, __values(layersForDepth)), layersForDepth_1_1 = layersForDepth_1.next(); !layersForDepth_1_1.done; layersForDepth_1_1 = layersForDepth_1.next()) {
                  var layer = layersForDepth_1_1.value;
                  if (layer instanceof Container2) {
                    _this.internalContainerRefs.push(layer);
                  }
                  _this.layers.push(layer);
                }
              } catch (e_7_1) {
                e_7 = { error: e_7_1 };
              } finally {
                try {
                  if (layersForDepth_1_1 && !layersForDepth_1_1.done && (_g = layersForDepth_1.return)) _g.call(layersForDepth_1);
                } finally {
                  if (e_7) throw e_7.error;
                }
              }
            }
          } catch (e_6_1) {
            e_6 = { error: e_6_1 };
          } finally {
            try {
              if (depthKeys_1_1 && !depthKeys_1_1.done && (_f = depthKeys_1.return)) _f.call(depthKeys_1);
            } finally {
              if (e_6) throw e_6.error;
            }
          }
          _this.layersByDepth = layersByDepth;
          depthKeys = Object.keys(nodesByDepth).map(function(x2) {
            return parseInt(x2, 10);
          }).sort(reverseNumberCompare);
          var computableTensors = _this.inputs.slice();
          var layersWithCompleteInput = [];
          try {
            for (var depthKeys_2 = __values(depthKeys), depthKeys_2_1 = depthKeys_2.next(); !depthKeys_2_1.done; depthKeys_2_1 = depthKeys_2.next()) {
              var depth = depthKeys_2_1.value;
              try {
                for (var _w = (e_9 = void 0, __values(nodesByDepth[depth])), _x = _w.next(); !_x.done; _x = _w.next()) {
                  var node = _x.value;
                  var layer = node.outboundLayer;
                  if (layer != null) {
                    try {
                      for (var _y = (e_10 = void 0, __values(node.inputTensors)), _z = _y.next(); !_z.done; _z = _y.next()) {
                        var x = _z.value;
                        if (computableTensors.indexOf(x) === -1) {
                          throw new RuntimeError("Graph disconnected: cannot obtain value for tensor ".concat(x) + ' at layer "'.concat(layer.name, '". ') + "The following previous layers were accessed without " + "issue: ".concat(layersWithCompleteInput));
                        }
                      }
                    } catch (e_10_1) {
                      e_10 = { error: e_10_1 };
                    } finally {
                      try {
                        if (_z && !_z.done && (_k = _y.return)) _k.call(_y);
                      } finally {
                        if (e_10) throw e_10.error;
                      }
                    }
                    try {
                      for (var _0 = (e_11 = void 0, __values(node.outputTensors)), _1 = _0.next(); !_1.done; _1 = _0.next()) {
                        var x = _1.value;
                        computableTensors.push(x);
                      }
                    } catch (e_11_1) {
                      e_11 = { error: e_11_1 };
                    } finally {
                      try {
                        if (_1 && !_1.done && (_l = _0.return)) _l.call(_0);
                      } finally {
                        if (e_11) throw e_11.error;
                      }
                    }
                    layersWithCompleteInput.push(layer.name);
                  }
                }
              } catch (e_9_1) {
                e_9 = { error: e_9_1 };
              } finally {
                try {
                  if (_x && !_x.done && (_j = _w.return)) _j.call(_w);
                } finally {
                  if (e_9) throw e_9.error;
                }
              }
            }
          } catch (e_8_1) {
            e_8 = { error: e_8_1 };
          } finally {
            try {
              if (depthKeys_2_1 && !depthKeys_2_1.done && (_h = depthKeys_2.return)) _h.call(depthKeys_2);
            } finally {
              if (e_8) throw e_8.error;
            }
          }
          _this.nodesByDepth = nodesByDepth;
          var allNames = _this.layers.map(function(x2) {
            return x2.name;
          });
          var _loop_1 = function(name2) {
            var numOccurrences = allNames.filter(function(x2) {
              return x2 === name2;
            }).length;
            if (numOccurrences !== 1) {
              throw new RuntimeError('The name "'.concat(name2, '" is used ').concat(numOccurrences, " times ") + "in the model. All layer names should be unique. Layer names: " + JSON.stringify(allNames));
            }
          };
          try {
            for (var allNames_1 = __values(allNames), allNames_1_1 = allNames_1.next(); !allNames_1_1.done; allNames_1_1 = allNames_1.next()) {
              var name = allNames_1_1.value;
              _loop_1(name);
            }
          } catch (e_12_1) {
            e_122 = { error: e_12_1 };
          } finally {
            try {
              if (allNames_1_1 && !allNames_1_1.done && (_m = allNames_1.return)) _m.call(allNames_1);
            } finally {
              if (e_122) throw e_122.error;
            }
          }
          _this.outboundNodes = [];
          _this.inboundNodes = [];
          new Node({
            outboundLayer: _this,
            inboundLayers: [],
            nodeIndices: [],
            tensorIndices: [],
            inputTensors: _this.inputs,
            outputTensors: _this.outputs,
            inputMasks: _this.inputs.map(function(x2) {
              return null;
            }),
            outputMasks: _this.outputs.map(function(x2) {
              return null;
            }),
            inputShapes: _this.inputs.map(function(x2) {
              return x2.shape;
            }),
            outputShapes: _this.outputs.map(function(x2) {
              return x2.shape;
            })
          });
          _this.built = true;
          _this._refCount = 1;
          return _this;
        }
        Container2.prototype.assertNotDisposed = function() {
          if (this._refCount === 0) {
            throw new Error("Container '".concat(this.name, "' is already disposed."));
          }
        };
        Container2.prototype.dispose = function() {
          var e_13, _a2, e_14, _b;
          this.assertNotDisposed();
          var result = { refCountAfterDispose: null, numDisposedVariables: 0 };
          if (--this._refCount === 0) {
            try {
              for (var _c = __values(this.layers), _d = _c.next(); !_d.done; _d = _c.next()) {
                var layer = _d.value;
                result.numDisposedVariables += layer.dispose().numDisposedVariables;
              }
            } catch (e_13_1) {
              e_13 = { error: e_13_1 };
            } finally {
              try {
                if (_d && !_d.done && (_a2 = _c.return)) _a2.call(_c);
              } finally {
                if (e_13) throw e_13.error;
              }
            }
            try {
              for (var _e = __values(this.internalContainerRefs), _f = _e.next(); !_f.done; _f = _e.next()) {
                var container = _f.value;
                result.numDisposedVariables += container.dispose().numDisposedVariables;
              }
            } catch (e_14_1) {
              e_14 = { error: e_14_1 };
            } finally {
              try {
                if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
              } finally {
                if (e_14) throw e_14.error;
              }
            }
          }
          result.refCountAfterDispose = this._refCount;
          return result;
        };
        Object.defineProperty(Container2.prototype, "trainable", {
          get: function() {
            return this.trainable_;
          },
          set: function(trainable) {
            this.layers.forEach(function(layer) {
              layer._trainableWeights.forEach(function(w) {
                return w.trainable = trainable;
              });
            });
            this.trainable_ = trainable;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(Container2.prototype, "trainableWeights", {
          get: function() {
            var e_15, _a2;
            if (this._trainableWeights.length > 0) {
              throw new ValueError("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 [];
            }
            var weights = [];
            try {
              for (var _b = __values(this.layers), _c = _b.next(); !_c.done; _c = _b.next()) {
                var layer = _c.value;
                weights = weights.concat(layer.trainableWeights);
              }
            } catch (e_15_1) {
              e_15 = { error: e_15_1 };
            } finally {
              try {
                if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
              } finally {
                if (e_15) throw e_15.error;
              }
            }
            return weights;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(Container2.prototype, "nonTrainableWeights", {
          get: function() {
            var e_16, _a2, e_17, _b;
            var weights = [];
            try {
              for (var _c = __values(this.layers), _d = _c.next(); !_d.done; _d = _c.next()) {
                var layer = _d.value;
                weights.push.apply(weights, __spreadArray([], __read(layer.nonTrainableWeights), false));
              }
            } catch (e_16_1) {
              e_16 = { error: e_16_1 };
            } finally {
              try {
                if (_d && !_d.done && (_a2 = _c.return)) _a2.call(_c);
              } finally {
                if (e_16) throw e_16.error;
              }
            }
            if (!this.trainable) {
              var trainableWeights = [];
              try {
                for (var _e = __values(this.layers), _f = _e.next(); !_f.done; _f = _e.next()) {
                  var layer = _f.value;
                  trainableWeights.push.apply(trainableWeights, __spreadArray([], __read(layer.trainableWeights), false));
                }
              } catch (e_17_1) {
                e_17 = { error: e_17_1 };
              } finally {
                try {
                  if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
                } finally {
                  if (e_17) throw e_17.error;
                }
              }
              return trainableWeights.concat(weights);
            }
            return weights;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(Container2.prototype, "weights", {
          get: function() {
            return this.trainableWeights.concat(this.nonTrainableWeights);
          },
          enumerable: false,
          configurable: true
        });
        Container2.prototype.loadWeights = function(weights, strict) {
          var e_18, _a2, e_19, _b;
          if (strict === void 0) {
            strict = true;
          }
          var nameToWeight = {};
          var totalWeightsCount = 0;
          var modelIsKerasSavedModelFormat = isKerasSavedModelFormat(weights);
          if (modelIsKerasSavedModelFormat) {
            this.parseWeights(weights);
          }
          try {
            for (var _c = __values(this.layers), _d = _c.next(); !_d.done; _d = _c.next()) {
              var layer = _d.value;
              try {
                for (var _e = (e_19 = void 0, __values(layer.weights.entries())), _f = _e.next(); !_f.done; _f = _e.next()) {
                  var _g = __read(_f.value, 2), index = _g[0], weight = _g[1];
                  var parsedName = modelIsKerasSavedModelFormat ? "".concat(weight.name.split("/").slice(0, -1).join("/") + "/").concat(index) : weight.originalName;
                  if (nameToWeight[parsedName] != null) {
                    throw new ValueError("Duplicate weight name: ".concat(parsedName));
                  }
                  nameToWeight[parsedName] = weight;
                  totalWeightsCount++;
                }
              } catch (e_19_1) {
                e_19 = { error: e_19_1 };
              } finally {
                try {
                  if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
                } finally {
                  if (e_19) throw e_19.error;
                }
              }
            }
          } catch (e_18_1) {
            e_18 = { error: e_18_1 };
          } finally {
            try {
              if (_d && !_d.done && (_a2 = _c.return)) _a2.call(_c);
            } finally {
              if (e_18) throw e_18.error;
            }
          }
          var weightValueTuples = [];
          for (var name in weights) {
            var validatedName = name;
            if (nameToWeight[name] == null) {
              var tokens = name.split("/");
              var shortenNameArray = tokens.slice(0, -2).concat([tokens[tokens.length - 1]]);
              validatedName = shortenNameArray.join("/");
            }
            if (nameToWeight[validatedName] != null) {
              weightValueTuples.push([nameToWeight[validatedName], weights[name]]);
            } else if (strict) {
              throw new ValueError("Provided weight data has no target variable: ".concat(name));
            }
            delete nameToWeight[validatedName];
          }
          if (strict) {
            var unsetNames = [];
            for (var name in nameToWeight) {
              unsetNames.push(name);
            }
            if (unsetNames.length > 0) {
              throw new ValueError("".concat(unsetNames.length, " of ").concat(totalWeightsCount, " weights are not set: ") + "".concat(unsetNames));
            }
          }
          batchSetValue(weightValueTuples);
        };
        Container2.prototype.parseWeights = function(weights) {
          var _loop_2 = function(key2) {
            var listParts = key2.split("/");
            var list = ["vars", "layer_checkpoint_dependencies"];
            var newKey = listParts.map(function(str) {
              if (str.startsWith("_")) {
                return str.slice(1);
              }
              return str;
            }).filter(function(str) {
              return !list.includes(str);
            }).join("/");
            if (newKey !== key2) {
              weights[newKey] = weights[key2];
              delete weights[key2];
            }
          };
          for (var key in Object.keys(weights)) {
            _loop_2(key);
          }
        };
        Container2.prototype.updatedConfig = function() {
          var theConfig = this.getConfig();
          var modelConfig = {};
          modelConfig["className"] = this.getClassName();
          modelConfig["config"] = theConfig;
          modelConfig["kerasVersion"] = "tfjs-layers ".concat(version);
          modelConfig["backend"] = "TensorFlow.js";
          return modelConfig;
        };
        Container2.prototype.toJSON = function(unused, returnString) {
          if (returnString === void 0) {
            returnString = true;
          }
          var modelConfig = convertTsToPythonic(this.updatedConfig());
          return returnString ? JSON.stringify(modelConfig) : modelConfig;
        };
        Container2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            inputs = toList(inputs);
            var feedDict = new FeedDict();
            for (var i = 0; i < _this.inputs.length; ++i) {
              feedDict.add(_this.inputs[i], inputs[i]);
            }
            return execute(_this.outputs, feedDict, kwargs);
          });
        };
        Container2.prototype.computeMask = function(inputs, mask) {
          var _this = this;
          return tfc.tidy(function() {
            inputs = toList(inputs);
            var masks;
            if (mask == null) {
              masks = pyListRepeat(null, inputs.length);
            } else {
              masks = toList(mask);
            }
            return _this.runInternalGraph(inputs, masks)[1];
          });
        };
        Container2.prototype.computeOutputShape = function(inputShape) {
          var e_20, _a2, e_21, _b;
          var inputShapes = normalizeShapeList(inputShape);
          if (inputShapes.length !== this.inputLayers.length) {
            throw new ValueError("Invalid inputShape argument ".concat(inputShape, ": ") + "model has ".concat(this.inputLayers.length, " tensor inputs."));
          }
          var layersToOutputShapes = {};
          for (var i = 0; i < inputShapes.length; i++) {
            var layer = this.inputLayers[i];
            var inputShape_1 = inputShapes[i];
            var shapeKey = layer.name + "_0_0";
            layersToOutputShapes[shapeKey] = inputShape_1;
          }
          var depthKeys = Object.keys(this.nodesByDepth).map(function(x) {
            return parseInt(x, 10);
          }).sort(reverseNumberCompare);
          if (depthKeys.length > 1) {
            try {
              for (var depthKeys_3 = __values(depthKeys), depthKeys_3_1 = depthKeys_3.next(); !depthKeys_3_1.done; depthKeys_3_1 = depthKeys_3.next()) {
                var depth = depthKeys_3_1.value;
                var nodes = this.nodesByDepth[depth];
                try {
                  for (var nodes_1 = (e_21 = void 0, __values(nodes)), nodes_1_1 = nodes_1.next(); !nodes_1_1.done; nodes_1_1 = nodes_1.next()) {
                    var node = nodes_1_1.value;
                    var layer = node.outboundLayer;
                    if (this.inputLayers.map(function(x) {
                      return x.id;
                    }).indexOf(layer.id) !== -1) {
                      continue;
                    }
                    var inputShapes_1 = [];
                    for (var j = 0; j < node.inboundLayers.length; j++) {
                      var inboundLayer = node.inboundLayers[j];
                      var nodeIndex_2 = node.nodeIndices[j];
                      var tensorIndex = node.tensorIndices[j];
                      var shapeKey = "".concat(inboundLayer.name, "_").concat(nodeIndex_2, "_").concat(tensorIndex);
                      var inputShape_2 = layersToOutputShapes[shapeKey];
                      inputShapes_1.push(inputShape_2);
                    }
                    var outputShape = layer.computeOutputShape(singletonOrArray(inputShapes_1));
                    var outputShapes_1 = normalizeShapeList(outputShape);
                    var nodeIndex = layer.inboundNodes.indexOf(node);
                    for (var j = 0; j < outputShapes_1.length; j++) {
                      var shapeKey = "".concat(layer.name, "_").concat(nodeIndex, "_").concat(j);
                      layersToOutputShapes[shapeKey] = outputShapes_1[j];
                    }
                  }
                } catch (e_21_1) {
                  e_21 = { error: e_21_1 };
                } finally {
                  try {
                    if (nodes_1_1 && !nodes_1_1.done && (_b = nodes_1.return)) _b.call(nodes_1);
                  } finally {
                    if (e_21) throw e_21.error;
                  }
                }
              }
            } catch (e_20_1) {
              e_20 = { error: e_20_1 };
            } finally {
              try {
                if (depthKeys_3_1 && !depthKeys_3_1.done && (_a2 = depthKeys_3.return)) _a2.call(depthKeys_3);
              } finally {
                if (e_20) throw e_20.error;
              }
            }
          }
          var outputShapes = [];
          var outputShapeKeys = [];
          for (var i = 0; i < this.outputLayers.length; i++) {
            var layer = this.outputLayers[i];
            var nodeIndex = this.outputLayersNodeIndices[i];
            var tensorIndex = this.outputLayersTensorIndices[i];
            var shapeKey = "".concat(layer.name, "_").concat(nodeIndex, "_").concat(tensorIndex);
            outputShapeKeys.push(shapeKey);
          }
          for (var i = 0; i < outputShapeKeys.length; i++) {
            var key = outputShapeKeys[i];
            assert$1(key in layersToOutputShapes);
            outputShapes.push(layersToOutputShapes[key]);
          }
          return singletonOrArray(outputShapes);
        };
        Container2.prototype.runInternalGraph = function(inputs, masks) {
          var e_22, _a2, e_23, _b, e_24, _c, e_25, _d;
          if (masks == null) {
            masks = pyListRepeat(null, inputs.length);
          }
          var tensorMap = {};
          for (var i = 0; i < this.inputs.length; ++i) {
            var x = this.inputs[i];
            var y = inputs[i];
            var mask = masks[i];
            tensorMap[x.id] = [y, mask];
          }
          var depthKeys = Object.keys(this.nodesByDepth).map(function(x2) {
            return parseInt(x2, 10);
          }).sort(reverseNumberCompare);
          try {
            for (var depthKeys_4 = __values(depthKeys), depthKeys_4_1 = depthKeys_4.next(); !depthKeys_4_1.done; depthKeys_4_1 = depthKeys_4.next()) {
              var depth = depthKeys_4_1.value;
              var nodes = this.nodesByDepth[depth];
              try {
                for (var nodes_2 = (e_23 = void 0, __values(nodes)), nodes_2_1 = nodes_2.next(); !nodes_2_1.done; nodes_2_1 = nodes_2.next()) {
                  var node = nodes_2_1.value;
                  var layer = node.outboundLayer;
                  var referenceInputTensors = node.inputTensors;
                  var referenceOutputTensors = node.outputTensors;
                  var computedData = new Array();
                  try {
                    for (var referenceInputTensors_1 = (e_24 = void 0, __values(referenceInputTensors)), referenceInputTensors_1_1 = referenceInputTensors_1.next(); !referenceInputTensors_1_1.done; referenceInputTensors_1_1 = referenceInputTensors_1.next()) {
                      var x = referenceInputTensors_1_1.value;
                      if (x.id in tensorMap) {
                        computedData.push(tensorMap[x.id]);
                      }
                    }
                  } catch (e_24_1) {
                    e_24 = { error: e_24_1 };
                  } finally {
                    try {
                      if (referenceInputTensors_1_1 && !referenceInputTensors_1_1.done && (_c = referenceInputTensors_1.return)) _c.call(referenceInputTensors_1);
                    } finally {
                      if (e_24) throw e_24.error;
                    }
                  }
                  if (computedData.length === referenceInputTensors.length) {
                    var kwargs = {};
                    var computedTensors = void 0;
                    var computedMasks = void 0;
                    var outputTensors_1 = void 0;
                    var outputMasks_1 = void 0;
                    if (node.callArgs != null) {
                      kwargs = node.callArgs;
                    }
                    if (computedData.length === 1) {
                      var _e = __read(computedData[0], 2), computedTensor = _e[0], computedMask = _e[1];
                      if (kwargs["mask"] == null) {
                        kwargs["mask"] = computedMask;
                      }
                      outputTensors_1 = toList(layer.call(computedTensor, kwargs));
                      outputMasks_1 = toList(layer.computeMask(computedTensor, computedMask));
                      computedTensors = [computedTensor];
                      computedMasks = [computedMask];
                    } else {
                      computedTensors = computedData.map(function(x2) {
                        return x2[0];
                      });
                      computedMasks = computedData.map(function(x2) {
                        return x2[1];
                      });
                      if (kwargs["mask"] == null) {
                        kwargs["mask"] = computedMasks;
                      }
                      outputTensors_1 = toList(layer.call(computedTensors, kwargs));
                      outputMasks_1 = toList(layer.computeMask(computedTensors, computedMasks));
                    }
                    if (layer.activityRegularizer) {
                      throw new NotImplementedError("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");
                    }
                    for (var i = 0; i < referenceOutputTensors.length; ++i) {
                      var x = referenceOutputTensors[i];
                      var y = outputTensors_1[i];
                      var mask = outputMasks_1[i];
                      tensorMap[x.id] = [y, mask];
                    }
                  }
                }
              } catch (e_23_1) {
                e_23 = { error: e_23_1 };
              } finally {
                try {
                  if (nodes_2_1 && !nodes_2_1.done && (_b = nodes_2.return)) _b.call(nodes_2);
                } finally {
                  if (e_23) throw e_23.error;
                }
              }
            }
          } catch (e_22_1) {
            e_22 = { error: e_22_1 };
          } finally {
            try {
              if (depthKeys_4_1 && !depthKeys_4_1.done && (_a2 = depthKeys_4.return)) _a2.call(depthKeys_4);
            } finally {
              if (e_22) throw e_22.error;
            }
          }
          var outputTensors = [];
          var outputMasks = [];
          var outputShapes = [];
          try {
            for (var _f = __values(this.outputs), _g = _f.next(); !_g.done; _g = _f.next()) {
              var x = _g.value;
              assert$1(x.id in tensorMap, "Could not compute output ".concat(x.name, " : ").concat(x.id));
              var _h = __read(tensorMap[x.id], 2), tensor = _h[0], mask = _h[1];
              outputShapes.push(tensor.shape);
              outputTensors.push(tensor);
              outputMasks.push(mask);
            }
          } catch (e_25_1) {
            e_25 = { error: e_25_1 };
          } finally {
            try {
              if (_g && !_g.done && (_d = _f.return)) _d.call(_f);
            } finally {
              if (e_25) throw e_25.error;
            }
          }
          return [outputTensors, outputMasks, outputShapes];
        };
        Container2.prototype.buildNodeConversionMap = function(layers) {
          var e_26, _a2;
          var nodeConversionMap = {};
          var keptNodes;
          try {
            for (var _b = __values(this.layers), _c = _b.next(); !_c.done; _c = _b.next()) {
              var layer = _c.value;
              keptNodes = layer instanceof Container2 ? 1 : 0;
              for (var originalNodeIndex = 0; originalNodeIndex < layer.inboundNodes.length; originalNodeIndex++) {
                var nodeKey = Container2.nodeKey(layer, originalNodeIndex);
                if (this.containerNodes.has(nodeKey)) {
                  nodeConversionMap[nodeKey] = keptNodes;
                  keptNodes += 1;
                }
              }
            }
          } catch (e_26_1) {
            e_26 = { error: e_26_1 };
          } finally {
            try {
              if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
            } finally {
              if (e_26) throw e_26.error;
            }
          }
          return nodeConversionMap;
        };
        Container2.prototype.getLayer = function(nameOrIndex, index) {
          var e_27, _a2;
          if (index != null) {
            return this.findLayer(index);
          } else {
            if (nameOrIndex == null) {
              throw new ValueError("Provide either a layer name or layer index");
            }
            if (typeof nameOrIndex === "number") {
              return this.findLayer(nameOrIndex);
            }
          }
          try {
            for (var _b = __values(this.layers), _c = _b.next(); !_c.done; _c = _b.next()) {
              var layer = _c.value;
              if (layer.name === nameOrIndex) {
                return layer;
              }
            }
          } catch (e_27_1) {
            e_27 = { error: e_27_1 };
          } finally {
            try {
              if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
            } finally {
              if (e_27) throw e_27.error;
            }
          }
          throw new ValueError("No such layer: ".concat(nameOrIndex));
        };
        Container2.prototype.findLayer = function(index) {
          if (this.layers.length <= index) {
            throw new ValueError("Was asked to retrieve layer at index ".concat(index, ", but model only ") + "has ".concat(this.layers.length, " layer(s)."));
          } else {
            return this.layers[index];
          }
        };
        Container2.prototype.calculateLosses = function() {
          var _this = this;
          return tfc.tidy(function() {
            var e_28, _a2;
            var losses = [];
            try {
              for (var _b = __values(_this.layers), _c = _b.next(); !_c.done; _c = _b.next()) {
                var layer = _c.value;
                for (var nodeIndex = 0; nodeIndex < layer.inboundNodes.length; ++nodeIndex) {
                  var nodeKey = Container2.nodeKey(layer, nodeIndex);
                  if (_this.containerNodes.has(nodeKey)) {
                    losses.push.apply(losses, __spreadArray([], __read(layer.calculateLosses()), false));
                  }
                }
              }
            } catch (e_28_1) {
              e_28 = { error: e_28_1 };
            } finally {
              try {
                if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
              } finally {
                if (e_28) throw e_28.error;
              }
            }
            return losses;
          });
        };
        Container2.prototype.getConfig = function() {
          var e_29, _a2;
          var config = { name: this.name };
          var nodeConversionMap = this.buildNodeConversionMap(this.layers);
          var layerConfigs = [];
          try {
            for (var _b = __values(this.layers), _c = _b.next(); !_c.done; _c = _b.next()) {
              var layer = _c.value;
              var layerClassName = layer.getClassName();
              var layerConfig = layer.getConfig();
              var filteredInboundNodes = [];
              for (var originalNodeIndex = 0; originalNodeIndex < layer.inboundNodes.length; originalNodeIndex++) {
                var node = layer.inboundNodes[originalNodeIndex];
                var nodeKey = Container2.nodeKey(layer, originalNodeIndex);
                var kwargs = {};
                if (this.containerNodes.has(nodeKey)) {
                  if (node.callArgs) {
                    try {
                      JSON.stringify(node.callArgs);
                      kwargs = node.callArgs;
                    } catch (err) {
                      console.warn("Layer ".concat(layer.name, " was passed ") + "non-serializable keyword arguments: " + "".concat(node.callArgs, ". They will not be included ") + "in the serialized model (and thus will be missing at deserialization time).");
                      kwargs = {};
                    }
                  }
                  if (node.inboundLayers.length > 0) {
                    var nodeData = [];
                    for (var i = 0; i < node.inboundLayers.length; i++) {
                      var inboundLayer = node.inboundLayers[i];
                      var nodeIndex = node.nodeIndices[i];
                      var tensorIndex = node.tensorIndices[i];
                      var nodeKey_1 = Container2.nodeKey(inboundLayer, nodeIndex);
                      var newNodeIndex = nodeConversionMap[nodeKey_1];
                      if (newNodeIndex == null) {
                        newNodeIndex = 0;
                      }
                      nodeData.push([inboundLayer.name, newNodeIndex, tensorIndex, kwargs]);
                    }
                    filteredInboundNodes.push(nodeData);
                  }
                }
              }
              var dict = {};
              dict["name"] = layer.name;
              dict["className"] = layerClassName;
              dict["config"] = layerConfig;
              dict["inboundNodes"] = filteredInboundNodes;
              layerConfigs.push(dict);
            }
          } catch (e_29_1) {
            e_29 = { error: e_29_1 };
          } finally {
            try {
              if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
            } finally {
              if (e_29) throw e_29.error;
            }
          }
          config["layers"] = layerConfigs;
          var modelInputs = [];
          for (var i = 0; i < this.inputLayers.length; i++) {
            var layer = this.inputLayers[i];
            var nodeIndex = this.inputLayersNodeIndices[i];
            var nodeKey = Container2.nodeKey(layer, nodeIndex);
            if (!this.containerNodes.has(nodeKey)) {
              continue;
            }
            var newNodeIndex = nodeConversionMap[nodeKey];
            if (newNodeIndex === null || newNodeIndex === void 0) {
              newNodeIndex = 0;
            }
            var tensorIndex = this.inputLayersTensorIndices[i];
            modelInputs.push([layer.name, newNodeIndex, tensorIndex]);
          }
          config["inputLayers"] = modelInputs;
          var modelOutputs = [];
          for (var i = 0; i < this.outputLayers.length; i++) {
            var layer = this.outputLayers[i];
            var nodeIndex = this.outputLayersNodeIndices[i];
            var nodeKey = Container2.nodeKey(layer, nodeIndex);
            if (!this.containerNodes.has(nodeKey)) {
              continue;
            }
            var newNodeIndex = nodeConversionMap[nodeKey];
            if (newNodeIndex === null || newNodeIndex === void 0) {
              newNodeIndex = 0;
            }
            var tensorIndex = this.outputLayersTensorIndices[i];
            modelOutputs.push([layer.name, newNodeIndex, tensorIndex]);
          }
          config["outputLayers"] = modelOutputs;
          return config;
        };
        Container2.fromConfig = function(cls, config, customObjects, fastWeightInit) {
          var e_30, _a2, e_31, _b, e_32, _c, e_33, _d, e_34, _e;
          if (fastWeightInit === void 0) {
            fastWeightInit = false;
          }
          var createdLayers = {};
          var unprocessedNodes = {};
          function addUnprocessedNode(layer2, nodeData2) {
            if (!(layer2.name in unprocessedNodes)) {
              unprocessedNodes[layer2.name] = [nodeData2];
            } else {
              unprocessedNodes[layer2.name].push(nodeData2);
            }
          }
          function processNode(layer2, nodeData2) {
            var e_35, _a3;
            var inputTensors2 = [];
            var kwargs;
            try {
              for (var nodeData_1 = __values(nodeData2), nodeData_1_1 = nodeData_1.next(); !nodeData_1_1.done; nodeData_1_1 = nodeData_1.next()) {
                var inputData = nodeData_1_1.value;
                var inboundLayerName = inputData[0];
                var inboundNodeIndex = inputData[1];
                var inboundTensorIndex = inputData[2];
                kwargs = inputData[3] == null ? {} : inputData[3];
                if (!(inboundLayerName in createdLayers)) {
                  addUnprocessedNode(layer2, nodeData2);
                  return;
                }
                var inboundLayer = createdLayers[inboundLayerName];
                if (inboundLayer.inboundNodes.length <= inboundNodeIndex) {
                  addUnprocessedNode(layer2, nodeData2);
                  return;
                }
                var inboundNode = inboundLayer.inboundNodes[inboundNodeIndex];
                inputTensors2.push(inboundNode.outputTensors[inboundTensorIndex]);
              }
            } catch (e_35_1) {
              e_35 = { error: e_35_1 };
            } finally {
              try {
                if (nodeData_1_1 && !nodeData_1_1.done && (_a3 = nodeData_1.return)) _a3.call(nodeData_1);
              } finally {
                if (e_35) throw e_35.error;
              }
            }
            if (inputTensors2.length > 0) {
              layer2.apply(singletonOrArray(inputTensors2), kwargs);
            }
          }
          function processLayer(layerData2) {
            var layerName2 = layerData2["name"];
            var layer2 = deserialize(layerData2, config["customObjects"] != null ? config["customObjects"] : {});
            layer2.setFastWeightInitDuringBuild(fastWeightInit);
            createdLayers[layerName2] = layer2;
            var inboundNodesData = layerData2["inboundNodes"];
            inboundNodesData.forEach(function(nodeData2) {
              if (!(nodeData2 instanceof Array)) {
                throw new ValueError("Corrupted configuration, expected array for nodeData: ".concat(nodeData2));
              }
              addUnprocessedNode(layer2, nodeData2);
            });
          }
          var name = config["name"];
          var layersFromConfig = config["layers"];
          try {
            for (var layersFromConfig_1 = __values(layersFromConfig), layersFromConfig_1_1 = layersFromConfig_1.next(); !layersFromConfig_1_1.done; layersFromConfig_1_1 = layersFromConfig_1.next()) {
              var layerData = layersFromConfig_1_1.value;
              processLayer(layerData);
            }
          } catch (e_30_1) {
            e_30 = { error: e_30_1 };
          } finally {
            try {
              if (layersFromConfig_1_1 && !layersFromConfig_1_1.done && (_a2 = layersFromConfig_1.return)) _a2.call(layersFromConfig_1);
            } finally {
              if (e_30) throw e_30.error;
            }
          }
          while (!isObjectEmpty(unprocessedNodes)) {
            try {
              for (var layersFromConfig_2 = (e_31 = void 0, __values(layersFromConfig)), layersFromConfig_2_1 = layersFromConfig_2.next(); !layersFromConfig_2_1.done; layersFromConfig_2_1 = layersFromConfig_2.next()) {
                var layerData = layersFromConfig_2_1.value;
                var layer = createdLayers[layerData["name"]];
                if (layer.name in unprocessedNodes) {
                  var currentUnprocessedNodesForLayer = unprocessedNodes[layer.name];
                  delete unprocessedNodes[layer.name];
                  try {
                    for (var currentUnprocessedNodesForLayer_1 = (e_32 = void 0, __values(currentUnprocessedNodesForLayer)), currentUnprocessedNodesForLayer_1_1 = currentUnprocessedNodesForLayer_1.next(); !currentUnprocessedNodesForLayer_1_1.done; currentUnprocessedNodesForLayer_1_1 = currentUnprocessedNodesForLayer_1.next()) {
                      var nodeData = currentUnprocessedNodesForLayer_1_1.value;
                      processNode(layer, nodeData);
                    }
                  } catch (e_32_1) {
                    e_32 = { error: e_32_1 };
                  } finally {
                    try {
                      if (currentUnprocessedNodesForLayer_1_1 && !currentUnprocessedNodesForLayer_1_1.done && (_c = currentUnprocessedNodesForLayer_1.return)) _c.call(currentUnprocessedNodesForLayer_1);
                    } finally {
                      if (e_32) throw e_32.error;
                    }
                  }
                }
              }
            } catch (e_31_1) {
              e_31 = { error: e_31_1 };
            } finally {
              try {
                if (layersFromConfig_2_1 && !layersFromConfig_2_1.done && (_b = layersFromConfig_2.return)) _b.call(layersFromConfig_2);
              } finally {
                if (e_31) throw e_31.error;
              }
            }
          }
          var inputTensors = [];
          var outputTensors = [];
          var inputLayersFromConfig = config["inputLayers"];
          try {
            for (var inputLayersFromConfig_1 = __values(inputLayersFromConfig), inputLayersFromConfig_1_1 = inputLayersFromConfig_1.next(); !inputLayersFromConfig_1_1.done; inputLayersFromConfig_1_1 = inputLayersFromConfig_1.next()) {
              var layerData = inputLayersFromConfig_1_1.value;
              var layerName = layerData[0];
              var nodeIndex = layerData[1];
              var tensorIndex = layerData[2];
              assert$1(layerName in createdLayers);
              var layer = createdLayers[layerName];
              var layerOutputTensors = layer.inboundNodes[nodeIndex].outputTensors;
              inputTensors.push(layerOutputTensors[tensorIndex]);
            }
          } catch (e_33_1) {
            e_33 = { error: e_33_1 };
          } finally {
            try {
              if (inputLayersFromConfig_1_1 && !inputLayersFromConfig_1_1.done && (_d = inputLayersFromConfig_1.return)) _d.call(inputLayersFromConfig_1);
            } finally {
              if (e_33) throw e_33.error;
            }
          }
          var outputLayersFromConfig = config["outputLayers"];
          try {
            for (var outputLayersFromConfig_1 = __values(outputLayersFromConfig), outputLayersFromConfig_1_1 = outputLayersFromConfig_1.next(); !outputLayersFromConfig_1_1.done; outputLayersFromConfig_1_1 = outputLayersFromConfig_1.next()) {
              var layerData = outputLayersFromConfig_1_1.value;
              var layerName = layerData[0];
              var nodeIndex = layerData[1];
              var tensorIndex = layerData[2];
              assert$1(layerName in createdLayers);
              var layer = createdLayers[layerName];
              var layerOutputTensors = layer.inboundNodes[nodeIndex].outputTensors;
              outputTensors.push(layerOutputTensors[tensorIndex]);
            }
          } catch (e_34_1) {
            e_34 = { error: e_34_1 };
          } finally {
            try {
              if (outputLayersFromConfig_1_1 && !outputLayersFromConfig_1_1.done && (_e = outputLayersFromConfig_1.return)) _e.call(outputLayersFromConfig_1);
            } finally {
              if (e_34) throw e_34.error;
            }
          }
          return new cls({ inputs: inputTensors, outputs: outputTensors, name });
        };
        Object.defineProperty(Container2.prototype, "stateful", {
          /**
           * Determine whether the container is stateful.
           *
           * Porting Note: this is the equivalent of the stateful @property of
           *   the Container class in PyKeras.
           */
          get: function() {
            var e_36, _a2;
            if (this._stateful) {
              throw new ValueError("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.");
            }
            try {
              for (var _b = __values(this.layers), _c = _b.next(); !_c.done; _c = _b.next()) {
                var layer = _c.value;
                if (layer.stateful) {
                  return true;
                }
              }
            } catch (e_36_1) {
              e_36 = { error: e_36_1 };
            } finally {
              try {
                if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
              } finally {
                if (e_36) throw e_36.error;
              }
            }
            return false;
          },
          enumerable: false,
          configurable: true
        });
        Container2.prototype.resetStates = function() {
          var _this = this;
          tfc.tidy(function() {
            _this.layers.forEach(function(layer) {
              if (layer.stateful) {
                layer.resetStates();
              }
            });
          });
        };
        return Container2;
      }(Layer)
    );
    function standardizeSampleOrClassWeights(xWeight, outputNames, weightType) {
      var numOutputs = outputNames.length;
      if (xWeight == null || Array.isArray(xWeight) && xWeight.length === 0) {
        return outputNames.map(function(name) {
          return null;
        });
      }
      if (numOutputs === 1) {
        if (Array.isArray(xWeight) && xWeight.length === 1) {
          return xWeight;
        } else if (typeof xWeight === "object" && outputNames[0] in xWeight) {
          return [xWeight[outputNames[0]]];
        } else {
          return [xWeight];
        }
      }
      if (Array.isArray(xWeight)) {
        if (xWeight.length !== numOutputs) {
          throw new Error("Provided ".concat(weightType, " is an array of ").concat(xWeight.length, " ") + "element(s), but the model has ".concat(numOutputs, " outputs. ") + "Make sure a set of weights is provided for each model output.");
        }
        return xWeight;
      } else if (typeof xWeight === "object" && Object.keys(xWeight).length > 0 && typeof xWeight[Object.keys(xWeight)[0]] === "object") {
        var output_1 = [];
        outputNames.forEach(function(outputName) {
          if (outputName in xWeight) {
            output_1.push(xWeight[outputName]);
          } else {
            output_1.push(null);
          }
        });
        return output_1;
      } else {
        throw new Error("The model has multiple (".concat(numOutputs, ") outputs, ") + "so ".concat(weightType, " must be either an array with ") + "".concat(numOutputs, " elements or an object with ").concat(outputNames, " keys. ") + "Provided ".concat(weightType, " not understood: ").concat(JSON.stringify(xWeight)));
      }
    }
    function standardizeClassWeights(classWeight, outputNames) {
      return standardizeSampleOrClassWeights(classWeight, outputNames, "classWeight");
    }
    function standardizeWeights(y, sampleWeight, classWeight, sampleWeightMode) {
      return __awaiter(this, void 0, void 0, function() {
        var yClasses, yClassIndices, _a2, _b, classSampleWeight_1;
        return __generator(this, function(_c) {
          switch (_c.label) {
            case 0:
              if (sampleWeight != null || sampleWeightMode != null) {
                throw new Error("Support sampleWeight is not implemented yet");
              }
              if (!(classWeight != null)) return [3, 2];
              yClasses = tfc.tidy(function() {
                if (y.shape.length === 1) {
                  return tfc.clone(y);
                } else if (y.shape.length === 2) {
                  if (y.shape[1] > 1) {
                    var axis = 1;
                    return tfc.argMax(y, axis);
                  } else if (y.shape[1] === 1) {
                    return tfc.reshape(y, [y.shape[0]]);
                  } else {
                    throw new Error("Encountered unexpected last-dimension size (".concat(y.shape[1], ") ") + "during handling of class weights. The size is expected to be >= 1.");
                  }
                } else {
                  throw new Error("Unexpected rank of target (y) tensor (".concat(y.rank, ") during ") + "handling of class weights. The rank is expected to be 1 or 2.");
                }
              });
              _b = (_a2 = Array).from;
              return [4, yClasses.data()];
            case 1:
              yClassIndices = _b.apply(_a2, [_c.sent()]);
              tfc.dispose(yClasses);
              classSampleWeight_1 = [];
              yClassIndices.forEach(function(classIndex) {
                if (classWeight[classIndex] == null) {
                  throw new Error("classWeight must contain all classes in the training data. " + "The class ".concat(classIndex, " exists in the data but not in ") + "classWeight");
                } else {
                  classSampleWeight_1.push(classWeight[classIndex]);
                }
              });
              return [2, tfc.tensor1d(classSampleWeight_1, "float32")];
            case 2:
              return [2, null];
          }
        });
      });
    }
    function computeWeightedLoss(losses, sampleWeights) {
      return tfc.mul(losses, sampleWeights);
    }
    var DEFAULT_VALIDATION_BATCH_SIZE = 32;
    function standardizeDataIteratorOutput(model2, iteratorOut) {
      var xs;
      var ys;
      var iteratorOutObj = iteratorOut;
      xs = iteratorOutObj["xs"];
      ys = iteratorOutObj["ys"];
      tfc__namespace.util.assert(xs != null && ys != null, function() {
        return "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 " + "".concat(iteratorOut);
      });
      var flattenedXs = flattenTensorOrArrayOrMap("input", model2.inputNames, xs);
      var flattenedYs = flattenTensorOrArrayOrMap("output", model2.outputNames, ys);
      var batchSize = flattenedXs[0].shape[0];
      tfc__namespace.util.assert(flattenedXs.length === model2.inputs.length, function() {
        return "LayersModel has ".concat(model2.inputs.length, " inputs, but the dataset ") + "provides ".concat(flattenedXs.length, " inputs.  (Expected input keys: ") + "".concat(JSON.stringify(model2.inputNames), ")");
      });
      tfc__namespace.util.assert(flattenedYs.length === model2.outputs.length, function() {
        return "LayersModel has ".concat(model2.outputs.length, " outputs, but the dataset ") + "provides ".concat(flattenedYs.length, " outputs.  (Expected output keys: ") + "".concat(JSON.stringify(model2.outputNames), ")");
      });
      var _loop_1 = function(xIndex2) {
        tfc__namespace.util.assert(flattenedXs[xIndex2].shape[0] === batchSize, function() {
          return "Batch size mismatch: input " + "".concat(model2.inputNames[xIndex2], " has ").concat(flattenedXs[xIndex2].shape[0], "; ") + "expected  ".concat(batchSize, " based on input ").concat(model2.inputNames[0], ".");
        });
      };
      for (var xIndex = 0; xIndex < flattenedXs.length; xIndex++) {
        _loop_1(xIndex);
      }
      var _loop_2 = function(yIndex2) {
        tfc__namespace.util.assert(flattenedYs[yIndex2].shape[0] === batchSize, function() {
          return "Batch size mismatch: output " + "".concat(model2.outputNames[yIndex2], " has ").concat(flattenedYs[yIndex2].shape[0], "; ") + "expected  ".concat(batchSize, " based on input ").concat(model2.inputNames[0], ".");
        });
      };
      for (var yIndex = 0; yIndex < flattenedYs.length; yIndex++) {
        _loop_2(yIndex);
      }
      return { xs: flattenedXs, ys: flattenedYs };
    }
    function flattenTensorOrArrayOrMap(inputOrOutput, names, values) {
      var e_12, _a2;
      if (values instanceof tfc__namespace.Tensor) {
        return [values];
      } else if (Array.isArray(values)) {
        tfc__namespace.util.assert(values.length === names.length, function() {
          return "Received an array of ".concat(values.length, " Tensors, but expected ").concat(names.length, " to match the ").concat(inputOrOutput, " keys ").concat(names, ".");
        });
        return values;
      } else {
        var result = [];
        try {
          for (var names_1 = __values(names), names_1_1 = names_1.next(); !names_1_1.done; names_1_1 = names_1.next()) {
            var name = names_1_1.value;
            if (values[name] == null) {
              throw new ValueError("The feature data generated by the dataset lacks the required " + "".concat(inputOrOutput, " key '").concat(name, "'."));
            }
            result.push(values[name]);
          }
        } catch (e_1_1) {
          e_12 = { error: e_1_1 };
        } finally {
          try {
            if (names_1_1 && !names_1_1.done && (_a2 = names_1.return)) _a2.call(names_1);
          } finally {
            if (e_12) throw e_12.error;
          }
        }
        return result;
      }
    }
    function standardizeTensorValidationData(data) {
      if (data.length === 3) {
        throw new NotImplementedError("Validation with sample weights is not implemented yet.");
      }
      return { xs: data[0], ys: data[1] };
    }
    function fitDataset(model2, dataset, args) {
      return __awaiter(this, void 0, void 0, function() {
        var hasBatchesPerEpoch, doValidation, valXs, valYs, validationData, trainFunction, outLabels, callbackMetrics, callbacks2, verbose, _a2, callbackList, history, epoch, dataIterator, epochLogs, stepsDone, batchIndex, iteratorOut, _b, xs, ys, batchLogs, sampleWeights, standardClassWeights, i, _c, _d, ins, outs, i, label, out, valOuts, _e, i;
        return __generator(this, function(_f) {
          switch (_f.label) {
            case 0:
              hasBatchesPerEpoch = args.batchesPerEpoch != null;
              tfc__namespace.util.assert(model2.optimizer != null, function() {
                return "You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig).";
              });
              tfc__namespace.util.assert(args != null, function() {
                return "For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call.";
              });
              tfc__namespace.util.assert(args.epochs != null && args.epochs > 0 && Number.isInteger(args.epochs), function() {
                return "For fitDataset(), config.epochs is expected to be a positive " + "integer, but got ".concat(args.epochs);
              });
              tfc__namespace.util.assert(!hasBatchesPerEpoch || args.batchesPerEpoch > 0 && Number.isInteger(args.batchesPerEpoch), function() {
                return "For fitDataset(), config.batchesPerEpoch is expected to be a " + "positive integer if specified, but got ".concat(args.batchesPerEpoch);
              });
              tfc__namespace.util.assert(
                // tslint:disable-next-line:no-any
                args["validationSplit"] == null,
                function() {
                  return "`validationSplit` is not supported by `fitDataset()`. Use validationData instead.";
                }
              );
              if (model2.isTraining) {
                throw new Error("Cannot start training because another fit() call is ongoing.");
              }
              model2.isTraining = true;
              _f.label = 1;
            case 1:
              _f.trys.push([1, , 26, 27]);
              doValidation = args.validationData != null;
              valXs = void 0;
              valYs = void 0;
              if (doValidation) {
                if (isDatasetObject(args.validationData)) {
                  tfc__namespace.util.assert(args.validationBatches == null || args.validationBatches > 0 && Number.isInteger(args.validationBatches), function() {
                    return "For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, " + "but got ".concat(args.validationBatches);
                  });
                } else {
                  validationData = standardizeTensorValidationData(args.validationData);
                  valXs = validationData.xs;
                  valYs = validationData.ys;
                }
              }
              trainFunction = model2.makeTrainFunction();
              outLabels = model2.getDedupedMetricsNames();
              callbackMetrics = void 0;
              if (doValidation) {
                callbackMetrics = outLabels.slice().concat(outLabels.map(function(n) {
                  return "val_" + n;
                }));
              } else {
                callbackMetrics = outLabels.slice();
              }
              callbacks2 = standardizeCallbacks(args.callbacks, args.yieldEvery);
              verbose = args.verbose == null ? 1 : args.verbose;
              _a2 = configureCallbacks(
                callbacks2,
                verbose,
                args.epochs,
                null,
                null,
                getStepsPerEpoch(dataset, args),
                null,
                // Batch size determined by the dataset itself.
                doValidation,
                callbackMetrics
              ), callbackList = _a2.callbackList, history = _a2.history;
              callbackList.setModel(model2);
              model2.history = history;
              return [4, callbackList.onTrainBegin()];
            case 2:
              _f.sent();
              model2.stopTraining_ = false;
              epoch = args.initialEpoch == null ? 0 : args.initialEpoch;
              return [4, dataset.iterator()];
            case 3:
              dataIterator = _f.sent();
              _f.label = 4;
            case 4:
              if (!(epoch < args.epochs)) return [3, 23];
              epochLogs = {};
              return [4, callbackList.onEpochBegin(epoch)];
            case 5:
              _f.sent();
              stepsDone = 0;
              batchIndex = 0;
              if (!!hasBatchesPerEpoch) return [3, 7];
              return [4, dataset.iterator()];
            case 6:
              dataIterator = _f.sent();
              _f.label = 7;
            case 7:
              if (!(hasBatchesPerEpoch ? stepsDone < args.batchesPerEpoch : true)) return [3, 21];
              return [4, dataIterator.next()];
            case 8:
              iteratorOut = _f.sent();
              if (hasBatchesPerEpoch && iteratorOut.done) {
                console.warn("You provided `batchesPerEpoch` as " + "".concat(args.batchesPerEpoch, ", ") + "but your dataset iterator ran out of data after " + "".concat(stepsDone, " batches; ") + "interrupting training. Make sure that your dataset can generate at least `batchesPerEpoch * epochs` batches (in this case, " + "".concat(args.batchesPerEpoch * args.epochs, " batches). ") + "You may need to use the repeat() function when building your dataset.");
                return [3, 21];
              }
              if (!(iteratorOut.value != null)) return [3, 15];
              _b = standardizeDataIteratorOutput(model2, iteratorOut.value), xs = _b.xs, ys = _b.ys;
              batchLogs = {};
              batchLogs["batch"] = batchIndex;
              batchLogs["size"] = xs[0].shape[0];
              return [4, callbackList.onBatchBegin(batchIndex, batchLogs)];
            case 9:
              _f.sent();
              sampleWeights = [];
              if (!(args.classWeight != null)) return [3, 13];
              standardClassWeights = standardizeClassWeights(args.classWeight, model2.outputNames);
              i = 0;
              _f.label = 10;
            case 10:
              if (!(i < standardClassWeights.length)) return [3, 13];
              _d = (_c = sampleWeights).push;
              return [4, standardizeWeights(ys[i], null, standardClassWeights[i])];
            case 11:
              _d.apply(_c, [_f.sent()]);
              _f.label = 12;
            case 12:
              ++i;
              return [3, 10];
            case 13:
              ins = xs.concat(ys).concat(sampleWeights);
              outs = trainFunction(ins);
              tfc__namespace.dispose(ins);
              for (i = 0; i < outLabels.length; ++i) {
                label = outLabels[i];
                out = outs[i];
                batchLogs[label] = out;
                tfc__namespace.keep(out);
              }
              return [4, callbackList.onBatchEnd(batchIndex, batchLogs)];
            case 14:
              _f.sent();
              disposeTensorsInLogs(batchLogs);
              batchIndex++;
              stepsDone++;
              _f.label = 15;
            case 15:
              if (!(hasBatchesPerEpoch ? stepsDone >= args.batchesPerEpoch : iteratorOut.done)) return [3, 20];
              if (!doValidation) return [3, 19];
              valOuts = void 0;
              if (!isDatasetObject(args.validationData)) return [3, 17];
              _e = toList;
              return [4, model2.evaluateDataset(args.validationData, { batches: args.validationBatches })];
            case 16:
              valOuts = _e.apply(void 0, [_f.sent()]);
              return [3, 18];
            case 17:
              valOuts = toList(model2.evaluate(valXs, valYs, {
                batchSize: args.validationBatchSize == null ? DEFAULT_VALIDATION_BATCH_SIZE : args.validationBatchSize,
                verbose: 0
              }));
              _f.label = 18;
            case 18:
              for (i = 0; i < model2.metricsNames.length; ++i) {
                epochLogs["val_".concat(model2.metricsNames[i])] = valOuts[i];
              }
              _f.label = 19;
            case 19:
              return [3, 21];
            case 20:
              if (model2.stopTraining_) {
                return [3, 21];
              }
              return [3, 7];
            case 21:
              return [4, callbackList.onEpochEnd(epoch, epochLogs)];
            case 22:
              _f.sent();
              epoch++;
              if (model2.stopTraining_) {
                return [3, 23];
              }
              return [3, 4];
            case 23:
              return [4, callbackList.onTrainEnd()];
            case 24:
              _f.sent();
              return [4, model2.history.syncData()];
            case 25:
              _f.sent();
              return [2, model2.history];
            case 26:
              model2.isTraining = false;
              return [
                7
                /*endfinally*/
              ];
            case 27:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    }
    function getStepsPerEpoch(dataset, args) {
      var stepsPerEpoch = null;
      if (args.batchesPerEpoch != null) {
        stepsPerEpoch = args.batchesPerEpoch;
      } else if (Number.isFinite(dataset.size)) {
        stepsPerEpoch = dataset.size;
      }
      return stepsPerEpoch;
    }
    function isDatasetObject(dataset) {
      return typeof dataset.iterator === "function";
    }
    function isLazyIteratorObject(iterator) {
      return typeof iterator.next === "function";
    }
    function evaluateDataset(model2, dataset, args) {
      return __awaiter(this, void 0, void 0, function() {
        var hasBatches, f, outs, dataIterator, _a2, numExamples, batch, _loop_3, state_1, i, oldScalar;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              args = args || {};
              hasBatches = args.batches != null;
              f = model2.testFunction;
              outs = [];
              if (args.verbose > 0) {
                throw new NotImplementedError("Verbose mode is not implemented yet.");
              }
              tfc__namespace.util.assert(!hasBatches || args.batches > 0 && Number.isInteger(args.batches), function() {
                return "Test loop expects `batches` to be a positive integer, but " + "received ".concat(JSON.stringify(args.batches));
              });
              if (!isLazyIteratorObject(dataset)) return [3, 1];
              _a2 = dataset;
              return [3, 3];
            case 1:
              return [4, dataset.iterator()];
            case 2:
              _a2 = _b.sent();
              _b.label = 3;
            case 3:
              dataIterator = _a2;
              numExamples = 0;
              batch = 0;
              _loop_3 = function() {
                var iteratorOut;
                return __generator(this, function(_c) {
                  switch (_c.label) {
                    case 0:
                      return [4, dataIterator.next()];
                    case 1:
                      iteratorOut = _c.sent();
                      outs = tfc__namespace.tidy(function() {
                        if (iteratorOut.value) {
                          var _a3 = standardizeDataIteratorOutput(model2, iteratorOut.value), xs = _a3.xs, ys = _a3.ys;
                          var xsAndYs_1 = xs.concat(ys);
                          var batchOuts = tfc__namespace.tidy(function() {
                            return f(xsAndYs_1);
                          });
                          tfc__namespace.dispose(xsAndYs_1);
                          if (batch === 0) {
                            for (var i2 = 0; i2 < batchOuts.length; ++i2) {
                              outs.push(tfc.scalar(0));
                            }
                          }
                          var batchSize_1 = xsAndYs_1[0].shape[0];
                          var _loop_4 = function(i3) {
                            var batchOut = batchOuts[i3];
                            var oldScalar2 = outs[i3];
                            outs[i3] = tfc__namespace.tidy(function() {
                              return tfc__namespace.add(outs[i3], tfc__namespace.mul(batchSize_1, batchOut));
                            });
                            if (batch > 0) {
                              tfc__namespace.dispose(oldScalar2);
                            }
                          };
                          for (var i2 = 0; i2 < batchOuts.length; ++i2) {
                            _loop_4(i2);
                          }
                          tfc__namespace.dispose(batchOuts);
                          numExamples += batchSize_1;
                          ++batch;
                        }
                        return outs;
                      });
                      if (iteratorOut.done) {
                        if (hasBatches) {
                          console.warn("Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least `batches` " + "batches (in this case, ".concat(args.batches, " batches). ") + "You may need to use the repeat() function when building your dataset.");
                        }
                        return [2, "break"];
                      }
                      return [
                        2
                        /*return*/
                      ];
                  }
                });
              };
              _b.label = 4;
            case 4:
              if (!(hasBatches ? batch < args.batches : true)) return [3, 6];
              return [5, _loop_3()];
            case 5:
              state_1 = _b.sent();
              if (state_1 === "break")
                return [3, 6];
              return [3, 4];
            case 6:
              for (i = 0; i < outs.length; ++i) {
                oldScalar = outs[i];
                outs[i] = tfc__namespace.div(outs[i], numExamples);
                tfc__namespace.dispose(oldScalar);
              }
              return [2, singletonOrArray(outs)];
          }
        });
      });
    }
    function checkBatchSize(batchSize) {
      tfc__namespace.util.assert(batchSize > 0 && Number.isInteger(batchSize), function() {
        return "batchSize is required to be a positive integer, but got ".concat(batchSize);
      });
    }
    function sliceArrays(arrays, start, stop) {
      if (arrays == null) {
        return [null];
      } else if (Array.isArray(arrays)) {
        return arrays.map(function(array) {
          return sliceAlongFirstAxis(array, start, stop - start);
        });
      } else {
        return sliceAlongFirstAxis(arrays, start, stop - start);
      }
    }
    function sliceArraysByIndices(arrays, indices) {
      return tfc__namespace.tidy(function() {
        if (arrays == null) {
          return null;
        } else if (Array.isArray(arrays)) {
          return arrays.map(function(array) {
            return sliceArraysByIndices(array, indices);
          });
        } else {
          return gather$1(arrays, indices.dtype === "int32" ? indices : tfc__namespace.cast(indices, "int32"));
        }
      });
    }
    function makeBatches(size, batchSize) {
      var output = [];
      var batchStart = 0;
      var batchEnd = null;
      while (batchStart < size) {
        batchEnd = batchStart + batchSize;
        if (batchEnd >= size) {
          batchEnd = size;
        }
        output.push([batchStart, batchEnd]);
        batchStart = batchEnd;
      }
      return output;
    }
    function ensureTensorsRank2OrHigher(tensors) {
      var outs = [];
      if (tensors instanceof tfc.Tensor) {
        tensors = [tensors];
      }
      for (var i = 0; i < tensors.length; ++i) {
        var tensor = tensors[i];
        if (tensor.rank === 1) {
          outs.push(expandDims$1(tensor, 1));
        } else if (tensor.rank === 0) {
          throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");
        } else {
          outs.push(tensor);
        }
      }
      return outs;
    }
    function disposeNewTensors(tensors, refTensors) {
      if (tensors == null) {
        return;
      }
      var oldTensorIds = [];
      if (refTensors instanceof tfc.Tensor) {
        oldTensorIds.push(refTensors.id);
      } else if (Array.isArray(refTensors)) {
        refTensors.forEach(function(t) {
          return oldTensorIds.push(t.id);
        });
      } else if (refTensors != null) {
        for (var name in refTensors) {
          var oldTensor = refTensors[name];
          oldTensorIds.push(oldTensor.id);
        }
      }
      var tensorsToDispose = [];
      if (tensors instanceof tfc.Tensor) {
        if (oldTensorIds.indexOf(tensors.id) === -1) {
          tensorsToDispose.push(tensors);
        }
      } else if (Array.isArray(tensors)) {
        tensors.forEach(function(t) {
          if (oldTensorIds.indexOf(t.id) === -1) {
            tensorsToDispose.push(t);
          }
        });
      } else if (tensors != null) {
        for (var name in tensors) {
          var tensor = tensors[name];
          if (oldTensorIds.indexOf(tensor.id) === -1) {
            tensorsToDispose.push(tensor);
          }
        }
      }
      tensorsToDispose.forEach(function(t) {
        if (!t.isDisposed) {
          t.dispose();
        }
      });
    }
    function isDataTensor(x) {
      return x instanceof tfc.Tensor;
    }
    function isDataArray(x) {
      return Array.isArray(x);
    }
    function isDataDict(x) {
      return !isDataTensor(x) && !isDataArray(x);
    }
    function standardizeInputData(data, names, shapes, checkBatchAxis, exceptionPrefix) {
      var e_12, _a2;
      if (checkBatchAxis === void 0) {
        checkBatchAxis = true;
      }
      if (exceptionPrefix === void 0) {
        exceptionPrefix = "";
      }
      if (names == null || names.length === 0) {
        if (data != null) {
          var gotUnexpectedData = false;
          if (isDataArray(data) && data.length > 0) {
            gotUnexpectedData = true;
          } else if (isDataDict(data)) {
            for (var key in data) {
              if (data.hasOwnProperty(key)) {
                gotUnexpectedData = true;
                break;
              }
            }
          } else {
            gotUnexpectedData = true;
          }
          if (gotUnexpectedData) {
            throw new ValueError("Error when checking model ".concat(exceptionPrefix, " expected no data, ") + "but got ".concat(data));
          }
        }
        return [];
      }
      if (data == null) {
        return names.map(function(name2) {
          return null;
        });
      }
      var arrays;
      if (isDataDict(data)) {
        data = data;
        arrays = [];
        try {
          for (var names_1 = __values(names), names_1_1 = names_1.next(); !names_1_1.done; names_1_1 = names_1.next()) {
            var name = names_1_1.value;
            if (data[name] == null) {
              throw new ValueError('No data provided for "'.concat(name, '". Need data for each key in: ') + "".concat(names));
            }
            arrays.push(data[name]);
          }
        } catch (e_1_1) {
          e_12 = { error: e_1_1 };
        } finally {
          try {
            if (names_1_1 && !names_1_1.done && (_a2 = names_1.return)) _a2.call(names_1);
          } finally {
            if (e_12) throw e_12.error;
          }
        }
      } else if (isDataArray(data)) {
        data = data;
        if (data.length !== names.length) {
          throw new ValueError("Error when checking model ".concat(exceptionPrefix, ": the Array of ") + "Tensors that you are passing to your model is not the size the " + "model expected. Expected to see ".concat(names.length, " Tensor(s), but ") + "instead got the following list of Tensor(s): ".concat(data));
        }
        arrays = data;
      } else {
        data = data;
        if (names.length > 1) {
          throw new ValueError("The model ".concat(exceptionPrefix, " expects ").concat(names.length, " Tensor(s), ") + "but only received one Tensor. Found: Tensor with shape ".concat(data.shape));
        }
        arrays = [data];
      }
      arrays = ensureTensorsRank2OrHigher(arrays);
      if (shapes != null) {
        for (var i = 0; i < names.length; ++i) {
          if (shapes[i] == null) {
            continue;
          }
          var array = arrays[i];
          if (array.shape.length !== shapes[i].length) {
            throw new ValueError("Error when checking ".concat(exceptionPrefix, ": expected ").concat(names[i], " ") + "to have ".concat(shapes[i].length, " dimension(s). but got array with ") + "shape ".concat(array.shape));
          }
          for (var j = 0; j < shapes[i].length; ++j) {
            if (j === 0 && !checkBatchAxis) {
              continue;
            }
            var dim = array.shape[j];
            var refDim = shapes[i][j];
            if (refDim != null && refDim >= 0 && dim !== refDim) {
              throw new ValueError("".concat(exceptionPrefix, " expected a batch of elements where each ") + "example has shape [".concat(shapes[i].slice(1, shapes[i].length), "] ") + "(i.e.,tensor shape [*,".concat(shapes[i].slice(1, shapes[i].length), "])") + " but the ".concat(exceptionPrefix, " received an input with ").concat(array.shape[0]) + " examples, each with shape [".concat(array.shape.slice(1, array.shape.length), "]") + " (tensor shape [".concat(array.shape, "])"));
            }
          }
        }
      }
      return arrays;
    }
    function checkArrayLengths(inputs, targets, weights) {
      var setX = unique(inputs.map(function(input2) {
        return input2.shape[0];
      }));
      setX.sort();
      var setY = unique(targets.map(function(target) {
        return target.shape[0];
      }));
      setY.sort();
      if (setX.length > 1) {
        throw new ValueError("All input Tensors (x) should have the same number of samples. Got array shapes: " + "".concat(JSON.stringify(inputs.map(function(input2) {
          return input2.shape;
        }))));
      }
      if (setY.length > 1) {
        throw new ValueError("All target Tensors (y) should have the same number of samples. Got array shapes: " + "".concat(JSON.stringify(targets.map(function(target) {
          return target.shape;
        }))));
      }
      if (setX.length > 0 && setY.length > 0 && !tfc.util.arraysEqual(setX, setY)) {
        throw new ValueError("Input Tensors should have the same number of samples as target " + "Tensors. Found ".concat(setX[0], " input sample(s) and ").concat(setY[0], " target ") + "sample(s).");
      }
    }
    function checkLossAndTargetCompatibility(targets, lossFns, outputShapes) {
      var keyLosses = [
        meanSquaredError$1,
        binaryCrossentropy$2,
        categoricalCrossentropy$2
      ];
      for (var i = 0; i < targets.length; ++i) {
        var y = targets[i];
        var loss = lossFns[i];
        var shape = outputShapes[i];
        if (loss == null) {
          continue;
        }
        if (loss === categoricalCrossentropy$2) {
          if (y.shape[y.shape.length - 1] === 1) {
            throw new ValueError("You are passing a target array of shape ".concat(y.shape, " while using ") + "a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].");
          }
        }
        if (keyLosses.indexOf(loss) !== -1) {
          var slicedYShape = y.shape.slice(1);
          var slicedShape = shape.slice(1);
          for (var j = 0; j < slicedYShape.length; ++j) {
            var targetDim = slicedYShape[j];
            var outDim = slicedShape[j];
            if (outDim != null && targetDim !== outDim) {
              throw new ValueError("A target Tensor with shape ".concat(y.shape, " was passed for an ") + "output of shape ".concat(shape, ", while using a loss function that ") + "expects targets to have the same shape as the output.");
            }
          }
        }
      }
    }
    function checkInputData(data, names, shapes, checkBatchAxis, exceptionPrefix) {
      if (checkBatchAxis === void 0) {
        checkBatchAxis = true;
      }
      if (exceptionPrefix === void 0) {
        exceptionPrefix = "";
      }
      var arrays;
      if (Array.isArray(data)) {
        if (data.length !== names.length) {
          throw new ValueError("Error when checking model ".concat(exceptionPrefix, ": the Array of ") + "Tensors that you are passing to your model is not the size the " + "the model expected. Expected to see ".concat(names.length, " Tensor(s),") + " but instead got ".concat(data.length, " Tensors(s)."));
        }
        arrays = data;
      } else {
        if (names.length > 1) {
          throw new ValueError("The model expects ".concat(names.length, " ").concat(exceptionPrefix, " Tensors, ") + "but only received one Tensor. Found: array with shape " + "".concat(JSON.stringify(data.shape), "."));
        }
        arrays = [data];
      }
      if (shapes != null) {
        for (var i = 0; i < names.length; ++i) {
          if (shapes[i] == null) {
            continue;
          }
          var array = arrays[i];
          if (array.shape.length !== shapes[i].length) {
            throw new ValueError("Error when checking ".concat(exceptionPrefix, ": expected ").concat(names[i], " ") + "to have ".concat(shapes[i].length, " dimension(s), but got array with ") + "shape ".concat(JSON.stringify(array.shape)));
          }
          for (var j = 0; j < shapes[i].length; ++j) {
            if (j === 0 && !checkBatchAxis) {
              continue;
            }
            var dim = array.shape[j];
            var refDim = shapes[i][j];
            if (refDim != null) {
              if (refDim !== dim) {
                throw new ValueError("Error when checking ".concat(exceptionPrefix, ": expected ") + "".concat(names[i], " to have shape ").concat(JSON.stringify(shapes[i]), " but ") + "got array with shape ".concat(JSON.stringify(array.shape), "."));
              }
            }
          }
        }
      }
    }
    function collectMetrics(metrics, outputNames) {
      var e_2, _a2;
      if (metrics == null || Array.isArray(metrics) && metrics.length === 0) {
        return outputNames.map(function(name2) {
          return [];
        });
      }
      var wrappedMetrics;
      if (typeof metrics === "string" || typeof metrics === "function") {
        wrappedMetrics = [metrics];
      } else if (Array.isArray(metrics) || typeof metrics === "object") {
        wrappedMetrics = metrics;
      } else {
        throw new TypeError("Type of metrics argument not understood. Expected an string," + "function, Array, or Object, found: ".concat(metrics));
      }
      if (Array.isArray(wrappedMetrics)) {
        return outputNames.map(function(name2) {
          return wrappedMetrics;
        });
      } else {
        var nestedMetrics = [];
        try {
          for (var outputNames_1 = __values(outputNames), outputNames_1_1 = outputNames_1.next(); !outputNames_1_1.done; outputNames_1_1 = outputNames_1.next()) {
            var name = outputNames_1_1.value;
            var outputMetrics = wrappedMetrics.hasOwnProperty(name) ? wrappedMetrics[name] : [];
            if (!Array.isArray(outputMetrics)) {
              outputMetrics = [outputMetrics];
            }
            nestedMetrics.push(outputMetrics);
          }
        } catch (e_2_1) {
          e_2 = { error: e_2_1 };
        } finally {
          try {
            if (outputNames_1_1 && !outputNames_1_1.done && (_a2 = outputNames_1.return)) _a2.call(outputNames_1);
          } finally {
            if (e_2) throw e_2.error;
          }
        }
        return nestedMetrics;
      }
    }
    var LAYERS_MODEL_FORMAT_NAME = "layers-model";
    var LayersModel = (
      /** @class */
      function(_super) {
        __extends(LayersModel2, _super);
        function LayersModel2(args) {
          var _this = _super.call(this, args) || this;
          _this.isTraining = false;
          return _this;
        }
        LayersModel2.prototype.summary = function(lineLength, positions, printFn) {
          if (printFn === void 0) {
            printFn = console.log;
          }
          if (!this.built) {
            throw new ValueError("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).");
          }
          printSummary(this, lineLength, positions, printFn);
        };
        LayersModel2.prototype.compile = function(args) {
          var e_3, _a2;
          var _this = this;
          if (args.loss == null) {
            args.loss = [];
          }
          this.loss = args.loss;
          if (typeof args.optimizer === "string") {
            this.optimizer_ = getOptimizer(args.optimizer);
            this.isOptimizerOwned = true;
          } else {
            if (!(args.optimizer instanceof tfc.Optimizer)) {
              throw new ValueError("User-defined optimizer must be an instance of tf.Optimizer.");
            }
            this.optimizer_ = args.optimizer;
            this.isOptimizerOwned = false;
          }
          var lossFunctions = [];
          if (!Array.isArray(args.loss) && typeof args.loss !== "string" && typeof args.loss !== "function") {
            args.loss = args.loss;
            for (var name in args.loss) {
              if (this.outputNames.indexOf(name) === -1) {
                throw new ValueError('Unknown entry in loss dictionary: "'.concat(name, '". ') + "Only expected the following keys: ".concat(this.outputNames));
              }
            }
            try {
              for (var _b = __values(this.outputNames), _c = _b.next(); !_c.done; _c = _b.next()) {
                var name = _c.value;
                if (args.loss[name] == null) {
                  console.warn('Output "'.concat(name, '" is missing from loss dictionary. We assume ') + "this was done on purpose, and we will not be expecting data " + "to be passed to ".concat(name, " during training"));
                }
                lossFunctions.push(get$1(args.loss[name]));
              }
            } catch (e_3_1) {
              e_3 = { error: e_3_1 };
            } finally {
              try {
                if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
              } finally {
                if (e_3) throw e_3.error;
              }
            }
          } else if (Array.isArray(args.loss)) {
            if (args.loss.length !== this.outputs.length) {
              throw new ValueError("When passing an Array as loss, it should have one entry per " + "model output. The model has ".concat(this.outputs.length, " output(s), ") + "but you passed loss=".concat(args.loss, "."));
            }
            var theLosses = args.loss;
            lossFunctions = theLosses.map(function(l) {
              return get$1(l);
            });
          } else {
            var lossFunction_1 = get$1(args.loss);
            this.outputs.forEach(function(_) {
              lossFunctions.push(lossFunction_1);
            });
          }
          this.lossFunctions = lossFunctions;
          this.feedOutputNames = [];
          this.feedOutputShapes = [];
          this.feedLossFns = [];
          for (var i = 0; i < this.outputs.length; ++i) {
            var shape = this.internalOutputShapes[i];
            var name = this.outputNames[i];
            this.feedOutputNames.push(name);
            this.feedOutputShapes.push(shape);
            this.feedLossFns.push(this.lossFunctions[i]);
          }
          var skipTargetIndices = [];
          this.metrics = args.metrics;
          this.metricsNames = ["loss"];
          this.metricsTensors = [];
          nameScope("loss", function() {
            for (var i2 = 0; i2 < _this.outputs.length; ++i2) {
              if (skipTargetIndices.indexOf(i2) !== -1) {
                continue;
              }
              var weightedLoss = _this.lossFunctions[i2];
              if (_this.outputs.length > 1) {
                _this.metricsTensors.push([weightedLoss, i2]);
                _this.metricsNames.push(_this.outputNames[i2] + "_loss");
              }
            }
          });
          var nestedMetrics = collectMetrics(args.metrics, this.outputNames);
          var appendMetric = function(outputIndex, metricName, metricTensor) {
            if (_this.outputNames.length > 1) {
              metricName = _this.outputNames[outputIndex] + "_" + metricName;
            }
            _this.metricsNames.push(metricName);
            _this.metricsTensors.push([metricTensor, outputIndex]);
          };
          nameScope("metric", function() {
            var _loop_1 = function(i3) {
              if (skipTargetIndices.indexOf(i3) !== -1) {
                return "continue";
              }
              var outputMetrics = nestedMetrics[i3];
              var handleMetrics = function(metrics) {
                var e_4, _a3;
                var metricNamePrefix = "";
                var metricName;
                var accFn;
                var weightedMetricFn;
                var _loop_2 = function(metric2) {
                  if (typeof metric2 === "string" && ["accuracy", "acc", "crossentropy", "ce"].indexOf(metric2) !== -1) {
                    var outputShape = _this.internalOutputShapes[i3];
                    if (outputShape[outputShape.length - 1] === 1 || _this.lossFunctions[i3] === binaryCrossentropy$2) {
                      if (["accuracy", "acc"].indexOf(metric2) !== -1) {
                        accFn = binaryAccuracy$1;
                      } else if (["crossentropy", "ce"].indexOf(metric2) !== -1) {
                        accFn = binaryCrossentropy$1;
                      }
                    } else if (_this.lossFunctions[i3] === sparseCategoricalCrossentropy$1) {
                      if (["accuracy", "acc"].indexOf(metric2) !== -1) {
                        accFn = sparseCategoricalAccuracy$1;
                      } else if (["crossentropy", "ce"].indexOf(metric2) !== -1) {
                        accFn = sparseCategoricalCrossentropy;
                      }
                    } else {
                      if (["accuracy", "acc"].indexOf(metric2) !== -1) {
                        accFn = categoricalAccuracy$1;
                      } else if (["crossentropy", "ce"].indexOf(metric2) !== -1) {
                        accFn = categoricalCrossentropy$1;
                      }
                    }
                    var suffix = void 0;
                    if (["accuracy", "acc"].indexOf(metric2) !== -1) {
                      suffix = "acc";
                    } else if (["crossentropy", "ce"].indexOf(metric2) !== -1) {
                      suffix = "ce";
                    }
                    weightedMetricFn = accFn;
                    metricName = metricNamePrefix + suffix;
                  } else {
                    var metricFn = get(metric2);
                    weightedMetricFn = metricFn;
                    metricName = metricNamePrefix + getLossOrMetricName(metric2);
                  }
                  var metricResult;
                  nameScope(metricName, function() {
                    metricResult = weightedMetricFn;
                  });
                  appendMetric(i3, metricName, metricResult);
                };
                try {
                  for (var metrics_1 = (e_4 = void 0, __values(metrics)), metrics_1_1 = metrics_1.next(); !metrics_1_1.done; metrics_1_1 = metrics_1.next()) {
                    var metric = metrics_1_1.value;
                    _loop_2(metric);
                  }
                } catch (e_4_1) {
                  e_4 = { error: e_4_1 };
                } finally {
                  try {
                    if (metrics_1_1 && !metrics_1_1.done && (_a3 = metrics_1.return)) _a3.call(metrics_1);
                  } finally {
                    if (e_4) throw e_4.error;
                  }
                }
              };
              handleMetrics(outputMetrics);
            };
            for (var i2 = 0; i2 < _this.outputs.length; ++i2) {
              _loop_1(i2);
            }
          });
          this.collectedTrainableWeights = this.trainableWeights;
        };
        LayersModel2.prototype.checkTrainableWeightsConsistency = function() {
          if (this.collectedTrainableWeights == null) {
            return;
          }
          if (this.trainableWeights.length !== this.collectedTrainableWeights.length) {
            console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?");
          }
        };
        LayersModel2.prototype.evaluate = function(x, y, args) {
          if (args === void 0) {
            args = {};
          }
          var batchSize = args.batchSize == null ? 32 : args.batchSize;
          checkBatchSize(batchSize);
          var checkBatchAxis = true;
          var standardizedOuts = this.standardizeUserDataXY(x, y, checkBatchAxis, batchSize);
          try {
            var ins = standardizedOuts[0].concat(standardizedOuts[1]);
            this.makeTestFunction();
            var f = this.testFunction;
            var testOuts = this.testLoop(f, ins, batchSize, args.verbose, args.steps);
            return singletonOrArray(testOuts);
          } finally {
            disposeNewTensors(standardizedOuts[0], x);
            disposeNewTensors(standardizedOuts[1], y);
          }
        };
        LayersModel2.prototype.evaluateDataset = function(dataset, args) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              this.makeTestFunction();
              return [2, evaluateDataset(this, dataset, args)];
            });
          });
        };
        LayersModel2.prototype.checkNumSamples = function(ins, batchSize, steps, stepsName) {
          if (stepsName === void 0) {
            stepsName = "steps";
          }
          var numSamples;
          if (steps != null) {
            numSamples = null;
            if (batchSize != null) {
              throw new ValueError("If ".concat(stepsName, " is set, batchSize must be null or undefined.") + "Got batchSize = ".concat(batchSize));
            }
          } else if (ins != null) {
            if (Array.isArray(ins)) {
              numSamples = ins[0].shape[0];
            } else {
              numSamples = ins.shape[0];
            }
          } else {
            throw new ValueError("Either the input data should have a defined shape, or " + "".concat(stepsName, " shoud be specified."));
          }
          return numSamples;
        };
        LayersModel2.prototype.execute = function(inputs, outputs) {
          var e_5, _a2;
          if (Array.isArray(outputs) && outputs.length === 0) {
            throw new ValueError("`outputs` is an empty Array, which is not allowed.");
          }
          var outputsIsArray = Array.isArray(outputs);
          var outputNames = outputsIsArray ? outputs : [outputs];
          var outputSymbolicTensors = this.retrieveSymbolicTensors(outputNames);
          var feedDict = new FeedDict();
          if (inputs instanceof tfc.Tensor) {
            inputs = [inputs];
          }
          if (Array.isArray(inputs)) {
            if (inputs.length !== this.inputs.length) {
              throw new ValueError("The number of inputs provided (".concat(inputs.length, ") ") + "does not match the number of inputs of this model " + "(".concat(this.inputs.length, ")."));
            }
            for (var i = 0; i < this.inputs.length; ++i) {
              feedDict.add(this.inputs[i], inputs[i]);
            }
          } else {
            try {
              for (var _b = __values(this.inputs), _c = _b.next(); !_c.done; _c = _b.next()) {
                var input2 = _c.value;
                var tensorValue = inputs[input2.name];
                if (tensorValue == null) {
                  throw new ValueError("No value is provided for the model's input ".concat(input2.name));
                }
                feedDict.add(input2, tensorValue);
              }
            } catch (e_5_1) {
              e_5 = { error: e_5_1 };
            } finally {
              try {
                if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
              } finally {
                if (e_5) throw e_5.error;
              }
            }
          }
          var executeOutputs = execute(outputSymbolicTensors, feedDict);
          return outputsIsArray ? executeOutputs : executeOutputs[0];
        };
        LayersModel2.prototype.retrieveSymbolicTensors = function(symbolicTensorNames) {
          var e_6, _a2;
          var outputSymbolicTensors = pyListRepeat(null, symbolicTensorNames.length);
          var outputsRemaining = symbolicTensorNames.length;
          try {
            for (var _b = __values(this.layers), _c = _b.next(); !_c.done; _c = _b.next()) {
              var layer = _c.value;
              var layerOutputs = Array.isArray(layer.output) ? layer.output : [layer.output];
              var layerOutputNames = layerOutputs.map(function(output) {
                return output.name;
              });
              for (var i = 0; i < symbolicTensorNames.length; ++i) {
                var index = layerOutputNames.indexOf(symbolicTensorNames[i]);
                if (index !== -1) {
                  outputSymbolicTensors[i] = layerOutputs[index];
                  outputsRemaining--;
                }
                if (outputsRemaining === 0) {
                  break;
                }
              }
              if (outputsRemaining === 0) {
                break;
              }
            }
          } catch (e_6_1) {
            e_6 = { error: e_6_1 };
          } finally {
            try {
              if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
            } finally {
              if (e_6) throw e_6.error;
            }
          }
          if (outputsRemaining > 0) {
            var remainingNames_1 = [];
            outputSymbolicTensors.forEach(function(tensor, i2) {
              if (tensor == null) {
                remainingNames_1.push(symbolicTensorNames[i2]);
              }
            });
            throw new ValueError("Cannot find SymbolicTensors for output name(s): " + "".concat(JSON.stringify(remainingNames_1)));
          }
          return outputSymbolicTensors;
        };
        LayersModel2.prototype.predictLoop = function(ins, batchSize, verbose) {
          var _this = this;
          if (batchSize === void 0) {
            batchSize = 32;
          }
          if (verbose === void 0) {
            verbose = false;
          }
          return tfc__namespace.tidy(function() {
            var numSamples = _this.checkNumSamples(ins);
            if (verbose) {
              throw new NotImplementedError("Verbose predictLoop() is not implemented yet.");
            }
            var batches = makeBatches(numSamples, batchSize);
            var outsBatches = _this.outputs.map(function(output) {
              return [];
            });
            var _loop_3 = function(batchIndex2) {
              var batchOuts = tfc__namespace.tidy(function() {
                var batchStart = batches[batchIndex2][0];
                var batchEnd = batches[batchIndex2][1];
                var insBatch = sliceArrays(ins, batchStart, batchEnd);
                var feeds = [];
                if (Array.isArray(insBatch)) {
                  for (var i = 0; i < insBatch.length; ++i) {
                    feeds.push({ key: _this.inputs[i], value: insBatch[i] });
                  }
                } else {
                  feeds.push({ key: _this.inputs[0], value: insBatch });
                }
                var feedDict = new FeedDict(feeds);
                return execute(_this.outputs, feedDict);
              });
              batchOuts.forEach(function(batchOut, i) {
                return outsBatches[i].push(batchOut);
              });
            };
            for (var batchIndex = 0; batchIndex < batches.length; ++batchIndex) {
              _loop_3(batchIndex);
            }
            return singletonOrArray(outsBatches.map(function(batches2) {
              return tfc__namespace.concat(batches2, 0);
            }));
          });
        };
        LayersModel2.prototype.predict = function(x, args) {
          if (args === void 0) {
            args = {};
          }
          var xsRank2OrHigher = ensureTensorsRank2OrHigher(x);
          checkInputData(xsRank2OrHigher, this.inputNames, this.feedInputShapes, false);
          try {
            var batchSize = args.batchSize == null ? 32 : args.batchSize;
            checkBatchSize(batchSize);
            return this.predictLoop(xsRank2OrHigher, batchSize);
          } finally {
            disposeNewTensors(xsRank2OrHigher, x);
          }
        };
        LayersModel2.prototype.predictOnBatch = function(x) {
          checkInputData(x, this.inputNames, this.feedInputShapes, true);
          var batchSize = (Array.isArray(x) ? x[0] : x).shape[0];
          return this.predictLoop(x, batchSize);
        };
        LayersModel2.prototype.standardizeUserDataXY = function(x, y, checkBatchAxis, batchSize) {
          if (this.optimizer_ == null) {
            throw new RuntimeError("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");
          }
          var outputShapes = [];
          for (var i = 0; i < this.feedOutputShapes.length; ++i) {
            var outputShape = this.feedOutputShapes[i];
            var lossFn = this.feedLossFns[i];
            if (lossFn === sparseCategoricalCrossentropy$1) {
              outputShapes.push(outputShape.slice(0, outputShape.length - 1).concat([1]));
            } else {
              outputShapes.push(outputShape);
            }
          }
          x = standardizeInputData(x, this.feedInputNames, this.feedInputShapes, false, "input");
          y = standardizeInputData(y, this.feedOutputNames, outputShapes, false, "target");
          checkArrayLengths(x, y);
          checkLossAndTargetCompatibility(y, this.feedLossFns, this.feedOutputShapes);
          if (this.stateful && batchSize != null && batchSize > 0) {
            if (x[0].shape[0] % batchSize !== 0) {
              throw new ValueError("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size " + "".concat(batchSize, ". Found: ").concat(x[0].shape[0], " sample(s)."));
            }
          }
          return [x, y];
        };
        LayersModel2.prototype.standardizeUserData = function(x, y, sampleWeight, classWeight, checkBatchAxis, batchSize) {
          if (checkBatchAxis === void 0) {
            checkBatchAxis = true;
          }
          return __awaiter(this, void 0, void 0, function() {
            var _a2, standardXs, standardYs, standardSampleWeights, classWeights, i, _b, _c;
            return __generator(this, function(_d) {
              switch (_d.label) {
                case 0:
                  _a2 = __read(this.standardizeUserDataXY(x, y, checkBatchAxis, batchSize), 2), standardXs = _a2[0], standardYs = _a2[1];
                  if (sampleWeight != null) {
                    throw new Error("sample weight is not supported yet.");
                  }
                  standardSampleWeights = null;
                  if (!(classWeight != null)) return [3, 4];
                  classWeights = standardizeClassWeights(classWeight, this.outputNames);
                  standardSampleWeights = [];
                  i = 0;
                  _d.label = 1;
                case 1:
                  if (!(i < classWeights.length)) return [3, 4];
                  _c = (_b = standardSampleWeights).push;
                  return [4, standardizeWeights(standardYs[i], null, classWeights[i])];
                case 2:
                  _c.apply(_b, [_d.sent()]);
                  _d.label = 3;
                case 3:
                  ++i;
                  return [3, 1];
                case 4:
                  return [2, [standardXs, standardYs, standardSampleWeights]];
              }
            });
          });
        };
        LayersModel2.prototype.testLoop = function(f, ins, batchSize, verbose, steps) {
          var _this = this;
          if (verbose === void 0) {
            verbose = 0;
          }
          return tfc__namespace.tidy(function() {
            var numSamples = _this.checkNumSamples(ins, batchSize, steps, "steps");
            var outs = [];
            if (verbose > 0) {
              throw new NotImplementedError("Verbose mode is not implemented yet.");
            }
            if (steps != null) {
              throw new NotImplementedError("steps mode in testLoop() is not implemented yet");
            } else {
              var batches = makeBatches(numSamples, batchSize);
              var indexArray = tfc.tensor1d(range(0, numSamples));
              for (var batchIndex = 0; batchIndex < batches.length; ++batchIndex) {
                var batchStart = batches[batchIndex][0];
                var batchEnd = batches[batchIndex][1];
                var batchIds = sliceAlongFirstAxis(indexArray, batchStart, batchEnd - batchStart);
                var insBatch = sliceArraysByIndices(ins, batchIds);
                var batchOuts = f(insBatch);
                if (batchIndex === 0) {
                  for (var i = 0; i < batchOuts.length; ++i) {
                    outs.push(tfc.scalar(0));
                  }
                }
                for (var i = 0; i < batchOuts.length; ++i) {
                  var batchOut = batchOuts[i];
                  outs[i] = tfc__namespace.add(outs[i], tfc__namespace.mul(batchEnd - batchStart, batchOut));
                }
              }
              for (var i = 0; i < outs.length; ++i) {
                outs[i] = tfc__namespace.div(outs[i], numSamples);
              }
            }
            return outs;
          });
        };
        LayersModel2.prototype.getDedupedMetricsNames = function() {
          var outLabels = this.metricsNames;
          var dedupedOutLabels = [];
          for (var i = 0; i < outLabels.length; ++i) {
            var label = outLabels[i];
            var newLabel = label;
            if (count(outLabels, label) > 1) {
              var dupIndex = count(outLabels.slice(0, i), label);
              newLabel += "_".concat(dupIndex);
            }
            dedupedOutLabels.push(newLabel);
          }
          return dedupedOutLabels;
        };
        LayersModel2.prototype.makeTrainFunction = function() {
          var _this = this;
          return function(data) {
            var lossValues = [];
            var inputs = data.slice(0, _this.inputs.length);
            var targets = data.slice(_this.inputs.length, _this.inputs.length + _this.outputs.length);
            var sampleWeights = data.slice(_this.inputs.length + _this.outputs.length, _this.inputs.length + _this.outputs.length * 2);
            var metricsValues = [];
            var totalLossFunction = function() {
              var feeds = [];
              for (var i = 0; i < _this.inputs.length; ++i) {
                feeds.push({ key: _this.inputs[i], value: inputs[i] });
              }
              var feedDict = new FeedDict(feeds);
              var outputs = execute(_this.outputs, feedDict, { "training": true });
              var totalLoss;
              for (var i = 0; i < _this.lossFunctions.length; ++i) {
                var lossFunction = _this.lossFunctions[i];
                var loss = lossFunction(targets[i], outputs[i]);
                if (sampleWeights[i] != null) {
                  loss = computeWeightedLoss(loss, sampleWeights[i]);
                }
                var meanLoss = tfc__namespace.mean(loss);
                lossValues.push(meanLoss);
                if (i === 0) {
                  totalLoss = loss;
                } else {
                  totalLoss = tfc__namespace.add(totalLoss, loss);
                }
              }
              for (var i = 0; i < _this.metricsTensors.length; ++i) {
                var weightedMetric = void 0;
                if (_this.outputs.length > 1 && i < _this.outputs.length) {
                  weightedMetric = lossValues[i];
                } else {
                  var metric = _this.metricsTensors[i][0];
                  var outputIndex = _this.metricsTensors[i][1];
                  weightedMetric = tfc__namespace.mean(metric(targets[outputIndex], outputs[outputIndex]));
                }
                tfc__namespace.keep(weightedMetric);
                metricsValues.push(weightedMetric);
              }
              totalLoss = tfc__namespace.mean(totalLoss);
              _this.calculateLosses().forEach(function(regularizerLoss) {
                totalLoss = tfc__namespace.add(totalLoss, regularizerLoss);
              });
              return totalLoss;
            };
            var variables = _this.collectedTrainableWeights.map(function(param) {
              return param.read();
            });
            var returnCost = true;
            var totalLossValue = _this.optimizer_.minimize(totalLossFunction, returnCost, variables);
            return [totalLossValue].concat(metricsValues);
          };
        };
        LayersModel2.prototype.makeTestFunction = function() {
          var _this = this;
          this.testFunction = function(data) {
            return tfc__namespace.tidy(function() {
              var valOutputs = [];
              var totalLoss;
              var inputs = data.slice(0, _this.inputs.length);
              var targets = data.slice(_this.inputs.length, _this.inputs.length + _this.outputs.length);
              var feeds = [];
              for (var i = 0; i < _this.inputs.length; ++i) {
                feeds.push({ key: _this.inputs[i], value: inputs[i] });
              }
              var feedDict = new FeedDict(feeds);
              var outputs = execute(_this.outputs, feedDict);
              for (var i = 0; i < _this.lossFunctions.length; ++i) {
                var lossFunction = _this.lossFunctions[i];
                var loss = tfc__namespace.mean(lossFunction(targets[i], outputs[i]));
                if (i === 0) {
                  totalLoss = loss;
                } else {
                  totalLoss = tfc__namespace.add(totalLoss, loss);
                }
                valOutputs.push(totalLoss);
              }
              for (var i = 0; i < _this.metricsTensors.length; ++i) {
                var metric = _this.metricsTensors[i][0];
                var outputIndex = _this.metricsTensors[i][1];
                var meanMetric = tfc__namespace.mean(metric(targets[outputIndex], outputs[outputIndex]));
                valOutputs.push(meanMetric);
              }
              return valOutputs;
            });
          };
        };
        LayersModel2.prototype.fit = function(x, y, args) {
          if (args === void 0) {
            args = {};
          }
          return __awaiter(this, void 0, void 0, function() {
            var inputs, targets, originalInputs, originalTargets, inputValX, inputValY, valX, valY, sampleWeights, batchSize, checkBatchAxis, standardizedOuts, doValidation, valIns, checkBatchAxis_1, valStandardized, splitAt, originalBatchSize, ins, trainFunction, outLabels, valFunction, callbackMetrics, callbacks2, out;
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  if (this.isTraining) {
                    throw new Error("Cannot start training because another fit() call is ongoing.");
                  }
                  this.isTraining = true;
                  _a2.label = 1;
                case 1:
                  _a2.trys.push([1, , 7, 8]);
                  batchSize = args.batchSize == null ? 32 : args.batchSize;
                  checkBatchSize(batchSize);
                  checkBatchAxis = false;
                  return [4, this.standardizeUserData(x, y, args.sampleWeight, args.classWeight, checkBatchAxis, batchSize)];
                case 2:
                  standardizedOuts = _a2.sent();
                  inputs = standardizedOuts[0];
                  targets = standardizedOuts[1];
                  sampleWeights = standardizedOuts[2];
                  doValidation = false;
                  valIns = void 0;
                  if (!(args.validationData != null && args.validationData.length > 0)) return [3, 4];
                  doValidation = true;
                  if (args.validationData.length === 2) {
                    inputValX = args.validationData[0];
                    inputValY = args.validationData[1];
                  } else if (args.validationData.length === 3) {
                    throw new NotImplementedError("validationData including sample weights is not supported yet.");
                  } else {
                    throw new ValueError("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; " + "".concat(args.validationData, " is invalid."));
                  }
                  checkBatchAxis_1 = true;
                  return [4, this.standardizeUserData(
                    inputValX,
                    inputValY,
                    null,
                    /** Unused sample weights. */
                    null,
                    /** Unused class weights. */
                    checkBatchAxis_1,
                    batchSize
                  )];
                case 3:
                  valStandardized = _a2.sent();
                  valX = valStandardized[0];
                  valY = valStandardized[1];
                  valIns = valX.concat(valY);
                  return [3, 5];
                case 4:
                  if (args.validationSplit != null && args.validationSplit > 0 && args.validationSplit < 1) {
                    doValidation = true;
                    splitAt = Math.floor(inputs[0].shape[0] * (1 - args.validationSplit));
                    originalBatchSize = inputs[0].shape[0];
                    valX = sliceArrays(inputs, splitAt, originalBatchSize);
                    originalInputs = inputs;
                    inputs = sliceArrays(inputs, 0, splitAt);
                    valY = sliceArrays(targets, splitAt, originalBatchSize);
                    originalTargets = targets;
                    targets = sliceArrays(targets, 0, splitAt);
                    valIns = valX.concat(valY);
                  } else if (args.validationSteps != null) {
                    doValidation = true;
                  }
                  _a2.label = 5;
                case 5:
                  ins = inputs.concat(targets).concat(sampleWeights);
                  this.checkTrainableWeightsConsistency();
                  trainFunction = this.makeTrainFunction();
                  outLabels = this.getDedupedMetricsNames();
                  valFunction = void 0;
                  callbackMetrics = void 0;
                  if (doValidation) {
                    this.makeTestFunction();
                    valFunction = this.testFunction;
                    callbackMetrics = outLabels.slice().concat(outLabels.map(function(n) {
                      return "val_" + n;
                    }));
                  } else {
                    valFunction = null;
                    valIns = [];
                    callbackMetrics = outLabels.slice();
                  }
                  callbacks2 = standardizeCallbacks(args.callbacks, args.yieldEvery);
                  return [4, this.fitLoop(trainFunction, ins, outLabels, batchSize, args.epochs, args.verbose, callbacks2, valFunction, valIns, args.shuffle, callbackMetrics, args.initialEpoch, null, null)];
                case 6:
                  out = _a2.sent();
                  return [2, out];
                case 7:
                  this.isTraining = false;
                  disposeNewTensors(inputs, x);
                  disposeNewTensors(targets, y);
                  disposeNewTensors(originalInputs, x);
                  disposeNewTensors(originalTargets, y);
                  disposeNewTensors(valX, inputValX);
                  disposeNewTensors(valY, inputValY);
                  if (sampleWeights != null) {
                    tfc__namespace.dispose(sampleWeights);
                  }
                  return [
                    7
                    /*endfinally*/
                  ];
                case 8:
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        LayersModel2.prototype.fitLoop = function(f, ins, outLabels, batchSize, epochs, verbose, callbacks2, valF, valIns, shuffle, callbackMetrics, initialEpoch, stepsPerEpoch, validationSteps) {
          return __awaiter(this, void 0, void 0, function() {
            var doValidation, numTrainSamples, indexArray, _a2, callbackList, history, _loop_4, this_1, epoch, state_1;
            var _this = this;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  if (batchSize == null) {
                    batchSize = 32;
                  }
                  if (epochs == null) {
                    epochs = 1;
                  }
                  if (shuffle == null) {
                    shuffle = true;
                  }
                  if (initialEpoch == null) {
                    initialEpoch = 0;
                  }
                  doValidation = false;
                  if (valF != null && valIns != null) {
                    doValidation = true;
                  }
                  if (validationSteps != null) {
                    doValidation = true;
                    if (stepsPerEpoch == null) {
                      throw new ValueError("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");
                    }
                  }
                  numTrainSamples = this.checkNumSamples(ins, batchSize, stepsPerEpoch, "steps_per_epoch");
                  if (numTrainSamples != null) {
                    indexArray = range(0, numTrainSamples);
                  }
                  if (verbose == null) {
                    verbose = 1;
                  }
                  _a2 = configureCallbacks(callbacks2, verbose, epochs, initialEpoch, numTrainSamples, stepsPerEpoch, batchSize, doValidation, callbackMetrics), callbackList = _a2.callbackList, history = _a2.history;
                  callbackList.setModel(this);
                  this.history = history;
                  return [4, callbackList.onTrainBegin()];
                case 1:
                  _b.sent();
                  this.stopTraining_ = false;
                  _loop_4 = function(epoch2) {
                    var epochLogs, epochIndexArray1D_1, batches_1, _loop_5, batchIndex, state_2;
                    return __generator(this, function(_c) {
                      switch (_c.label) {
                        case 0:
                          return [4, callbackList.onEpochBegin(epoch2)];
                        case 1:
                          _c.sent();
                          epochLogs = {};
                          if (!(stepsPerEpoch != null)) return [3, 2];
                          throw new NotImplementedError("stepsPerEpoch mode is not implemented yet.");
                        case 2:
                          if (shuffle === "batch") {
                            throw new NotImplementedError("batch shuffling is not implemneted yet");
                          } else if (shuffle) {
                            tfc.util.shuffle(indexArray);
                          }
                          epochIndexArray1D_1 = tfc.tensor1d(indexArray);
                          batches_1 = makeBatches(numTrainSamples, batchSize);
                          _loop_5 = function(batchIndex2) {
                            var batchLogs;
                            return __generator(this, function(_d) {
                              switch (_d.label) {
                                case 0:
                                  batchLogs = {};
                                  return [4, callbackList.onBatchBegin(batchIndex2, batchLogs)];
                                case 1:
                                  _d.sent();
                                  tfc__namespace.tidy(function() {
                                    var batchStart = batches_1[batchIndex2][0];
                                    var batchEnd = batches_1[batchIndex2][1];
                                    var batchIds = sliceAlongFirstAxis(epochIndexArray1D_1, batchStart, batchEnd - batchStart);
                                    batchLogs["batch"] = batchIndex2;
                                    batchLogs["size"] = batchEnd - batchStart;
                                    var insBatch = sliceArraysByIndices(ins, batchIds);
                                    var outs = f(insBatch);
                                    for (var i = 0; i < outLabels.length; ++i) {
                                      var label = outLabels[i];
                                      var out = outs[i];
                                      batchLogs[label] = out;
                                      tfc__namespace.keep(out);
                                    }
                                    if (batchIndex2 === batches_1.length - 1) {
                                      if (doValidation) {
                                        var valOuts = _this.testLoop(valF, valIns, batchSize);
                                        for (var i = 0; i < outLabels.length; ++i) {
                                          var label = outLabels[i];
                                          var out = valOuts[i];
                                          tfc__namespace.keep(out);
                                          epochLogs["val_" + label] = out;
                                        }
                                      }
                                    }
                                  });
                                  return [4, callbackList.onBatchEnd(batchIndex2, batchLogs)];
                                case 2:
                                  _d.sent();
                                  disposeTensorsInLogs(batchLogs);
                                  if (this_1.stopTraining_) {
                                    return [2, "break"];
                                  }
                                  return [
                                    2
                                    /*return*/
                                  ];
                              }
                            });
                          };
                          batchIndex = 0;
                          _c.label = 3;
                        case 3:
                          if (!(batchIndex < batches_1.length)) return [3, 6];
                          return [5, _loop_5(batchIndex)];
                        case 4:
                          state_2 = _c.sent();
                          if (state_2 === "break")
                            return [3, 6];
                          _c.label = 5;
                        case 5:
                          ++batchIndex;
                          return [3, 3];
                        case 6:
                          epochIndexArray1D_1.dispose();
                          _c.label = 7;
                        case 7:
                          return [4, callbackList.onEpochEnd(epoch2, epochLogs)];
                        case 8:
                          _c.sent();
                          if (this_1.stopTraining_) {
                            return [2, "break"];
                          }
                          return [
                            2
                            /*return*/
                          ];
                      }
                    });
                  };
                  this_1 = this;
                  epoch = initialEpoch;
                  _b.label = 2;
                case 2:
                  if (!(epoch < epochs)) return [3, 5];
                  return [5, _loop_4(epoch)];
                case 3:
                  state_1 = _b.sent();
                  if (state_1 === "break")
                    return [3, 5];
                  _b.label = 4;
                case 4:
                  ++epoch;
                  return [3, 2];
                case 5:
                  return [4, callbackList.onTrainEnd()];
                case 6:
                  _b.sent();
                  return [4, this.history.syncData()];
                case 7:
                  _b.sent();
                  return [2, this.history];
              }
            });
          });
        };
        LayersModel2.prototype.fitDataset = function(dataset, args) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              return [2, fitDataset(this, dataset, args)];
            });
          });
        };
        LayersModel2.prototype.trainOnBatch = function(x, y) {
          return __awaiter(this, void 0, void 0, function() {
            var standardizeOut, inputs, targets, trainFunction, losses, lossValues, losses_1, losses_1_1, loss, v, e_7_1;
            var e_7, _a2;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  return [4, this.standardizeUserData(x, y)];
                case 1:
                  standardizeOut = _b.sent();
                  inputs = standardizeOut[0];
                  targets = standardizeOut[1];
                  trainFunction = this.makeTrainFunction();
                  losses = trainFunction(inputs.concat(targets));
                  lossValues = [];
                  _b.label = 2;
                case 2:
                  _b.trys.push([2, 7, 8, 9]);
                  losses_1 = __values(losses), losses_1_1 = losses_1.next();
                  _b.label = 3;
                case 3:
                  if (!!losses_1_1.done) return [3, 6];
                  loss = losses_1_1.value;
                  return [4, loss.data()];
                case 4:
                  v = _b.sent();
                  lossValues.push(v[0]);
                  _b.label = 5;
                case 5:
                  losses_1_1 = losses_1.next();
                  return [3, 3];
                case 6:
                  return [3, 9];
                case 7:
                  e_7_1 = _b.sent();
                  e_7 = { error: e_7_1 };
                  return [3, 9];
                case 8:
                  try {
                    if (losses_1_1 && !losses_1_1.done && (_a2 = losses_1.return)) _a2.call(losses_1);
                  } finally {
                    if (e_7) throw e_7.error;
                  }
                  return [
                    7
                    /*endfinally*/
                  ];
                case 9:
                  tfc__namespace.dispose(losses);
                  disposeNewTensors(standardizeOut[0], x);
                  disposeNewTensors(standardizeOut[1], y);
                  return [2, singletonOrArray(lossValues)];
              }
            });
          });
        };
        LayersModel2.prototype.getNamedWeights = function(config) {
          var namedWeights = [];
          var trainableOnly = config != null && config.trainableOnly;
          var weights = trainableOnly ? this.trainableWeights : this.weights;
          var weightValues = this.getWeights(trainableOnly);
          for (var i = 0; i < weights.length; ++i) {
            if (trainableOnly && !weights[i].trainable) {
              continue;
            }
            namedWeights.push({ name: weights[i].originalName, tensor: weightValues[i] });
          }
          return namedWeights;
        };
        Object.defineProperty(LayersModel2.prototype, "stopTraining", {
          get: function() {
            return this.stopTraining_;
          },
          /**
           * Setter used for force stopping of LayersModel.fit() (i.e., training).
           *
           * Example:
           *
           * ```js
           * const input = tf.input({shape: [10]});
           * const output = tf.layers.dense({units: 1}).apply(input);
           * const model = tf.model({inputs: [input], outputs: [output]});
           * model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
           * const xs = tf.ones([8, 10]);
           * const ys = tf.zeros([8, 1]);
           *
           * const history = await model.fit(xs, ys, {
           *   epochs: 10,
           *   callbacks: {
           *     onEpochEnd: async (epoch, logs) => {
           *       if (epoch === 2) {
           *         model.stopTraining = true;
           *       }
           *     }
           *   }
           * });
           *
           * // There should be only 3 values in the loss array, instead of 10
           * values,
           * // due to the stopping after 3 epochs.
           * console.log(history.history.loss);
           * ```
           */
          set: function(stop) {
            this.stopTraining_ = stop;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(LayersModel2.prototype, "optimizer", {
          get: function() {
            return this.optimizer_;
          },
          set: function(optimizer) {
            if (this.optimizer_ !== optimizer) {
              this.optimizer_ = optimizer;
              this.isOptimizerOwned = false;
            }
          },
          enumerable: false,
          configurable: true
        });
        LayersModel2.prototype.dispose = function() {
          var result = _super.prototype.dispose.call(this);
          if (result.refCountAfterDispose === 0 && this.optimizer != null && this.isOptimizerOwned) {
            var numTensorsBeforeOptmizerDisposal = tfc__namespace.memory().numTensors;
            this.optimizer_.dispose();
            result.numDisposedVariables += numTensorsBeforeOptmizerDisposal - tfc__namespace.memory().numTensors;
          }
          return result;
        };
        LayersModel2.prototype.getLossIdentifiers = function() {
          var e_8, _a2, e_9, _b;
          var lossNames;
          if (typeof this.loss === "string") {
            lossNames = toSnakeCase(this.loss);
          } else if (Array.isArray(this.loss)) {
            try {
              for (var _c = __values(this.loss), _d = _c.next(); !_d.done; _d = _c.next()) {
                var loss = _d.value;
                if (typeof loss !== "string") {
                  throw new Error("Serialization of non-string loss is not supported.");
                }
              }
            } catch (e_8_1) {
              e_8 = { error: e_8_1 };
            } finally {
              try {
                if (_d && !_d.done && (_a2 = _c.return)) _a2.call(_c);
              } finally {
                if (e_8) throw e_8.error;
              }
            }
            lossNames = this.loss.map(function(name) {
              return toSnakeCase(name);
            });
          } else {
            var outputNames = Object.keys(this.loss);
            lossNames = {};
            var losses_2 = this.loss;
            try {
              for (var outputNames_2 = __values(outputNames), outputNames_2_1 = outputNames_2.next(); !outputNames_2_1.done; outputNames_2_1 = outputNames_2.next()) {
                var outputName = outputNames_2_1.value;
                if (typeof losses_2[outputName] === "string") {
                  lossNames[outputName] = toSnakeCase(losses_2[outputName]);
                } else {
                  throw new Error("Serialization of non-string loss is not supported.");
                }
              }
            } catch (e_9_1) {
              e_9 = { error: e_9_1 };
            } finally {
              try {
                if (outputNames_2_1 && !outputNames_2_1.done && (_b = outputNames_2.return)) _b.call(outputNames_2);
              } finally {
                if (e_9) throw e_9.error;
              }
            }
          }
          return lossNames;
        };
        LayersModel2.prototype.getMetricIdentifiers = function() {
          if (typeof this.metrics === "string" || typeof this.metrics === "function") {
            return [toSnakeCase(getLossOrMetricName(this.metrics))];
          } else if (Array.isArray(this.metrics)) {
            return this.metrics.map(function(metric) {
              return toSnakeCase(getLossOrMetricName(metric));
            });
          } else {
            var metricsIdentifiers = {};
            for (var key in this.metrics) {
              metricsIdentifiers[key] = toSnakeCase(getLossOrMetricName(this.metrics[key]));
            }
            return metricsIdentifiers;
          }
        };
        LayersModel2.prototype.getTrainingConfig = function() {
          return {
            loss: this.getLossIdentifiers(),
            metrics: this.getMetricIdentifiers(),
            optimizer_config: {
              class_name: this.optimizer.getClassName(),
              config: this.optimizer.getConfig()
            }
          };
        };
        LayersModel2.prototype.loadTrainingConfig = function(trainingConfig) {
          if (trainingConfig.weighted_metrics != null) {
            throw new Error("Loading weight_metrics is not supported yet.");
          }
          if (trainingConfig.loss_weights != null) {
            throw new Error("Loading loss_weights is not supported yet.");
          }
          if (trainingConfig.sample_weight_mode != null) {
            throw new Error("Loading sample_weight_mode is not supported yet.");
          }
          var tsConfig = convertPythonicToTs(trainingConfig.optimizer_config);
          var optimizer = deserialize(tsConfig);
          var loss;
          if (typeof trainingConfig.loss === "string") {
            loss = toCamelCase(trainingConfig.loss);
          } else if (Array.isArray(trainingConfig.loss)) {
            loss = trainingConfig.loss.map(function(lossEntry) {
              return toCamelCase(lossEntry);
            });
          } else if (trainingConfig.loss != null) {
            loss = {};
            for (var key in trainingConfig.loss) {
              loss[key] = toCamelCase(trainingConfig.loss[key]);
            }
          }
          var metrics;
          if (Array.isArray(trainingConfig.metrics)) {
            metrics = trainingConfig.metrics.map(function(metric) {
              return toCamelCase(metric);
            });
          } else if (trainingConfig.metrics != null) {
            metrics = {};
            for (var key in trainingConfig.metrics) {
              metrics[key] = toCamelCase(trainingConfig.metrics[key]);
            }
          }
          this.compile({ loss, metrics, optimizer });
        };
        LayersModel2.prototype.save = function(handlerOrURL, config) {
          return __awaiter(this, void 0, void 0, function() {
            var handlers, weightDataAndSpecs, returnString, unusedArg, modelConfig, modelArtifacts, includeOptimizer, weightType, _a2, optimizerWeightData, optimizerWeightSpecs, _b, _c, checkSize;
            var _d;
            return __generator(this, function(_e) {
              switch (_e.label) {
                case 0:
                  if (typeof handlerOrURL === "string") {
                    handlers = tfc.io.getSaveHandlers(handlerOrURL);
                    if (handlers.length === 0) {
                      throw new ValueError("Cannot find any save handlers for URL '".concat(handlerOrURL, "'"));
                    } else if (handlers.length > 1) {
                      throw new ValueError("Found more than one (".concat(handlers.length, ") save handlers for ") + "URL '".concat(handlerOrURL, "'"));
                    }
                    handlerOrURL = handlers[0];
                  }
                  if (handlerOrURL.save == null) {
                    throw new ValueError("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");
                  }
                  return [4, tfc.io.encodeWeights(this.getNamedWeights(config))];
                case 1:
                  weightDataAndSpecs = _e.sent();
                  returnString = false;
                  unusedArg = null;
                  modelConfig = this.toJSON(unusedArg, returnString);
                  modelArtifacts = {
                    modelTopology: modelConfig,
                    format: LAYERS_MODEL_FORMAT_NAME,
                    generatedBy: "TensorFlow.js tfjs-layers v".concat(version),
                    convertedBy: null
                  };
                  includeOptimizer = config == null ? false : config.includeOptimizer;
                  if (!(includeOptimizer && this.optimizer != null)) return [3, 4];
                  modelArtifacts.trainingConfig = this.getTrainingConfig();
                  weightType = "optimizer";
                  _c = (_b = tfc.io).encodeWeights;
                  return [4, this.optimizer.getWeights()];
                case 2:
                  return [4, _c.apply(_b, [_e.sent(), weightType])];
                case 3:
                  _a2 = _e.sent(), optimizerWeightData = _a2.data, optimizerWeightSpecs = _a2.specs;
                  (_d = weightDataAndSpecs.specs).push.apply(_d, __spreadArray([], __read(optimizerWeightSpecs), false));
                  weightDataAndSpecs.data = tfc.io.concatenateArrayBuffers([weightDataAndSpecs.data, optimizerWeightData]);
                  _e.label = 4;
                case 4:
                  if (this.userDefinedMetadata != null) {
                    checkSize = true;
                    checkUserDefinedMetadata(this.userDefinedMetadata, this.name, checkSize);
                    modelArtifacts.userDefinedMetadata = this.userDefinedMetadata;
                  }
                  modelArtifacts.weightData = weightDataAndSpecs.data;
                  modelArtifacts.weightSpecs = weightDataAndSpecs.specs;
                  return [2, handlerOrURL.save(modelArtifacts)];
              }
            });
          });
        };
        LayersModel2.prototype.setUserDefinedMetadata = function(userDefinedMetadata) {
          checkUserDefinedMetadata(userDefinedMetadata, this.name);
          this.userDefinedMetadata = userDefinedMetadata;
        };
        LayersModel2.prototype.getUserDefinedMetadata = function() {
          return this.userDefinedMetadata;
        };
        return LayersModel2;
      }(Container)
    );
    LayersModel.className = "Model";
    tfc.serialization.registerClass(LayersModel);
    var Functional = (
      /** @class */
      function(_super) {
        __extends(Functional2, _super);
        function Functional2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        return Functional2;
      }(LayersModel)
    );
    Functional.className = "Functional";
    tfc.serialization.registerClass(Functional);
    function modelFromJSON(modelAndWeightsConfig, customObjects) {
      return __awaiter(this, void 0, void 0, function() {
        var modelTopology, tsConfig, model2, weightValues, uniqueWeightValues, _a2, _b, weight;
        var e_12, _c;
        return __generator(this, function(_d) {
          switch (_d.label) {
            case 0:
              if (!("modelTopology" in modelAndWeightsConfig)) {
                modelAndWeightsConfig = { modelTopology: modelAndWeightsConfig };
              }
              modelAndWeightsConfig = modelAndWeightsConfig;
              modelTopology = modelAndWeightsConfig.modelTopology;
              if (modelTopology["model_config"] != null) {
                modelTopology = modelTopology["model_config"];
              }
              tsConfig = convertPythonicToTs(modelTopology);
              model2 = deserialize(tsConfig, customObjects);
              if (!(modelAndWeightsConfig.weightsManifest != null)) return [3, 2];
              return [4, tfc.io.loadWeights(modelAndWeightsConfig.weightsManifest, modelAndWeightsConfig.pathPrefix, model2.weights.map(function(weight2) {
                return weight2.originalName;
              }))];
            case 1:
              weightValues = _d.sent();
              uniqueWeightValues = {};
              try {
                for (_a2 = __values(model2.weights), _b = _a2.next(); !_b.done; _b = _a2.next()) {
                  weight = _b.value;
                  uniqueWeightValues[weight.originalName] = weightValues[weight.originalName];
                }
              } catch (e_1_1) {
                e_12 = { error: e_1_1 };
              } finally {
                try {
                  if (_b && !_b.done && (_c = _a2.return)) _c.call(_a2);
                } finally {
                  if (e_12) throw e_12.error;
                }
              }
              model2.loadWeights(uniqueWeightValues);
              tfc.dispose(weightValues);
              _d.label = 2;
            case 2:
              return [2, model2];
          }
        });
      });
    }
    function loadLayersModel(pathOrIOHandler, options) {
      return __awaiter(this, void 0, void 0, function() {
        var handlers;
        return __generator(this, function(_a2) {
          if (options == null) {
            options = {};
          }
          if (typeof pathOrIOHandler === "string") {
            handlers = tfc.io.getLoadHandlers(pathOrIOHandler, options);
            if (handlers.length === 0) {
              handlers.push(tfc.io.browserHTTPRequest(pathOrIOHandler, options));
            } else if (handlers.length > 1) {
              throw new ValueError("Found more than one (".concat(handlers.length, ") load handlers for ") + "URL '".concat(pathOrIOHandler, "'"));
            }
            pathOrIOHandler = handlers[0];
          }
          return [2, loadLayersModelFromIOHandler(pathOrIOHandler, void 0, options)];
        });
      });
    }
    function loadLayersModelFromIOHandler(handler, customObjects, options) {
      return __awaiter(this, void 0, void 0, function() {
        var artifacts, modelTopology, strict, fastWeightInit, model2, trainingConfig, _a2, modelWeights, optimizerWeights;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              if (options == null) {
                options = {};
              }
              if (handler.load == null) {
                throw new ValueError("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");
              }
              return [4, handler.load()];
            case 1:
              artifacts = _b.sent();
              modelTopology = artifacts.modelTopology;
              if (modelTopology["model_config"] != null) {
                modelTopology = modelTopology["model_config"];
              }
              strict = options.strict == null ? true : options.strict;
              fastWeightInit = artifacts.weightData != null && artifacts.weightSpecs != null && strict;
              model2 = deserialize(convertPythonicToTs(modelTopology), customObjects, fastWeightInit);
              trainingConfig = artifacts.trainingConfig;
              if (trainingConfig != null) {
                model2.loadTrainingConfig(trainingConfig);
              }
              if (artifacts.userDefinedMetadata != null) {
                model2.setUserDefinedMetadata(artifacts.userDefinedMetadata);
              }
              if (!(artifacts.weightData != null)) return [3, 4];
              if (artifacts.weightSpecs == null) {
                throw new ValueError("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");
              }
              _a2 = decodeModelAndOptimizerWeights(artifacts.weightData, artifacts.weightSpecs), modelWeights = _a2.modelWeights, optimizerWeights = _a2.optimizerWeights;
              model2.loadWeights(modelWeights, strict);
              if (!(model2.optimizer != null && optimizerWeights.length > 0)) return [3, 3];
              return [4, model2.optimizer.setWeights(optimizerWeights)];
            case 2:
              _b.sent();
              _b.label = 3;
            case 3:
              tfc.dispose(modelWeights);
              tfc.dispose(optimizerWeights.map(function(w) {
                return w.tensor;
              }));
              _b.label = 4;
            case 4:
              return [2, model2];
          }
        });
      });
    }
    function decodeModelAndOptimizerWeights(weightData, specs) {
      var name2Tensor = tfc.io.decodeWeights(weightData, specs);
      var modelWeights = {};
      var optimizerWeights = [];
      specs.forEach(function(spec) {
        if (spec.group === "optimizer") {
          optimizerWeights.push({ name: spec.name, tensor: name2Tensor[spec.name] });
        } else {
          modelWeights[spec.name] = name2Tensor[spec.name];
        }
      });
      return { modelWeights, optimizerWeights };
    }
    var Sequential = (
      /** @class */
      function(_super) {
        __extends(Sequential2, _super);
        function Sequential2(args) {
          var e_2, _a2;
          var _this = _super.call(this, { inputs: [], outputs: [] }) || this;
          args = args || {};
          _this.trainable = true;
          _this.built = false;
          _this.name = args.name != null ? args.name : getUid("sequential_");
          if (args.layers != null) {
            try {
              for (var _b = __values(args.layers), _c = _b.next(); !_c.done; _c = _b.next()) {
                var layer = _c.value;
                _this.add(layer);
              }
            } catch (e_2_1) {
              e_2 = { error: e_2_1 };
            } finally {
              try {
                if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
              } finally {
                if (e_2) throw e_2.error;
              }
            }
          }
          return _this;
        }
        Sequential2.prototype.checkShape = function(layer) {
          var shape = layer.inboundNodes[0].outputTensors[0].shape;
          if (shape.some(function(x) {
            return x < 0;
          })) {
            throw new ValueError("Negative dimension size caused by adding layer " + "".concat(layer.name, " with input shape [") + "".concat(layer.inboundNodes[0].inputTensors[0].shape, "]"));
          }
        };
        Sequential2.prototype.add = function(layer) {
          var isLayerModelInstance = layer instanceof Sequential2 || layer instanceof LayersModel;
          var modelLayer;
          if (isLayerModelInstance) {
            modelLayer = layer;
            if (modelLayer.outputs.length !== 1) {
              throw new ValueError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");
            }
            if (modelLayer.inputs.length !== 1) {
              throw new ValueError("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.");
            }
          }
          if (this.outputs.length === 0) {
            if (layer.inboundNodes.length === 0) {
              if (layer.batchInputShape == null) {
                throw new ValueError("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");
              }
              var x = Input({
                batchShape: layer.batchInputShape,
                dtype: layer.dtype,
                name: layer.name + "_input"
              });
              layer.apply(x);
            }
            if (isLayerModelInstance) {
              this.outputs = modelLayer.outputs;
              this.inputs = modelLayer.inputs;
            } else {
              if (layer.inboundNodes.length !== 1) {
                throw new ValueError("A layer added to a Sequential model must not already be " + "connected somewhere else. LayersModel received layer ".concat(layer.name, " ") + "which has ".concat(layer.inboundNodes.length, " pre-existing inbound ") + "connections.");
              }
              if (layer.inboundNodes[0].outputTensors.length !== 1) {
                throw new ValueError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");
              }
              this.checkShape(layer);
              this.outputs = [layer.inboundNodes[0].outputTensors[0]];
              this.inputs = getSourceInputs(this.outputs[0]);
            }
            this.inboundNodes = [];
            new Node({
              outboundLayer: this,
              inboundLayers: [],
              nodeIndices: [],
              tensorIndices: [],
              inputTensors: this.inputs,
              outputTensors: this.outputs,
              // no model-level masking for now
              inputMasks: pyListRepeat(null, this.inputs.length),
              outputMasks: [null],
              inputShapes: this.inputs.map(function(x2) {
                return x2.shape;
              }),
              outputShapes: this.outputs[0].shape
            });
          } else {
            var outputTensor = layer.apply(this.outputs[0]);
            if (Array.isArray(outputTensor)) {
              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(layer);
            this.outputs = [outputTensor];
            this.inboundNodes[0].outputTensors = this.outputs;
            this.inboundNodes[0].outputShapes = [this.outputs[0].shape];
          }
          this.layers.push(layer);
          this.built = false;
        };
        Sequential2.prototype.pop = function() {
          if (this.layers.length === 0) {
            throw new TypeError("There are no layers in the model.");
          }
          this.layers.pop();
          if (this.layers.length === 0) {
            this.outputs = [];
            this.inboundNodes = [];
            this.outboundNodes = [];
          } else {
            var lastLayerIndex = this.layers.length - 1;
            this.layers[lastLayerIndex].outboundNodes = [];
            this.outputs = [this.layers[lastLayerIndex].output];
            this.inboundNodes[0].outputTensors = this.outputs;
            this.inboundNodes[0].outputShapes = [this.outputs[0].shape];
          }
        };
        Sequential2.prototype.call = function(inputs, kwargs) {
          if (this.model == null) {
            this.build();
          }
          return this.model.call(inputs, kwargs);
        };
        Sequential2.prototype.build = function(inputShape) {
          getExactlyOneShape(inputShape);
          if (this.inputs.length === 0 || this.outputs.length === 0) {
            throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");
          }
          this.model = new LayersModel({
            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 = true;
        };
        Sequential2.prototype.countParams = function() {
          if (!this.built) {
            this.build();
          }
          return _super.prototype.countParams.call(this);
        };
        Sequential2.prototype.summary = function(lineLength, positions, printFn) {
          if (printFn === void 0) {
            printFn = console.log;
          }
          if (!this.built) {
            this.build();
          }
          _super.prototype.summary.call(this, lineLength, positions, printFn);
        };
        Sequential2.prototype.setWeights = function(weights) {
          if (this.model == null) {
            this.build();
          }
          this.model.setWeights(weights);
        };
        Sequential2.prototype.evaluate = function(x, y, args) {
          if (args === void 0) {
            args = {};
          }
          if (!this.built) {
            throw new RuntimeError("The model needs to be compiled before being used.");
          }
          return this.model.evaluate(x, y, args);
        };
        Sequential2.prototype.evaluateDataset = function(dataset, args) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              if (!this.built) {
                throw new RuntimeError("The model needs to be compiled before being used.");
              }
              return [2, this.model.evaluateDataset(dataset, args)];
            });
          });
        };
        Sequential2.prototype.predict = function(x, args) {
          if (args === void 0) {
            args = {};
          }
          if (this.model == null) {
            this.build();
          }
          return this.model.predict(x, args);
        };
        Sequential2.prototype.predictOnBatch = function(x) {
          if (this.model == null) {
            this.build();
          }
          return this.model.predictOnBatch(x);
        };
        Sequential2.prototype.compile = function(args) {
          this.build();
          this.model.compile(args);
          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;
        };
        Object.defineProperty(Sequential2.prototype, "optimizer", {
          get: function() {
            return this.model == null ? void 0 : this.model.optimizer;
          },
          set: function(optimizer) {
            this.model.optimizer = optimizer;
          },
          enumerable: false,
          configurable: true
        });
        Sequential2.prototype.fit = function(x, y, args) {
          if (args === void 0) {
            args = {};
          }
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              if (!this.built) {
                throw new RuntimeError("The model needs to be compiled before being used.");
              }
              return [2, this.model.fit(x, y, args)];
            });
          });
        };
        Sequential2.prototype.fitDataset = function(dataset, args) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              if (!this.built) {
                throw new RuntimeError("The model needs to be compiled before being used.");
              }
              return [2, this.model.fitDataset(dataset, args)];
            });
          });
        };
        Sequential2.prototype.trainOnBatch = function(x, y) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              return [2, this.model.trainOnBatch(x, y)];
            });
          });
        };
        Sequential2.fromConfig = function(cls, config, customObjects, fastWeightInit) {
          var e_3, _a2;
          if (fastWeightInit === void 0) {
            fastWeightInit = false;
          }
          var configArray;
          var extraModelConfig = {};
          if (config instanceof Array) {
            if (!(config[0].className != null) || config[0]["className"] === "Merge") {
              throw new ValueError("Legacy serialization format not supported yet.");
            }
            configArray = config;
          } else {
            tfc.util.assert(config["layers"] != null, function() {
              return "When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field.";
            });
            configArray = config["layers"];
            delete config["layers"];
            extraModelConfig = config;
          }
          var model2 = new cls(extraModelConfig);
          if (!(model2 instanceof Sequential2)) {
            throw new NotImplementedError("Sequential.fromConfig called on non-Sequential input: ".concat(model2));
          }
          try {
            for (var configArray_1 = __values(configArray), configArray_1_1 = configArray_1.next(); !configArray_1_1.done; configArray_1_1 = configArray_1.next()) {
              var conf = configArray_1_1.value;
              var customObjects_1 = void 0;
              var layer = deserialize(conf, customObjects_1, fastWeightInit);
              if (fastWeightInit) {
                layer.setFastWeightInitDuringBuild(true);
              }
              model2.add(layer);
            }
          } catch (e_3_1) {
            e_3 = { error: e_3_1 };
          } finally {
            try {
              if (configArray_1_1 && !configArray_1_1.done && (_a2 = configArray_1.return)) _a2.call(configArray_1);
            } finally {
              if (e_3) throw e_3.error;
            }
          }
          return model2;
        };
        Object.defineProperty(Sequential2.prototype, "stopTraining", {
          get: function() {
            if (this.model == null) {
              throw new ValueError("Cannot get the stopTraining property of a sequential model before it is compiled.");
            }
            return this.model.stopTraining;
          },
          /**
           * Setter used for force stopping of LayersModel.fit() (i.e., training).
           *
           * Example:
           *
           * ```js
           * const model = tf.sequential();
           * model.add(tf.layers.dense({units: 1, inputShape: [10]}));
           * model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
           * const xs = tf.ones([8, 10]);
           * const ys = tf.zeros([8, 1]);
           *
           * const history = await model.fit(xs, ys, {
           *   epochs: 10,
           *   callbacks: {
           *     onEpochEnd: async (epoch, logs) => {
           *       if (epoch === 2) {
           *         model.stopTraining = true;
           *       }
           *     }
           *   }
           * });
           *
           * // There should be only 3 values in the loss array, instead of 10 values,
           * // due to the stopping after 3 epochs.
           * console.log(history.history.loss);
           * ```
           */
          set: function(stop) {
            if (this.model == null) {
              throw new ValueError("Cannot set the stopTraining property of a sequential model before it is compiled.");
            }
            this.model.stopTraining = stop;
          },
          enumerable: false,
          configurable: true
        });
        Sequential2.prototype.getConfig = function() {
          var e_4, _a2;
          var layers = [];
          try {
            for (var _b = __values(this.layers), _c = _b.next(); !_c.done; _c = _b.next()) {
              var layer = _c.value;
              var dict = {};
              dict["className"] = layer.getClassName();
              dict["config"] = layer.getConfig();
              layers.push(dict);
            }
          } catch (e_4_1) {
            e_4 = { error: e_4_1 };
          } finally {
            try {
              if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
            } finally {
              if (e_4) throw e_4.error;
            }
          }
          return { name: this.name, layers };
        };
        return Sequential2;
      }(LayersModel)
    );
    Sequential.className = "Sequential";
    tfc.serialization.registerClass(Sequential);
    function model(args) {
      return new LayersModel(args);
    }
    function sequential(config) {
      return new Sequential(config);
    }
    function input(config) {
      return Input(config);
    }
    function registerCallbackConstructor(verbosityLevel, callbackConstructor) {
      CallbackConstructorRegistry.registerCallbackConstructor(verbosityLevel, callbackConstructor);
    }
    var Activation$1 = (
      /** @class */
      function(_super) {
        __extends(Activation2, _super);
        function Activation2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Activation2.prototype.getConfig = function() {
          return {};
        };
        return Activation2;
      }(tfc.serialization.Serializable)
    );
    var Elu = (
      /** @class */
      function(_super) {
        __extends(Elu2, _super);
        function Elu2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Elu2.prototype.apply = function(x, alpha) {
          if (alpha === void 0) {
            alpha = 1;
          }
          return elu$1(x, alpha);
        };
        return Elu2;
      }(Activation$1)
    );
    Elu.className = "elu";
    tfc.serialization.registerClass(Elu);
    var Selu = (
      /** @class */
      function(_super) {
        __extends(Selu2, _super);
        function Selu2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Selu2.prototype.apply = function(x) {
          return tfc__namespace.selu(x);
        };
        return Selu2;
      }(Activation$1)
    );
    Selu.className = "selu";
    tfc.serialization.registerClass(Selu);
    var Relu = (
      /** @class */
      function(_super) {
        __extends(Relu2, _super);
        function Relu2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Relu2.prototype.apply = function(x) {
          return tfc__namespace.relu(x);
        };
        return Relu2;
      }(Activation$1)
    );
    Relu.className = "relu";
    tfc.serialization.registerClass(Relu);
    var Relu6 = (
      /** @class */
      function(_super) {
        __extends(Relu62, _super);
        function Relu62() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Relu62.prototype.apply = function(x) {
          return tfc.tidy(function() {
            return tfc__namespace.minimum(6, tfc__namespace.relu(x));
          });
        };
        return Relu62;
      }(Activation$1)
    );
    Relu6.className = "relu6";
    tfc.serialization.registerClass(Relu6);
    var Linear = (
      /** @class */
      function(_super) {
        __extends(Linear2, _super);
        function Linear2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Linear2.prototype.apply = function(x) {
          return x;
        };
        return Linear2;
      }(Activation$1)
    );
    Linear.className = "linear";
    tfc.serialization.registerClass(Linear);
    var Sigmoid = (
      /** @class */
      function(_super) {
        __extends(Sigmoid2, _super);
        function Sigmoid2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Sigmoid2.prototype.apply = function(x) {
          return tfc__namespace.sigmoid(x);
        };
        return Sigmoid2;
      }(Activation$1)
    );
    Sigmoid.className = "sigmoid";
    tfc.serialization.registerClass(Sigmoid);
    var HardSigmoid = (
      /** @class */
      function(_super) {
        __extends(HardSigmoid2, _super);
        function HardSigmoid2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        HardSigmoid2.prototype.apply = function(x) {
          return hardSigmoid(x);
        };
        return HardSigmoid2;
      }(Activation$1)
    );
    HardSigmoid.className = "hardSigmoid";
    tfc.serialization.registerClass(HardSigmoid);
    var Softplus = (
      /** @class */
      function(_super) {
        __extends(Softplus2, _super);
        function Softplus2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Softplus2.prototype.apply = function(x) {
          return tfc__namespace.softplus(x);
        };
        return Softplus2;
      }(Activation$1)
    );
    Softplus.className = "softplus";
    tfc.serialization.registerClass(Softplus);
    var Softsign = (
      /** @class */
      function(_super) {
        __extends(Softsign2, _super);
        function Softsign2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Softsign2.prototype.apply = function(x) {
          return softsign(x);
        };
        return Softsign2;
      }(Activation$1)
    );
    Softsign.className = "softsign";
    tfc.serialization.registerClass(Softsign);
    var Tanh = (
      /** @class */
      function(_super) {
        __extends(Tanh2, _super);
        function Tanh2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Tanh2.prototype.apply = function(x) {
          return tfc__namespace.tanh(x);
        };
        return Tanh2;
      }(Activation$1)
    );
    Tanh.className = "tanh";
    tfc.serialization.registerClass(Tanh);
    var Softmax$1 = (
      /** @class */
      function(_super) {
        __extends(Softmax2, _super);
        function Softmax2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Softmax2.prototype.apply = function(x, axis) {
          if (axis === void 0) {
            axis = -1;
          }
          return tfc__namespace.softmax(x, axis);
        };
        return Softmax2;
      }(Activation$1)
    );
    Softmax$1.className = "softmax";
    tfc.serialization.registerClass(Softmax$1);
    var LogSoftmax = (
      /** @class */
      function(_super) {
        __extends(LogSoftmax2, _super);
        function LogSoftmax2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        LogSoftmax2.prototype.apply = function(x, axis) {
          if (axis === void 0) {
            axis = -1;
          }
          return tfc__namespace.logSoftmax(x, axis);
        };
        return LogSoftmax2;
      }(Activation$1)
    );
    LogSoftmax.className = "logSoftmax";
    tfc.serialization.registerClass(LogSoftmax);
    var Gelu = (
      /** @class */
      function(_super) {
        __extends(Gelu2, _super);
        function Gelu2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Gelu2.prototype.apply = function(x) {
          return tfc.tidy(function() {
            return tfc__namespace.tidy(function() {
              var sqrtTwo = Math.sqrt(2);
              var cdf = tfc__namespace.mul(0.5, tfc__namespace.add(1, tfc__namespace.erf(tfc__namespace.div(x, sqrtTwo))));
              return tfc__namespace.mul(x, cdf);
            });
          });
        };
        return Gelu2;
      }(Activation$1)
    );
    Gelu.className = "gelu";
    tfc.serialization.registerClass(Gelu);
    var GeluNew = (
      /** @class */
      function(_super) {
        __extends(GeluNew2, _super);
        function GeluNew2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        GeluNew2.prototype.apply = function(x) {
          return tfc.tidy(function() {
            return tfc__namespace.mul(0.5, tfc__namespace.mul(x, tfc__namespace.add(1, tfc__namespace.tanh(tfc__namespace.mul(tfc__namespace.sqrt(tfc__namespace.div(2, Math.PI)), tfc__namespace.add(x, tfc__namespace.mul(0.044715, tfc__namespace.pow(x, 3))))))));
          });
        };
        return GeluNew2;
      }(Activation$1)
    );
    GeluNew.className = "gelu_new";
    tfc.serialization.registerClass(GeluNew);
    var Mish = (
      /** @class */
      function(_super) {
        __extends(Mish2, _super);
        function Mish2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Mish2.prototype.apply = function(x) {
          return tfc.tidy(function() {
            return tfc__namespace.mul(x, tfc__namespace.tanh(tfc__namespace.softplus(x)));
          });
        };
        return Mish2;
      }(Activation$1)
    );
    Mish.className = "mish";
    tfc.serialization.registerClass(Mish);
    var Swish = (
      /** @class */
      function(_super) {
        __extends(Swish2, _super);
        function Swish2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        Swish2.prototype.apply = function(x, alpha) {
          if (alpha === void 0) {
            alpha = 1;
          }
          return tfc.tidy(function() {
            return tfc__namespace.mul(tfc__namespace.sigmoid(tfc__namespace.mul(x, alpha)), x);
          });
        };
        return Swish2;
      }(Activation$1)
    );
    Swish.className = "swish";
    tfc.serialization.registerClass(Swish);
    function serializeActivation(activation2) {
      return activation2.getClassName();
    }
    function deserializeActivation(config, customObjects) {
      if (customObjects === void 0) {
        customObjects = {};
      }
      return deserializeKerasObject(config, tfc.serialization.SerializationMap.getMap().classNameMap, customObjects, "activation");
    }
    function getActivation(identifier) {
      if (identifier == null) {
        var config = {};
        config["className"] = "linear";
        config["config"] = {};
        return deserializeActivation(config);
      }
      if (typeof identifier === "string") {
        var config = {};
        config["className"] = identifier;
        config["config"] = {};
        return deserializeActivation(config);
      } else if (identifier instanceof Activation$1) {
        return identifier;
      } else {
        return deserializeActivation(identifier);
      }
    }
    function assertObjectArgs(args) {
      if (args != null && typeof args !== "object") {
        throw new Error("Argument to L1L2 regularizer's constructor is expected to be an " + "object, but received: ".concat(args));
      }
    }
    var Regularizer = (
      /** @class */
      function(_super) {
        __extends(Regularizer2, _super);
        function Regularizer2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        return Regularizer2;
      }(tfc.serialization.Serializable)
    );
    var L1L2 = (
      /** @class */
      function(_super) {
        __extends(L1L22, _super);
        function L1L22(args) {
          var _this = _super.call(this) || this;
          assertObjectArgs(args);
          _this.l1 = args == null || args.l1 == null ? 0.01 : args.l1;
          _this.l2 = args == null || args.l2 == null ? 0.01 : args.l2;
          _this.hasL1 = _this.l1 !== 0;
          _this.hasL2 = _this.l2 !== 0;
          return _this;
        }
        L1L22.prototype.apply = function(x) {
          var _this = this;
          return tfc.tidy(function() {
            var regularization = tfc.zeros([1]);
            if (_this.hasL1) {
              regularization = tfc.add(regularization, tfc.sum(tfc__namespace.mul(_this.l1, tfc.abs(x))));
            }
            if (_this.hasL2) {
              regularization = tfc.add(regularization, tfc.sum(tfc__namespace.mul(_this.l2, square$1(x))));
            }
            return tfc__namespace.reshape(regularization, []);
          });
        };
        L1L22.prototype.getConfig = function() {
          return { "l1": this.l1, "l2": this.l2 };
        };
        L1L22.fromConfig = function(cls, config) {
          return new cls({ l1: config["l1"], l2: config["l2"] });
        };
        return L1L22;
      }(Regularizer)
    );
    L1L2.className = "L1L2";
    tfc.serialization.registerClass(L1L2);
    function l1$1(args) {
      assertObjectArgs(args);
      return new L1L2({ l1: args != null ? args.l1 : null, l2: 0 });
    }
    function l2$1(args) {
      assertObjectArgs(args);
      return new L1L2({ l2: args != null ? args.l2 : null, l1: 0 });
    }
    var REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP = {
      "l1l2": "L1L2"
    };
    function serializeRegularizer(constraint) {
      return serializeKerasObject(constraint);
    }
    function deserializeRegularizer(config, customObjects) {
      if (customObjects === void 0) {
        customObjects = {};
      }
      return deserializeKerasObject(config, tfc.serialization.SerializationMap.getMap().classNameMap, customObjects, "regularizer");
    }
    function getRegularizer(identifier) {
      if (identifier == null) {
        return null;
      }
      if (typeof identifier === "string") {
        var className = identifier in REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP ? REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[identifier] : identifier;
        var config = { className, config: {} };
        return deserializeRegularizer(config);
      } else if (identifier instanceof Regularizer) {
        return identifier;
      } else {
        return deserializeRegularizer(identifier);
      }
    }
    var ReLU = (
      /** @class */
      function(_super) {
        __extends(ReLU2, _super);
        function ReLU2(args) {
          var _this = _super.call(this, args == null ? {} : args) || this;
          _this.supportsMasking = true;
          if (args != null) {
            _this.maxValue = args.maxValue;
          }
          return _this;
        }
        ReLU2.prototype.call = function(inputs, kwargs) {
          inputs = getExactlyOneTensor(inputs);
          var output = tfc.relu(inputs);
          if (this.maxValue != null) {
            output = tfc.clipByValue(output, 0, this.maxValue);
          }
          return output;
        };
        ReLU2.prototype.computeOutputShape = function(inputShape) {
          return inputShape;
        };
        ReLU2.prototype.getConfig = function() {
          var config = { maxValue: this.maxValue };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return ReLU2;
      }(Layer)
    );
    ReLU.className = "ReLU";
    tfc.serialization.registerClass(ReLU);
    var LeakyReLU = (
      /** @class */
      function(_super) {
        __extends(LeakyReLU2, _super);
        function LeakyReLU2(args) {
          var _this = _super.call(this, args == null ? {} : args) || this;
          _this.DEFAULT_ALPHA = 0.3;
          if (args == null) {
            args = {};
          }
          _this.alpha = args.alpha == null ? _this.DEFAULT_ALPHA : args.alpha;
          return _this;
        }
        LeakyReLU2.prototype.call = function(inputs, kwargs) {
          var x = getExactlyOneTensor(inputs);
          return tfc.leakyRelu(x, this.alpha);
        };
        LeakyReLU2.prototype.computeOutputShape = function(inputShape) {
          return inputShape;
        };
        LeakyReLU2.prototype.getConfig = function() {
          var config = { alpha: this.alpha };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return LeakyReLU2;
      }(Layer)
    );
    LeakyReLU.className = "LeakyReLU";
    tfc.serialization.registerClass(LeakyReLU);
    var PReLU = (
      /** @class */
      function(_super) {
        __extends(PReLU2, _super);
        function PReLU2(args) {
          var _this = _super.call(this, args == null ? {} : args) || this;
          _this.DEFAULT_ALPHA_INITIALIZER = "zeros";
          if (args == null) {
            args = {};
          }
          _this.supportsMasking = true;
          _this.alphaInitializer = getInitializer(args.alphaInitializer || _this.DEFAULT_ALPHA_INITIALIZER);
          _this.alphaRegularizer = getRegularizer(args.alphaRegularizer);
          _this.alphaConstraint = getConstraint(args.alphaConstraint);
          if (args.sharedAxes == null) {
            _this.sharedAxes = null;
          } else if (Array.isArray(args.sharedAxes)) {
            _this.sharedAxes = args.sharedAxes;
          } else if (typeof args.sharedAxes === "number") {
            _this.sharedAxes = [args.sharedAxes];
          } else {
            throw new ValueError("Expected sharedAxes to be a number or an array of numbers, " + "but got ".concat(args.sharedAxes));
          }
          return _this;
        }
        PReLU2.prototype.build = function(inputShape) {
          var e_12, _a2;
          inputShape = getExactlyOneShape(inputShape);
          var paramShape = inputShape.slice(1);
          if (this.sharedAxes != null) {
            try {
              for (var _b = __values(this.sharedAxes), _c = _b.next(); !_c.done; _c = _b.next()) {
                var i = _c.value;
                paramShape[i - 1] = 1;
              }
            } catch (e_1_1) {
              e_12 = { error: e_1_1 };
            } finally {
              try {
                if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
              } finally {
                if (e_12) throw e_12.error;
              }
            }
          }
          this.alpha = this.addWeight("alpha", paramShape, "float32", this.alphaInitializer, this.alphaRegularizer, true, this.alphaConstraint);
          var axes = {};
          if (this.sharedAxes != null) {
            for (var i = 1; i < inputShape.length; ++i) {
              axes[i] = inputShape[i];
            }
          }
          this.inputSpec = [new InputSpec({
            ndim: inputShape.length,
            axes
          })];
          this.built = true;
        };
        PReLU2.prototype.call = function(inputs, kwargs) {
          inputs = getExactlyOneTensor(inputs);
          return tfc.prelu(inputs, this.alpha.read());
        };
        PReLU2.prototype.getConfig = function() {
          var config = {
            alphaInitializer: serializeInitializer(this.alphaInitializer),
            alphaRegularizer: serializeRegularizer(this.alphaRegularizer),
            alphaConstraint: serializeConstraint(this.alphaConstraint),
            sharedAxes: this.sharedAxes
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return PReLU2;
      }(Layer)
    );
    PReLU.className = "PReLU";
    tfc.serialization.registerClass(PReLU);
    var ELU = (
      /** @class */
      function(_super) {
        __extends(ELU2, _super);
        function ELU2(args) {
          var _this = _super.call(this, args == null ? {} : args) || this;
          _this.DEFAULT_ALPHA = 1;
          if (args == null) {
            args = {};
          }
          if (args.alpha != null && args.alpha !== _this.DEFAULT_ALPHA) {
            throw new NotImplementedError("Non-default alpha value (".concat(args.alpha, ") is not supported by the ") + "ELU layer yet.");
          }
          _this.alpha = args.alpha == null ? _this.DEFAULT_ALPHA : args.alpha;
          return _this;
        }
        ELU2.prototype.call = function(inputs, kwargs) {
          var x = getExactlyOneTensor(inputs);
          return tfc.elu(x);
        };
        ELU2.prototype.computeOutputShape = function(inputShape) {
          return inputShape;
        };
        ELU2.prototype.getConfig = function() {
          var config = { alpha: this.alpha };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return ELU2;
      }(Layer)
    );
    ELU.className = "ELU";
    tfc.serialization.registerClass(ELU);
    var ThresholdedReLU = (
      /** @class */
      function(_super) {
        __extends(ThresholdedReLU2, _super);
        function ThresholdedReLU2(args) {
          var _this = _super.call(this, args == null ? {} : args) || this;
          _this.DEFAULT_THETA = 1;
          if (args == null) {
            args = {};
          }
          _this.theta = args.theta == null ? _this.DEFAULT_THETA : args.theta;
          return _this;
        }
        ThresholdedReLU2.prototype.call = function(inputs, kwargs) {
          var x = getExactlyOneTensor(inputs);
          return tfc.mul(x, tfc.cast(tfc.greater(x, this.theta), "float32"));
        };
        ThresholdedReLU2.prototype.computeOutputShape = function(inputShape) {
          return inputShape;
        };
        ThresholdedReLU2.prototype.getConfig = function() {
          var config = { theta: this.theta };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return ThresholdedReLU2;
      }(Layer)
    );
    ThresholdedReLU.className = "ThresholdedReLU";
    tfc.serialization.registerClass(ThresholdedReLU);
    var Softmax = (
      /** @class */
      function(_super) {
        __extends(Softmax2, _super);
        function Softmax2(args) {
          var _this = _super.call(this, args == null ? {} : args) || this;
          _this.DEFAULT_AXIS = 1;
          if (args == null) {
            args = {};
          }
          _this.softmax = new Softmax$1().apply;
          _this.axis = args.axis == null ? _this.DEFAULT_AXIS : args.axis;
          return _this;
        }
        Softmax2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            var x = getExactlyOneTensor(inputs);
            var mask = kwargs["mask"];
            if (mask != null) {
              var adder = tfc.mul(tfc.sub(tfc.ones(x.shape), tfc.cast(mask, x.dtype)), tfc.scalar(-1e9));
              x = tfc.add(x, adder);
            }
            if (_this.axis instanceof Array) {
              if (_this.axis.length > 1) {
                return tfc.exp(tfc.sub(x, tfc.logSumExp(x, _this.axis, true)));
              } else {
                return _this.softmax(x, _this.axis[0]);
              }
            }
            return _this.softmax(x, _this.axis);
          });
        };
        Softmax2.prototype.computeOutputShape = function(inputShape) {
          return inputShape;
        };
        Softmax2.prototype.getConfig = function() {
          var config = { axis: this.axis };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return Softmax2;
      }(Layer)
    );
    Softmax.className = "Softmax";
    tfc.serialization.registerClass(Softmax);
    function normalizeArray(value, n, name) {
      if (typeof value === "number") {
        return pyListRepeat(value, n);
      } else {
        if (value.length !== n) {
          throw new ValueError("The ".concat(name, " argument must be an integer or tuple of ").concat(n, " integers.") + " Received: ".concat(value.length, " elements."));
        }
        for (var i = 0; i < n; ++i) {
          var singleValue = value[i];
          if (!isInteger(singleValue)) {
            throw new ValueError("The ".concat(name, " argument must be an integer or tuple of ").concat(n) + " integers. Received: ".concat(JSON.stringify(value), " including a") + " non-integer number ".concat(singleValue));
          }
        }
        return value;
      }
    }
    function convOutputLength(inputLength, filterSize, padding, stride, dilation) {
      if (dilation === void 0) {
        dilation = 1;
      }
      if (inputLength == null) {
        return inputLength;
      }
      var dilatedFilterSize = filterSize + (filterSize - 1) * (dilation - 1);
      var outputLength;
      if (padding === "same") {
        outputLength = inputLength;
      } else {
        outputLength = inputLength - dilatedFilterSize + 1;
      }
      return Math.floor((outputLength + stride - 1) / stride);
    }
    function deconvLength(dimSize, strideSize, kernelSize, padding) {
      if (dimSize == null) {
        return null;
      }
      if (padding === "valid") {
        dimSize = dimSize * strideSize + max([kernelSize - strideSize, 0]);
      } else if (padding === "same") {
        dimSize = dimSize * strideSize;
      } else {
        throw new ValueError("Unsupport padding mode: ".concat(padding, "."));
      }
      return dimSize;
    }
    function preprocessConv2DInput(x, dataFormat) {
      return tfc.tidy(function() {
        checkDataFormat(dataFormat);
        if (dataFormat === "channelsFirst") {
          return tfc__namespace.transpose(x, [0, 2, 3, 1]);
        } else {
          return x;
        }
      });
    }
    function preprocessConv3DInput(x, dataFormat) {
      return tfc.tidy(function() {
        checkDataFormat(dataFormat);
        if (dataFormat === "channelsFirst") {
          return tfc__namespace.transpose(x, [0, 2, 3, 4, 1]);
        } else {
          return x;
        }
      });
    }
    function conv1dWithBias(x, kernel, bias, strides, padding, dataFormat, dilationRate) {
      if (strides === void 0) {
        strides = 1;
      }
      if (padding === void 0) {
        padding = "valid";
      }
      if (dilationRate === void 0) {
        dilationRate = 1;
      }
      return tfc.tidy(function() {
        if (dataFormat == null) {
          dataFormat = imageDataFormat();
        }
        checkDataFormat(dataFormat);
        if (x.shape.length !== 3) {
          throw new ValueError("The input of a conv1dWithBias operation should be 3, but is " + "".concat(x.shape.length, " instead."));
        }
        if (kernel.shape.length !== 3) {
          throw new ValueError("The kernel for a conv1dWithBias operation should be 3, but is " + "".concat(kernel.shape.length, " instead"));
        }
        if (bias != null && bias.shape.length !== 1) {
          throw new ValueError("The bias for a conv1dWithBias operation should be 1, but is " + "".concat(bias.shape.length, " instead"));
        }
        if (dataFormat === "channelsFirst") {
          x = tfc__namespace.transpose(x, [0, 2, 1]);
        }
        if (padding === "causal") {
          throw new NotImplementedError("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");
        }
        var y = tfc__namespace.conv1d(x, kernel, strides, padding === "same" ? "same" : "valid", "NWC", dilationRate);
        if (bias != null) {
          y = biasAdd(y, bias);
        }
        return y;
      });
    }
    function conv2dWithBiasActivation(x, kernel, bias, strides, padding, dataFormat, dilationRate, activation2) {
      if (strides === void 0) {
        strides = [1, 1];
      }
      if (padding === void 0) {
        padding = "valid";
      }
      if (activation2 === void 0) {
        activation2 = null;
      }
      return tfc.tidy(function() {
        if (dataFormat == null) {
          dataFormat = imageDataFormat();
        }
        checkDataFormat(dataFormat);
        if (x.rank !== 3 && x.rank !== 4) {
          throw new ValueError("conv2dWithBiasActivation expects input to be of rank 3 or 4, " + "but received ".concat(x.rank, "."));
        }
        if (kernel.rank !== 3 && kernel.rank !== 4) {
          throw new ValueError("conv2dWithBiasActivation expects kernel to be of rank 3 or 4, " + "but received ".concat(x.rank, "."));
        }
        var y = preprocessConv2DInput(x, dataFormat);
        if (padding === "causal") {
          throw new NotImplementedError("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");
        }
        y = tfc__namespace.fused.conv2d({
          x: y,
          filter: kernel,
          strides,
          pad: padding === "same" ? "same" : "valid",
          dilations: dilationRate,
          dataFormat: "NHWC",
          bias,
          activation: activation2
        });
        if (dataFormat === "channelsFirst") {
          y = tfc__namespace.transpose(y, [0, 3, 1, 2]);
        }
        return y;
      });
    }
    function conv3dWithBias(x, kernel, bias, strides, padding, dataFormat, dilationRate) {
      if (strides === void 0) {
        strides = [1, 1, 1];
      }
      if (padding === void 0) {
        padding = "valid";
      }
      return tfc.tidy(function() {
        if (dataFormat == null) {
          dataFormat = imageDataFormat();
        }
        checkDataFormat(dataFormat);
        if (x.rank !== 4 && x.rank !== 5) {
          throw new ValueError("conv3dWithBias expects input to be of rank 4 or 5, but received " + "".concat(x.rank, "."));
        }
        if (kernel.rank !== 4 && kernel.rank !== 5) {
          throw new ValueError("conv3dWithBias expects kernel to be of rank 4 or 5, but received " + "".concat(x.rank, "."));
        }
        var y = preprocessConv3DInput(x, dataFormat);
        if (padding === "causal") {
          throw new NotImplementedError("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");
        }
        y = tfc__namespace.conv3d(y, kernel, strides, padding === "same" ? "same" : "valid", "NDHWC", dilationRate);
        if (bias != null) {
          y = biasAdd(y, bias);
        }
        if (dataFormat === "channelsFirst") {
          y = tfc__namespace.transpose(y, [0, 4, 1, 2, 3]);
        }
        return y;
      });
    }
    var BaseConv = (
      /** @class */
      function(_super) {
        __extends(BaseConv2, _super);
        function BaseConv2(rank, args) {
          var _this = _super.call(this, args) || this;
          _this.bias = null;
          _this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal";
          _this.DEFAULT_BIAS_INITIALIZER = "zeros";
          BaseConv2.verifyArgs(args);
          _this.rank = rank;
          assertPositiveInteger(_this.rank, "rank");
          if (_this.rank !== 1 && _this.rank !== 2 && _this.rank !== 3) {
            throw new NotImplementedError("Convolution layer for rank other than 1, 2, or 3 (".concat(_this.rank, ") is ") + "not implemented yet.");
          }
          _this.kernelSize = normalizeArray(args.kernelSize, rank, "kernelSize");
          _this.strides = normalizeArray(args.strides == null ? 1 : args.strides, rank, "strides");
          _this.padding = args.padding == null ? "valid" : args.padding;
          checkPaddingMode(_this.padding);
          _this.dataFormat = args.dataFormat == null ? "channelsLast" : args.dataFormat;
          checkDataFormat(_this.dataFormat);
          _this.activation = getActivation(args.activation);
          _this.useBias = args.useBias == null ? true : args.useBias;
          _this.biasInitializer = getInitializer(args.biasInitializer || _this.DEFAULT_BIAS_INITIALIZER);
          _this.biasConstraint = getConstraint(args.biasConstraint);
          _this.biasRegularizer = getRegularizer(args.biasRegularizer);
          _this.activityRegularizer = getRegularizer(args.activityRegularizer);
          _this.dilationRate = normalizeArray(args.dilationRate == null ? 1 : args.dilationRate, rank, "dilationRate");
          if (_this.rank === 1 && (Array.isArray(_this.dilationRate) && _this.dilationRate.length !== 1)) {
            throw new ValueError("dilationRate must be a number or an array of a single number for 1D convolution, but received " + "".concat(JSON.stringify(_this.dilationRate)));
          } else if (_this.rank === 2) {
            if (typeof _this.dilationRate === "number") {
              _this.dilationRate = [_this.dilationRate, _this.dilationRate];
            } else if (_this.dilationRate.length !== 2) {
              throw new ValueError("dilationRate must be a number or array of two numbers for 2D " + "convolution, but received ".concat(JSON.stringify(_this.dilationRate)));
            }
          } else if (_this.rank === 3) {
            if (typeof _this.dilationRate === "number") {
              _this.dilationRate = [_this.dilationRate, _this.dilationRate, _this.dilationRate];
            } else if (_this.dilationRate.length !== 3) {
              throw new ValueError("dilationRate must be a number or array of three numbers for 3D " + "convolution, but received ".concat(JSON.stringify(_this.dilationRate)));
            }
          }
          return _this;
        }
        BaseConv2.verifyArgs = function(args) {
          assert$1("kernelSize" in args, "required key 'kernelSize' not in config");
          if (typeof args.kernelSize !== "number" && !checkArrayTypeAndLength(args.kernelSize, "number", 1, 3)) {
            throw new ValueError("BaseConv expects config.kernelSize to be number or number[] with " + "length 1, 2, or 3, but received ".concat(JSON.stringify(args.kernelSize), "."));
          }
        };
        BaseConv2.prototype.getConfig = function() {
          var config = {
            kernelSize: this.kernelSize,
            strides: this.strides,
            padding: this.padding,
            dataFormat: this.dataFormat,
            dilationRate: this.dilationRate,
            activation: serializeActivation(this.activation),
            useBias: this.useBias,
            biasInitializer: serializeInitializer(this.biasInitializer),
            biasRegularizer: serializeRegularizer(this.biasRegularizer),
            activityRegularizer: serializeRegularizer(this.activityRegularizer),
            biasConstraint: serializeConstraint(this.biasConstraint)
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return BaseConv2;
      }(Layer)
    );
    var Conv = (
      /** @class */
      function(_super) {
        __extends(Conv2, _super);
        function Conv2(rank, args) {
          var _this = _super.call(this, rank, args) || this;
          _this.kernel = null;
          Conv2.verifyArgs(args);
          _this.filters = args.filters;
          assertPositiveInteger(_this.filters, "filters");
          _this.kernelInitializer = getInitializer(args.kernelInitializer || _this.DEFAULT_KERNEL_INITIALIZER);
          _this.kernelConstraint = getConstraint(args.kernelConstraint);
          _this.kernelRegularizer = getRegularizer(args.kernelRegularizer);
          return _this;
        }
        Conv2.prototype.build = function(inputShape) {
          var _a2;
          inputShape = getExactlyOneShape(inputShape);
          var channelAxis = this.dataFormat === "channelsFirst" ? 1 : inputShape.length - 1;
          if (inputShape[channelAxis] == null) {
            throw new ValueError("The channel dimension of the input should be defined. " + "Found ".concat(inputShape[channelAxis]));
          }
          var inputDim = inputShape[channelAxis];
          var kernelShape = this.kernelSize.concat([inputDim, this.filters]);
          this.kernel = this.addWeight("kernel", kernelShape, null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint);
          if (this.useBias) {
            this.bias = this.addWeight("bias", [this.filters], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint);
          }
          this.inputSpec = [{ ndim: this.rank + 2, axes: (_a2 = {}, _a2[channelAxis] = inputDim, _a2) }];
          this.built = true;
        };
        Conv2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            inputs = getExactlyOneTensor(inputs);
            var outputs;
            var biasValue = _this.bias == null ? null : _this.bias.read();
            var fusedActivationName = mapActivationToFusedKernel(_this.activation.getClassName());
            if (fusedActivationName != null && _this.rank === 2) {
              outputs = conv2dWithBiasActivation(inputs, _this.kernel.read(), biasValue, _this.strides, _this.padding, _this.dataFormat, _this.dilationRate, fusedActivationName);
            } else {
              if (_this.rank === 1) {
                outputs = conv1dWithBias(inputs, _this.kernel.read(), biasValue, _this.strides[0], _this.padding, _this.dataFormat, _this.dilationRate[0]);
              } else if (_this.rank === 2) {
                outputs = conv2dWithBiasActivation(inputs, _this.kernel.read(), biasValue, _this.strides, _this.padding, _this.dataFormat, _this.dilationRate);
              } else if (_this.rank === 3) {
                outputs = conv3dWithBias(inputs, _this.kernel.read(), biasValue, _this.strides, _this.padding, _this.dataFormat, _this.dilationRate);
              } else {
                throw new NotImplementedError("convolutions greater than 3D are not implemented yet.");
              }
              if (_this.activation != null) {
                outputs = _this.activation.apply(outputs);
              }
            }
            return outputs;
          });
        };
        Conv2.prototype.computeOutputShape = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          var newSpace = [];
          var space = this.dataFormat === "channelsLast" ? inputShape.slice(1, inputShape.length - 1) : inputShape.slice(2);
          for (var i = 0; i < space.length; ++i) {
            var newDim = convOutputLength(space[i], this.kernelSize[i], this.padding, this.strides[i], typeof this.dilationRate === "number" ? this.dilationRate : this.dilationRate[i]);
            newSpace.push(newDim);
          }
          var outputShape = [inputShape[0]];
          if (this.dataFormat === "channelsLast") {
            outputShape = outputShape.concat(newSpace);
            outputShape.push(this.filters);
          } else {
            outputShape.push(this.filters);
            outputShape = outputShape.concat(newSpace);
          }
          return outputShape;
        };
        Conv2.prototype.getConfig = function() {
          var config = {
            filters: this.filters,
            kernelInitializer: serializeInitializer(this.kernelInitializer),
            kernelRegularizer: serializeRegularizer(this.kernelRegularizer),
            kernelConstraint: serializeConstraint(this.kernelConstraint)
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        Conv2.verifyArgs = function(args) {
          if (!("filters" in args) || typeof args.filters !== "number" || args.filters < 1) {
            throw new ValueError("Convolution layer expected config.filters to be a 'number' > 0 " + "but got ".concat(JSON.stringify(args.filters)));
          }
        };
        return Conv2;
      }(BaseConv)
    );
    var Conv2D = (
      /** @class */
      function(_super) {
        __extends(Conv2D2, _super);
        function Conv2D2(args) {
          var _this = _super.call(this, 2, args) || this;
          Conv2D2.verifyArgs(args);
          return _this;
        }
        Conv2D2.prototype.getConfig = function() {
          var config = _super.prototype.getConfig.call(this);
          delete config["rank"];
          return config;
        };
        Conv2D2.verifyArgs = function(args) {
          if (typeof args.kernelSize !== "number" && !checkArrayTypeAndLength(args.kernelSize, "number", 1, 2)) {
            throw new ValueError("Conv2D expects config.kernelSize to be number or number[] with " + "length 1 or 2, but received ".concat(JSON.stringify(args.kernelSize), "."));
          }
        };
        return Conv2D2;
      }(Conv)
    );
    Conv2D.className = "Conv2D";
    tfc.serialization.registerClass(Conv2D);
    var Conv3D = (
      /** @class */
      function(_super) {
        __extends(Conv3D2, _super);
        function Conv3D2(args) {
          var _this = _super.call(this, 3, args) || this;
          Conv3D2.verifyArgs(args);
          return _this;
        }
        Conv3D2.prototype.getConfig = function() {
          var config = _super.prototype.getConfig.call(this);
          delete config["rank"];
          return config;
        };
        Conv3D2.verifyArgs = function(args) {
          if (typeof args.kernelSize !== "number") {
            if (!(Array.isArray(args.kernelSize) && (args.kernelSize.length === 1 || args.kernelSize.length === 3))) {
              throw new ValueError("Conv3D expects config.kernelSize to be number or" + " [number, number, number], but received ".concat(JSON.stringify(args.kernelSize), "."));
            }
          }
        };
        return Conv3D2;
      }(Conv)
    );
    Conv3D.className = "Conv3D";
    tfc.serialization.registerClass(Conv3D);
    var Conv2DTranspose = (
      /** @class */
      function(_super) {
        __extends(Conv2DTranspose2, _super);
        function Conv2DTranspose2(args) {
          var _this = _super.call(this, args) || this;
          _this.inputSpec = [new InputSpec({ ndim: 4 })];
          if (_this.padding !== "same" && _this.padding !== "valid") {
            throw new ValueError("Conv2DTranspose currently supports only padding modes 'same' " + "and 'valid', but received padding mode ".concat(_this.padding));
          }
          return _this;
        }
        Conv2DTranspose2.prototype.build = function(inputShape) {
          var _a2;
          inputShape = getExactlyOneShape(inputShape);
          if (inputShape.length !== 4) {
            throw new ValueError("Input should have rank 4; Received input shape: " + JSON.stringify(inputShape));
          }
          var channelAxis = this.dataFormat === "channelsFirst" ? 1 : inputShape.length - 1;
          if (inputShape[channelAxis] == null) {
            throw new ValueError("The channel dimension of the inputs should be defined. Found `None`.");
          }
          var inputDim = inputShape[channelAxis];
          var kernelShape = this.kernelSize.concat([this.filters, inputDim]);
          this.kernel = this.addWeight("kernel", kernelShape, "float32", this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint);
          if (this.useBias) {
            this.bias = this.addWeight("bias", [this.filters], "float32", this.biasInitializer, this.biasRegularizer, true, this.biasConstraint);
          }
          this.inputSpec = [new InputSpec({ ndim: 4, axes: (_a2 = {}, _a2[channelAxis] = inputDim, _a2) })];
          this.built = true;
        };
        Conv2DTranspose2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc__namespace.tidy(function() {
            var input2 = getExactlyOneTensor(inputs);
            if (input2.shape.length !== 4) {
              throw new ValueError("Conv2DTranspose.call() expects input tensor to be rank-4, but " + "received a tensor of rank-".concat(input2.shape.length));
            }
            var inputShape = input2.shape;
            var batchSize = inputShape[0];
            var hAxis;
            var wAxis;
            if (_this.dataFormat === "channelsFirst") {
              hAxis = 2;
              wAxis = 3;
            } else {
              hAxis = 1;
              wAxis = 2;
            }
            var height = inputShape[hAxis];
            var width = inputShape[wAxis];
            var kernelH = _this.kernelSize[0];
            var kernelW = _this.kernelSize[1];
            var strideH = _this.strides[0];
            var strideW = _this.strides[1];
            var outHeight = deconvLength(height, strideH, kernelH, _this.padding);
            var outWidth = deconvLength(width, strideW, kernelW, _this.padding);
            var outputShape = [batchSize, outHeight, outWidth, _this.filters];
            if (_this.dataFormat !== "channelsLast") {
              input2 = tfc__namespace.transpose(input2, [0, 2, 3, 1]);
            }
            var outputs = tfc__namespace.conv2dTranspose(input2, _this.kernel.read(), outputShape, _this.strides, _this.padding);
            if (_this.dataFormat !== "channelsLast") {
              outputs = tfc__namespace.transpose(outputs, [0, 3, 1, 2]);
            }
            if (_this.bias != null) {
              outputs = biasAdd(outputs, _this.bias.read(), _this.dataFormat);
            }
            if (_this.activation != null) {
              outputs = _this.activation.apply(outputs);
            }
            return outputs;
          });
        };
        Conv2DTranspose2.prototype.computeOutputShape = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          var outputShape = inputShape.slice();
          var channelAxis;
          var heightAxis;
          var widthAxis;
          if (this.dataFormat === "channelsFirst") {
            channelAxis = 1;
            heightAxis = 2;
            widthAxis = 3;
          } else {
            channelAxis = 3;
            heightAxis = 1;
            widthAxis = 2;
          }
          var kernelH = this.kernelSize[0];
          var kernelW = this.kernelSize[1];
          var strideH = this.strides[0];
          var strideW = this.strides[1];
          outputShape[channelAxis] = this.filters;
          outputShape[heightAxis] = deconvLength(outputShape[heightAxis], strideH, kernelH, this.padding);
          outputShape[widthAxis] = deconvLength(outputShape[widthAxis], strideW, kernelW, this.padding);
          return outputShape;
        };
        Conv2DTranspose2.prototype.getConfig = function() {
          var config = _super.prototype.getConfig.call(this);
          delete config["dilationRate"];
          return config;
        };
        return Conv2DTranspose2;
      }(Conv2D)
    );
    Conv2DTranspose.className = "Conv2DTranspose";
    tfc.serialization.registerClass(Conv2DTranspose);
    var Conv3DTranspose = (
      /** @class */
      function(_super) {
        __extends(Conv3DTranspose2, _super);
        function Conv3DTranspose2(args) {
          var _this = _super.call(this, args) || this;
          _this.inputSpec = [new InputSpec({ ndim: 5 })];
          if (_this.padding !== "same" && _this.padding !== "valid") {
            throw new ValueError("Conv3DTranspose currently supports only padding modes 'same' " + "and 'valid', but received padding mode ".concat(_this.padding));
          }
          return _this;
        }
        Conv3DTranspose2.prototype.build = function(inputShape) {
          var _a2;
          inputShape = getExactlyOneShape(inputShape);
          if (inputShape.length !== 5) {
            throw new ValueError("Input should have rank 5; Received input shape: " + JSON.stringify(inputShape));
          }
          var channelAxis = this.dataFormat === "channelsFirst" ? 1 : inputShape.length - 1;
          if (inputShape[channelAxis] == null) {
            throw new ValueError("The channel dimension of the inputs should be defined. Found `None`.");
          }
          var inputDim = inputShape[channelAxis];
          var kernelShape = this.kernelSize.concat([this.filters, inputDim]);
          this.kernel = this.addWeight("kernel", kernelShape, "float32", this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint);
          if (this.useBias) {
            this.bias = this.addWeight("bias", [this.filters], "float32", this.biasInitializer, this.biasRegularizer, true, this.biasConstraint);
          }
          this.inputSpec = [new InputSpec({ ndim: 5, axes: (_a2 = {}, _a2[channelAxis] = inputDim, _a2) })];
          this.built = true;
        };
        Conv3DTranspose2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc__namespace.tidy(function() {
            var input2 = getExactlyOneTensor(inputs);
            if (input2.shape.length !== 5) {
              throw new ValueError("Conv3DTranspose.call() expects input tensor to be rank-4, but " + "received a tensor of rank-".concat(input2.shape.length));
            }
            var inputShape = input2.shape;
            var batchSize = inputShape[0];
            var hAxis;
            var wAxis;
            var dAxis;
            if (_this.dataFormat === "channelsFirst") {
              dAxis = 2;
              hAxis = 3;
              wAxis = 4;
            } else {
              dAxis = 1;
              hAxis = 2;
              wAxis = 3;
            }
            var depth = inputShape[dAxis];
            var height = inputShape[hAxis];
            var width = inputShape[wAxis];
            var kernelD = _this.kernelSize[0];
            var kernelH = _this.kernelSize[1];
            var kernelW = _this.kernelSize[2];
            var strideD = _this.strides[0];
            var strideH = _this.strides[1];
            var strideW = _this.strides[2];
            var outDepth = deconvLength(depth, strideD, kernelD, _this.padding);
            var outHeight = deconvLength(height, strideH, kernelH, _this.padding);
            var outWidth = deconvLength(width, strideW, kernelW, _this.padding);
            var outputShape = [batchSize, outDepth, outHeight, outWidth, _this.filters];
            if (_this.dataFormat !== "channelsLast") {
              input2 = tfc__namespace.transpose(input2, [0, 2, 3, 4, 1]);
            }
            var outputs = tfc__namespace.conv3dTranspose(input2, _this.kernel.read(), outputShape, _this.strides, _this.padding);
            if (_this.dataFormat !== "channelsLast") {
              outputs = tfc__namespace.transpose(outputs, [0, 4, 1, 2, 3]);
            }
            if (_this.bias !== null) {
              outputs = biasAdd(outputs, _this.bias.read(), _this.dataFormat);
            }
            if (_this.activation !== null) {
              outputs = _this.activation.apply(outputs);
            }
            return outputs;
          });
        };
        Conv3DTranspose2.prototype.computeOutputShape = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          var outputShape = inputShape.slice();
          var channelAxis;
          var depthAxis;
          var heightAxis;
          var widthAxis;
          if (this.dataFormat === "channelsFirst") {
            channelAxis = 1;
            depthAxis = 2;
            heightAxis = 3;
            widthAxis = 4;
          } else {
            channelAxis = 4;
            depthAxis = 1;
            heightAxis = 2;
            widthAxis = 3;
          }
          var kernelD = this.kernelSize[0];
          var kernelH = this.kernelSize[1];
          var kernelW = this.kernelSize[2];
          var strideD = this.strides[0];
          var strideH = this.strides[1];
          var strideW = this.strides[2];
          outputShape[channelAxis] = this.filters;
          outputShape[depthAxis] = deconvLength(outputShape[depthAxis], strideD, kernelD, this.padding);
          outputShape[heightAxis] = deconvLength(outputShape[heightAxis], strideH, kernelH, this.padding);
          outputShape[widthAxis] = deconvLength(outputShape[widthAxis], strideW, kernelW, this.padding);
          return outputShape;
        };
        Conv3DTranspose2.prototype.getConfig = function() {
          var config = _super.prototype.getConfig.call(this);
          delete config["dilationRate"];
          return config;
        };
        return Conv3DTranspose2;
      }(Conv3D)
    );
    Conv3DTranspose.className = "Conv3DTranspose";
    tfc.serialization.registerClass(Conv3DTranspose);
    var SeparableConv = (
      /** @class */
      function(_super) {
        __extends(SeparableConv2, _super);
        function SeparableConv2(rank, config) {
          var _this = _super.call(this, rank, config) || this;
          _this.DEFAULT_DEPTHWISE_INITIALIZER = "glorotUniform";
          _this.DEFAULT_POINTWISE_INITIALIZER = "glorotUniform";
          _this.depthwiseKernel = null;
          _this.pointwiseKernel = null;
          if (config.filters == null) {
            throw new ValueError("The `filters` configuration field is required by SeparableConv, but is unspecified.");
          }
          if (config.kernelInitializer != null || config.kernelRegularizer != null || config.kernelConstraint != null) {
            throw new ValueError("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");
          }
          if (config.padding != null && config.padding !== "same" && config.padding !== "valid") {
            throw new ValueError("SeparableConv".concat(_this.rank, "D supports only padding modes: ") + "'same' and 'valid', but received ".concat(JSON.stringify(config.padding)));
          }
          _this.depthMultiplier = config.depthMultiplier == null ? 1 : config.depthMultiplier;
          _this.depthwiseInitializer = getInitializer(config.depthwiseInitializer || _this.DEFAULT_DEPTHWISE_INITIALIZER);
          _this.depthwiseRegularizer = getRegularizer(config.depthwiseRegularizer);
          _this.depthwiseConstraint = getConstraint(config.depthwiseConstraint);
          _this.pointwiseInitializer = getInitializer(config.depthwiseInitializer || _this.DEFAULT_POINTWISE_INITIALIZER);
          _this.pointwiseRegularizer = getRegularizer(config.pointwiseRegularizer);
          _this.pointwiseConstraint = getConstraint(config.pointwiseConstraint);
          return _this;
        }
        SeparableConv2.prototype.build = function(inputShape) {
          var _a2;
          inputShape = getExactlyOneShape(inputShape);
          if (inputShape.length < this.rank + 2) {
            throw new ValueError("Inputs to SeparableConv".concat(this.rank, "D should have rank ") + "".concat(this.rank + 2, ", but received input shape: ") + "".concat(JSON.stringify(inputShape)));
          }
          var channelAxis = this.dataFormat === "channelsFirst" ? 1 : inputShape.length - 1;
          if (inputShape[channelAxis] == null || inputShape[channelAxis] < 0) {
            throw new ValueError("The channel dimension of the inputs should be defined, " + "but found ".concat(JSON.stringify(inputShape[channelAxis])));
          }
          var inputDim = inputShape[channelAxis];
          var depthwiseKernelShape = this.kernelSize.concat([inputDim, this.depthMultiplier]);
          var pointwiseKernelShape = [];
          for (var i = 0; i < this.rank; ++i) {
            pointwiseKernelShape.push(1);
          }
          pointwiseKernelShape.push(inputDim * this.depthMultiplier, this.filters);
          var trainable = true;
          this.depthwiseKernel = this.addWeight("depthwise_kernel", depthwiseKernelShape, "float32", this.depthwiseInitializer, this.depthwiseRegularizer, trainable, this.depthwiseConstraint);
          this.pointwiseKernel = this.addWeight("pointwise_kernel", pointwiseKernelShape, "float32", this.pointwiseInitializer, this.pointwiseRegularizer, trainable, this.pointwiseConstraint);
          if (this.useBias) {
            this.bias = this.addWeight("bias", [this.filters], "float32", this.biasInitializer, this.biasRegularizer, trainable, this.biasConstraint);
          } else {
            this.bias = null;
          }
          this.inputSpec = [new InputSpec({ ndim: this.rank + 2, axes: (_a2 = {}, _a2[channelAxis] = inputDim, _a2) })];
          this.built = true;
        };
        SeparableConv2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            inputs = getExactlyOneTensor(inputs);
            var output;
            if (_this.rank === 1) {
              throw new NotImplementedError("1D separable convolution is not implemented yet.");
            } else if (_this.rank === 2) {
              if (_this.dataFormat === "channelsFirst") {
                inputs = tfc__namespace.transpose(inputs, [0, 2, 3, 1]);
              }
              output = tfc__namespace.separableConv2d(inputs, _this.depthwiseKernel.read(), _this.pointwiseKernel.read(), _this.strides, _this.padding, _this.dilationRate, "NHWC");
            }
            if (_this.useBias) {
              output = biasAdd(output, _this.bias.read(), _this.dataFormat);
            }
            if (_this.activation != null) {
              output = _this.activation.apply(output);
            }
            if (_this.dataFormat === "channelsFirst") {
              output = tfc__namespace.transpose(output, [0, 3, 1, 2]);
            }
            return output;
          });
        };
        SeparableConv2.prototype.getConfig = function() {
          var config = _super.prototype.getConfig.call(this);
          delete config["rank"];
          delete config["kernelInitializer"];
          delete config["kernelRegularizer"];
          delete config["kernelConstraint"];
          config["depthwiseInitializer"] = serializeInitializer(this.depthwiseInitializer);
          config["pointwiseInitializer"] = serializeInitializer(this.pointwiseInitializer);
          config["depthwiseRegularizer"] = serializeRegularizer(this.depthwiseRegularizer);
          config["pointwiseRegularizer"] = serializeRegularizer(this.pointwiseRegularizer);
          config["depthwiseConstraint"] = serializeConstraint(this.depthwiseConstraint);
          config["pointwiseConstraint"] = serializeConstraint(this.pointwiseConstraint);
          return config;
        };
        return SeparableConv2;
      }(Conv)
    );
    SeparableConv.className = "SeparableConv";
    var SeparableConv2D = (
      /** @class */
      function(_super) {
        __extends(SeparableConv2D2, _super);
        function SeparableConv2D2(args) {
          return _super.call(this, 2, args) || this;
        }
        return SeparableConv2D2;
      }(SeparableConv)
    );
    SeparableConv2D.className = "SeparableConv2D";
    tfc.serialization.registerClass(SeparableConv2D);
    var Conv1D = (
      /** @class */
      function(_super) {
        __extends(Conv1D2, _super);
        function Conv1D2(args) {
          var _this = _super.call(this, 1, args) || this;
          Conv1D2.verifyArgs(args);
          _this.inputSpec = [{ ndim: 3 }];
          return _this;
        }
        Conv1D2.prototype.getConfig = function() {
          var config = _super.prototype.getConfig.call(this);
          delete config["rank"];
          delete config["dataFormat"];
          return config;
        };
        Conv1D2.verifyArgs = function(args) {
          if (typeof args.kernelSize !== "number" && !checkArrayTypeAndLength(args.kernelSize, "number", 1, 1)) {
            throw new ValueError("Conv1D expects config.kernelSize to be number or number[] with " + "length 1, but received ".concat(JSON.stringify(args.kernelSize), "."));
          }
        };
        return Conv1D2;
      }(Conv)
    );
    Conv1D.className = "Conv1D";
    tfc.serialization.registerClass(Conv1D);
    var Cropping2D = (
      /** @class */
      function(_super) {
        __extends(Cropping2D2, _super);
        function Cropping2D2(args) {
          var _this = _super.call(this, args) || this;
          if (typeof args.cropping === "number") {
            _this.cropping = [[args.cropping, args.cropping], [args.cropping, args.cropping]];
          } else if (typeof args.cropping[0] === "number") {
            _this.cropping = [
              [args.cropping[0], args.cropping[0]],
              [args.cropping[1], args.cropping[1]]
            ];
          } else {
            _this.cropping = args.cropping;
          }
          _this.dataFormat = args.dataFormat === void 0 ? "channelsLast" : args.dataFormat;
          _this.inputSpec = [{ ndim: 4 }];
          return _this;
        }
        Cropping2D2.prototype.computeOutputShape = function(inputShape) {
          if (this.dataFormat === "channelsFirst") {
            return [
              inputShape[0],
              inputShape[1],
              inputShape[2] - this.cropping[0][0] - this.cropping[0][1],
              inputShape[3] - this.cropping[1][0] - this.cropping[1][1]
            ];
          } else {
            return [
              inputShape[0],
              inputShape[1] - this.cropping[0][0] - this.cropping[0][1],
              inputShape[2] - this.cropping[1][0] - this.cropping[1][1],
              inputShape[3]
            ];
          }
        };
        Cropping2D2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            inputs = getExactlyOneTensor(inputs);
            if (_this.dataFormat === "channelsLast") {
              var hSliced = sliceAlongAxis(inputs, _this.cropping[0][0], inputs.shape[1] - _this.cropping[0][0] - _this.cropping[0][1], 2);
              return sliceAlongAxis(hSliced, _this.cropping[1][0], inputs.shape[2] - _this.cropping[1][1] - _this.cropping[1][0], 3);
            } else {
              var hSliced = sliceAlongAxis(inputs, _this.cropping[0][0], inputs.shape[2] - _this.cropping[0][0] - _this.cropping[0][1], 3);
              return sliceAlongAxis(hSliced, _this.cropping[1][0], inputs.shape[3] - _this.cropping[1][1] - _this.cropping[1][0], 4);
            }
          });
        };
        Cropping2D2.prototype.getConfig = function() {
          var config = { cropping: this.cropping, dataFormat: this.dataFormat };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return Cropping2D2;
      }(Layer)
    );
    Cropping2D.className = "Cropping2D";
    tfc.serialization.registerClass(Cropping2D);
    var UpSampling2D = (
      /** @class */
      function(_super) {
        __extends(UpSampling2D2, _super);
        function UpSampling2D2(args) {
          var _this = _super.call(this, args) || this;
          _this.DEFAULT_SIZE = [2, 2];
          _this.inputSpec = [{ ndim: 4 }];
          _this.size = args.size == null ? _this.DEFAULT_SIZE : args.size;
          _this.dataFormat = args.dataFormat == null ? "channelsLast" : args.dataFormat;
          checkDataFormat(_this.dataFormat);
          _this.interpolation = args.interpolation == null ? "nearest" : args.interpolation;
          checkInterpolationFormat(_this.interpolation);
          return _this;
        }
        UpSampling2D2.prototype.computeOutputShape = function(inputShape) {
          if (this.dataFormat === "channelsFirst") {
            var height = inputShape[2] == null ? null : this.size[0] * inputShape[2];
            var width = inputShape[3] == null ? null : this.size[1] * inputShape[3];
            return [inputShape[0], inputShape[1], height, width];
          } else {
            var height = inputShape[1] == null ? null : this.size[0] * inputShape[1];
            var width = inputShape[2] == null ? null : this.size[1] * inputShape[2];
            return [inputShape[0], height, width, inputShape[3]];
          }
        };
        UpSampling2D2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc__namespace.tidy(function() {
            var input2 = getExactlyOneTensor(inputs);
            var inputShape = input2.shape;
            if (_this.dataFormat === "channelsFirst") {
              input2 = tfc__namespace.transpose(input2, [0, 2, 3, 1]);
              var height = _this.size[0] * inputShape[2];
              var width = _this.size[1] * inputShape[3];
              var resized = _this.interpolation === "nearest" ? tfc__namespace.image.resizeNearestNeighbor(input2, [height, width]) : tfc__namespace.image.resizeBilinear(input2, [height, width]);
              return tfc__namespace.transpose(resized, [0, 3, 1, 2]);
            } else {
              var height = _this.size[0] * inputShape[1];
              var width = _this.size[1] * inputShape[2];
              return _this.interpolation === "nearest" ? tfc__namespace.image.resizeNearestNeighbor(input2, [height, width]) : tfc__namespace.image.resizeBilinear(input2, [height, width]);
            }
          });
        };
        UpSampling2D2.prototype.getConfig = function() {
          var config = {
            size: this.size,
            dataFormat: this.dataFormat,
            interpolation: this.interpolation
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return UpSampling2D2;
      }(Layer)
    );
    UpSampling2D.className = "UpSampling2D";
    tfc.serialization.registerClass(UpSampling2D);
    function depthwiseConv2d$1(x, depthwiseKernel, strides, padding, dataFormat, dilationRate) {
      if (strides === void 0) {
        strides = [1, 1];
      }
      if (padding === void 0) {
        padding = "valid";
      }
      return tfc.tidy(function() {
        if (dataFormat == null) {
          dataFormat = imageDataFormat();
        }
        checkDataFormat(dataFormat);
        var y = preprocessConv2DInput(x, dataFormat);
        if (x.rank !== 4) {
          throw new ValueError("Input for depthwiseConv2d is required to be 4-D, but is instead " + "".concat(x.rank, "-D"));
        }
        if (depthwiseKernel.rank !== 4) {
          throw new ValueError("depthwiseKernel is required to be 4-D, but is instead " + "".concat(depthwiseKernel.rank, "-D"));
        }
        y = tfc__namespace.depthwiseConv2d(y, depthwiseKernel, strides, padding === "same" ? "same" : "valid", "NHWC", dilationRate);
        if (dataFormat === "channelsFirst") {
          y = tfc__namespace.transpose(y, [0, 3, 1, 2]);
        }
        return y;
      });
    }
    var DepthwiseConv2D = (
      /** @class */
      function(_super) {
        __extends(DepthwiseConv2D2, _super);
        function DepthwiseConv2D2(args) {
          var _this = _super.call(this, 2, args) || this;
          _this.depthwiseKernel = null;
          _this.depthMultiplier = args.depthMultiplier == null ? 1 : args.depthMultiplier;
          _this.depthwiseInitializer = getInitializer(args.depthwiseInitializer || _this.DEFAULT_KERNEL_INITIALIZER);
          _this.depthwiseConstraint = getConstraint(args.depthwiseConstraint);
          _this.depthwiseRegularizer = getRegularizer(args.depthwiseRegularizer);
          return _this;
        }
        DepthwiseConv2D2.prototype.build = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          if (inputShape.length < 4) {
            throw new ValueError("Inputs to DepthwiseConv2D should have rank 4. " + "Received input shape: ".concat(JSON.stringify(inputShape), "."));
          }
          var channelAxis = this.dataFormat === "channelsFirst" ? 1 : 3;
          if (inputShape[channelAxis] == null || inputShape[channelAxis] < 0) {
            throw new ValueError("The channel dimension of the inputs to DepthwiseConv2D should " + "be defined, but is not (".concat(inputShape[channelAxis], ")."));
          }
          var inputDim = inputShape[channelAxis];
          var depthwiseKernelShape = [
            this.kernelSize[0],
            this.kernelSize[1],
            inputDim,
            this.depthMultiplier
          ];
          this.depthwiseKernel = this.addWeight("depthwise_kernel", depthwiseKernelShape, null, this.depthwiseInitializer, this.depthwiseRegularizer, true, this.depthwiseConstraint);
          if (this.useBias) {
            this.bias = this.addWeight("bias", [inputDim * this.depthMultiplier], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint);
          } else {
            this.bias = null;
          }
          this.built = true;
        };
        DepthwiseConv2D2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            inputs = getExactlyOneTensor(inputs);
            var outputs = depthwiseConv2d$1(inputs, _this.depthwiseKernel.read(), _this.strides, _this.padding, _this.dataFormat, null);
            if (_this.useBias) {
              outputs = biasAdd(outputs, _this.bias.read(), _this.dataFormat);
            }
            if (_this.activation != null) {
              outputs = _this.activation.apply(outputs);
            }
            return outputs;
          });
        };
        DepthwiseConv2D2.prototype.computeOutputShape = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          var rows = this.dataFormat === "channelsFirst" ? inputShape[2] : inputShape[1];
          var cols = this.dataFormat === "channelsFirst" ? inputShape[3] : inputShape[2];
          var outFilters = this.dataFormat === "channelsFirst" ? inputShape[1] * this.depthMultiplier : inputShape[3] * this.depthMultiplier;
          var outRows = convOutputLength(rows, this.kernelSize[0], this.padding, this.strides[0]);
          var outCols = convOutputLength(cols, this.kernelSize[1], this.padding, this.strides[1]);
          if (this.dataFormat === "channelsFirst") {
            return [inputShape[0], outFilters, outRows, outCols];
          } else {
            return [inputShape[0], outRows, outCols, outFilters];
          }
        };
        DepthwiseConv2D2.prototype.getConfig = function() {
          var config = _super.prototype.getConfig.call(this);
          config["depthMultiplier"] = this.depthMultiplier;
          config["depthwiseInitializer"] = serializeInitializer(this.depthwiseInitializer);
          config["depthwiseRegularizer"] = serializeRegularizer(this.depthwiseRegularizer);
          config["depthwiseConstraint"] = serializeConstraint(this.depthwiseRegularizer);
          return config;
        };
        return DepthwiseConv2D2;
      }(BaseConv)
    );
    DepthwiseConv2D.className = "DepthwiseConv2D";
    tfc.serialization.registerClass(DepthwiseConv2D);
    function standardizeArgs(inputs, initialState, constants, numConstants) {
      if (Array.isArray(inputs)) {
        if (initialState != null || constants != null) {
          throw new ValueError("When inputs is an array, neither initialState or constants should be provided");
        }
        if (numConstants != null) {
          constants = inputs.slice(inputs.length - numConstants, inputs.length);
          inputs = inputs.slice(0, inputs.length - numConstants);
        }
        if (inputs.length > 1) {
          initialState = inputs.slice(1, inputs.length);
        }
        inputs = inputs[0];
      }
      function toListOrNull(x) {
        if (x == null || Array.isArray(x)) {
          return x;
        } else {
          return [x];
        }
      }
      initialState = toListOrNull(initialState);
      constants = toListOrNull(constants);
      return { inputs, initialState, constants };
    }
    function rnn$1(stepFunction, inputs, initialStates, goBackwards, mask, constants, unroll, needPerStepOutputs) {
      if (goBackwards === void 0) {
        goBackwards = false;
      }
      if (unroll === void 0) {
        unroll = false;
      }
      if (needPerStepOutputs === void 0) {
        needPerStepOutputs = false;
      }
      return tfc__namespace.tidy(function() {
        var ndim = inputs.shape.length;
        if (ndim < 3) {
          throw new ValueError("Input should be at least 3D, but is ".concat(ndim, "D."));
        }
        var axes = [1, 0].concat(range(2, ndim));
        inputs = tfc__namespace.transpose(inputs, axes);
        if (constants != null) {
          throw new NotImplementedError("The rnn() functoin of the deeplearn.js backend does not support constants yet.");
        }
        if (unroll) {
          console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend.");
        }
        if (mask != null) {
          mask = tfc__namespace.cast(tfc__namespace.cast(mask, "bool"), "float32");
          if (mask.rank === ndim - 1) {
            mask = tfc__namespace.expandDims(mask, -1);
          }
          mask = tfc__namespace.transpose(mask, axes);
        }
        if (goBackwards) {
          inputs = tfc__namespace.reverse(inputs, 0);
          if (mask != null) {
            mask = tfc__namespace.reverse(mask, 0);
          }
        }
        var perStepOutputs = [];
        var lastOutput;
        var states = initialStates;
        var timeSteps = inputs.shape[0];
        var perStepInputs = tfc__namespace.unstack(inputs);
        var perStepMasks;
        if (mask != null) {
          perStepMasks = tfc__namespace.unstack(mask);
        }
        var _loop_1 = function(t2) {
          var currentInput = perStepInputs[t2];
          var stepOutputs = tfc__namespace.tidy(function() {
            return stepFunction(currentInput, states);
          });
          if (mask == null) {
            lastOutput = stepOutputs[0];
            states = stepOutputs[1];
          } else {
            var maskedOutputs = tfc__namespace.tidy(function() {
              var stepMask = perStepMasks[t2];
              var negStepMask = tfc__namespace.sub(tfc__namespace.onesLike(stepMask), stepMask);
              var output = tfc__namespace.add(tfc__namespace.mul(stepOutputs[0], stepMask), tfc__namespace.mul(states[0], negStepMask));
              var newStates = states.map(function(state, i) {
                return tfc__namespace.add(tfc__namespace.mul(stepOutputs[1][i], stepMask), tfc__namespace.mul(state, negStepMask));
              });
              return { output, newStates };
            });
            lastOutput = maskedOutputs.output;
            states = maskedOutputs.newStates;
          }
          if (needPerStepOutputs) {
            perStepOutputs.push(lastOutput);
          }
        };
        for (var t = 0; t < timeSteps; ++t) {
          _loop_1(t);
        }
        var outputs;
        if (needPerStepOutputs) {
          var axis = 1;
          outputs = tfc__namespace.stack(perStepOutputs, axis);
        }
        return [lastOutput, outputs, states];
      });
    }
    var RNN = (
      /** @class */
      function(_super) {
        __extends(RNN2, _super);
        function RNN2(args) {
          var _this = _super.call(this, args) || this;
          var cell;
          if (args.cell == null) {
            throw new ValueError("cell property is missing for the constructor of RNN.");
          } else if (Array.isArray(args.cell)) {
            cell = new StackedRNNCells({ cells: args.cell });
          } else {
            cell = args.cell;
          }
          if (cell.stateSize == null) {
            throw new ValueError("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");
          }
          _this.cell = cell;
          _this.returnSequences = args.returnSequences == null ? false : args.returnSequences;
          _this.returnState = args.returnState == null ? false : args.returnState;
          _this.goBackwards = args.goBackwards == null ? false : args.goBackwards;
          _this._stateful = args.stateful == null ? false : args.stateful;
          _this.unroll = args.unroll == null ? false : args.unroll;
          _this.supportsMasking = true;
          _this.inputSpec = [new InputSpec({ ndim: 3 })];
          _this.stateSpec = null;
          _this.states_ = null;
          _this.numConstants = null;
          _this.keptStates = [];
          return _this;
        }
        RNN2.prototype.getStates = function() {
          if (this.states_ == null) {
            var numStates = Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;
            return range(0, numStates).map(function(x) {
              return null;
            });
          } else {
            return this.states_;
          }
        };
        RNN2.prototype.setStates = function(states) {
          this.states_ = states;
        };
        RNN2.prototype.computeOutputShape = function(inputShape) {
          var e_12, _b;
          if (isArrayOfShapes(inputShape)) {
            inputShape = inputShape[0];
          }
          inputShape = inputShape;
          var stateSize = this.cell.stateSize;
          if (!Array.isArray(stateSize)) {
            stateSize = [stateSize];
          }
          var outputDim = stateSize[0];
          var outputShape;
          if (this.returnSequences) {
            outputShape = [inputShape[0], inputShape[1], outputDim];
          } else {
            outputShape = [inputShape[0], outputDim];
          }
          if (this.returnState) {
            var stateShape = [];
            try {
              for (var stateSize_1 = __values(stateSize), stateSize_1_1 = stateSize_1.next(); !stateSize_1_1.done; stateSize_1_1 = stateSize_1.next()) {
                var dim = stateSize_1_1.value;
                stateShape.push([inputShape[0], dim]);
              }
            } catch (e_1_1) {
              e_12 = { error: e_1_1 };
            } finally {
              try {
                if (stateSize_1_1 && !stateSize_1_1.done && (_b = stateSize_1.return)) _b.call(stateSize_1);
              } finally {
                if (e_12) throw e_12.error;
              }
            }
            return [outputShape].concat(stateShape);
          } else {
            return outputShape;
          }
        };
        RNN2.prototype.computeMask = function(inputs, mask) {
          var _this = this;
          return tfc__namespace.tidy(function() {
            if (Array.isArray(mask)) {
              mask = mask[0];
            }
            var outputMask = _this.returnSequences ? mask : null;
            if (_this.returnState) {
              var stateMask = _this.states.map(function(s) {
                return null;
              });
              return [outputMask].concat(stateMask);
            } else {
              return outputMask;
            }
          });
        };
        Object.defineProperty(RNN2.prototype, "states", {
          /**
           * Get the current state tensors of the RNN.
           *
           * If the state hasn't been set, return an array of `null`s of the correct
           * length.
           */
          get: function() {
            if (this.states_ == null) {
              var numStates = Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;
              var output = [];
              for (var i = 0; i < numStates; ++i) {
                output.push(null);
              }
              return output;
            } else {
              return this.states_;
            }
          },
          set: function(s) {
            this.states_ = s;
          },
          enumerable: false,
          configurable: true
        });
        RNN2.prototype.build = function(inputShape) {
          if (this.numConstants != null) {
            throw new NotImplementedError("Constants support is not implemented in RNN yet.");
          }
          if (isArrayOfShapes(inputShape)) {
            inputShape = inputShape[0];
          }
          inputShape = inputShape;
          var batchSize = this.stateful ? inputShape[0] : null;
          var inputDim = inputShape.slice(2);
          this.inputSpec[0] = new InputSpec({ shape: __spreadArray([batchSize, null], __read(inputDim), false) });
          var stepInputShape = [inputShape[0]].concat(inputShape.slice(2));
          {
            this.cell.build(stepInputShape);
          }
          var stateSize;
          if (Array.isArray(this.cell.stateSize)) {
            stateSize = this.cell.stateSize;
          } else {
            stateSize = [this.cell.stateSize];
          }
          if (this.stateSpec != null) {
            if (!tfc.util.arraysEqual(this.stateSpec.map(function(spec) {
              return spec.shape[spec.shape.length - 1];
            }), stateSize)) {
              throw new ValueError("An initialState was passed that is not compatible with " + "cell.stateSize. Received stateSpec=".concat(this.stateSpec, "; ") + "However cell.stateSize is ".concat(this.cell.stateSize));
            }
          } else {
            this.stateSpec = stateSize.map(function(dim) {
              return new InputSpec({ shape: [null, dim] });
            });
          }
          if (this.stateful) {
            this.resetStates();
          }
        };
        RNN2.prototype.resetStates = function(states, training) {
          var _this = this;
          if (training === void 0) {
            training = false;
          }
          tfc.tidy(function() {
            if (!_this.stateful) {
              throw new AttributeError("Cannot call resetStates() on an RNN Layer that is not stateful.");
            }
            var batchSize = _this.inputSpec[0].shape[0];
            if (batchSize == null) {
              throw new ValueError("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");
            }
            if (_this.states_ == null) {
              if (Array.isArray(_this.cell.stateSize)) {
                _this.states_ = _this.cell.stateSize.map(function(dim2) {
                  return tfc__namespace.zeros([batchSize, dim2]);
                });
              } else {
                _this.states_ = [tfc__namespace.zeros([batchSize, _this.cell.stateSize])];
              }
            } else if (states == null) {
              tfc__namespace.dispose(_this.states_);
              if (_this.keptStates != null) {
                tfc__namespace.dispose(_this.keptStates);
                _this.keptStates = [];
              }
              if (Array.isArray(_this.cell.stateSize)) {
                _this.states_ = _this.cell.stateSize.map(function(dim2) {
                  return tfc__namespace.zeros([batchSize, dim2]);
                });
              } else {
                _this.states_[0] = tfc__namespace.zeros([batchSize, _this.cell.stateSize]);
              }
            } else {
              if (!Array.isArray(states)) {
                states = [states];
              }
              if (states.length !== _this.states_.length) {
                throw new ValueError("Layer ".concat(_this.name, " expects ").concat(_this.states_.length, " state(s), ") + "but it received ".concat(states.length, " state value(s). Input ") + "received: ".concat(states));
              }
              if (training === true) {
                _this.keptStates.push(_this.states_.slice());
              } else {
                tfc__namespace.dispose(_this.states_);
              }
              for (var index = 0; index < _this.states_.length; ++index) {
                var value = states[index];
                var dim = Array.isArray(_this.cell.stateSize) ? _this.cell.stateSize[index] : _this.cell.stateSize;
                var expectedShape = [batchSize, dim];
                if (!tfc.util.arraysEqual(value.shape, expectedShape)) {
                  throw new ValueError("State ".concat(index, " is incompatible with layer ").concat(_this.name, ": ") + "expected shape=".concat(expectedShape, ", received shape=").concat(value.shape));
                }
                _this.states_[index] = value;
              }
            }
            _this.states_ = _this.states_.map(function(state) {
              return tfc__namespace.keep(state.clone());
            });
          });
        };
        RNN2.prototype.apply = function(inputs, kwargs) {
          var e_2, _b;
          var initialState = kwargs == null ? null : kwargs["initialState"];
          var constants = kwargs == null ? null : kwargs["constants"];
          if (kwargs == null) {
            kwargs = {};
          }
          var standardized = standardizeArgs(inputs, initialState, constants, this.numConstants);
          inputs = standardized.inputs;
          initialState = standardized.initialState;
          constants = standardized.constants;
          var additionalInputs = [];
          var additionalSpecs = [];
          if (initialState != null) {
            kwargs["initialState"] = initialState;
            additionalInputs = additionalInputs.concat(initialState);
            this.stateSpec = [];
            try {
              for (var initialState_1 = __values(initialState), initialState_1_1 = initialState_1.next(); !initialState_1_1.done; initialState_1_1 = initialState_1.next()) {
                var state = initialState_1_1.value;
                this.stateSpec.push(new InputSpec({ shape: state.shape }));
              }
            } catch (e_2_1) {
              e_2 = { error: e_2_1 };
            } finally {
              try {
                if (initialState_1_1 && !initialState_1_1.done && (_b = initialState_1.return)) _b.call(initialState_1);
              } finally {
                if (e_2) throw e_2.error;
              }
            }
            additionalSpecs = additionalSpecs.concat(this.stateSpec);
          }
          if (constants != null) {
            kwargs["constants"] = constants;
            additionalInputs = additionalInputs.concat(constants);
            this.numConstants = constants.length;
          }
          var isTensor = additionalInputs[0] instanceof SymbolicTensor;
          if (isTensor) {
            var fullInput = [inputs].concat(additionalInputs);
            var fullInputSpec = this.inputSpec.concat(additionalSpecs);
            var originalInputSpec = this.inputSpec;
            this.inputSpec = fullInputSpec;
            var output = _super.prototype.apply.call(this, fullInput, kwargs);
            this.inputSpec = originalInputSpec;
            return output;
          } else {
            return _super.prototype.apply.call(this, inputs, kwargs);
          }
        };
        RNN2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            var mask = kwargs == null ? null : kwargs["mask"];
            var training = kwargs == null ? null : kwargs["training"];
            var initialState = kwargs == null ? null : kwargs["initialState"];
            inputs = getExactlyOneTensor(inputs);
            if (initialState == null) {
              if (_this.stateful) {
                initialState = _this.states_;
              } else {
                initialState = _this.getInitialState(inputs);
              }
            }
            var numStates = Array.isArray(_this.cell.stateSize) ? _this.cell.stateSize.length : 1;
            if (initialState.length !== numStates) {
              throw new ValueError("RNN Layer has ".concat(numStates, " state(s) but was passed ") + "".concat(initialState.length, " initial state(s)."));
            }
            if (_this.unroll) {
              console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");
            }
            var cellCallKwargs = { training };
            var step2 = function(inputs2, states2) {
              var outputs2 = _this.cell.call([inputs2].concat(states2), cellCallKwargs);
              return [outputs2[0], outputs2.slice(1)];
            };
            var rnnOutputs = rnn$1(step2, inputs, initialState, _this.goBackwards, mask, null, _this.unroll, _this.returnSequences);
            var lastOutput = rnnOutputs[0];
            var outputs = rnnOutputs[1];
            var states = rnnOutputs[2];
            if (_this.stateful) {
              _this.resetStates(states, training);
            }
            var output = _this.returnSequences ? outputs : lastOutput;
            if (_this.returnState) {
              return [output].concat(states);
            } else {
              return output;
            }
          });
        };
        RNN2.prototype.getInitialState = function(inputs) {
          var _this = this;
          return tfc.tidy(function() {
            var initialState = tfc__namespace.zeros(inputs.shape);
            initialState = tfc__namespace.sum(initialState, [1, 2]);
            initialState = expandDims$1(initialState);
            if (Array.isArray(_this.cell.stateSize)) {
              return _this.cell.stateSize.map(function(dim) {
                return dim > 1 ? tile$1(initialState, [1, dim]) : initialState;
              });
            } else {
              return _this.cell.stateSize > 1 ? [tile$1(initialState, [1, _this.cell.stateSize])] : [initialState];
            }
          });
        };
        Object.defineProperty(RNN2.prototype, "trainableWeights", {
          get: function() {
            if (!this.trainable) {
              return [];
            }
            return this.cell.trainableWeights;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(RNN2.prototype, "nonTrainableWeights", {
          get: function() {
            if (!this.trainable) {
              return this.cell.weights;
            }
            return this.cell.nonTrainableWeights;
          },
          enumerable: false,
          configurable: true
        });
        RNN2.prototype.setFastWeightInitDuringBuild = function(value) {
          _super.prototype.setFastWeightInitDuringBuild.call(this, value);
          if (this.cell != null) {
            this.cell.setFastWeightInitDuringBuild(value);
          }
        };
        RNN2.prototype.getConfig = function() {
          var baseConfig = _super.prototype.getConfig.call(this);
          var config = {
            returnSequences: this.returnSequences,
            returnState: this.returnState,
            goBackwards: this.goBackwards,
            stateful: this.stateful,
            unroll: this.unroll
          };
          if (this.numConstants != null) {
            config["numConstants"] = this.numConstants;
          }
          var cellConfig = this.cell.getConfig();
          if (this.getClassName() === RNN2.className) {
            config["cell"] = {
              "className": this.cell.getClassName(),
              "config": cellConfig
            };
          }
          return Object.assign(Object.assign(Object.assign({}, cellConfig), baseConfig), config);
        };
        RNN2.fromConfig = function(cls, config, customObjects) {
          if (customObjects === void 0) {
            customObjects = {};
          }
          var cellConfig = config["cell"];
          var cell = deserialize(cellConfig, customObjects);
          return new cls(Object.assign(config, { cell }));
        };
        return RNN2;
      }(Layer)
    );
    RNN.className = "RNN";
    tfc.serialization.registerClass(RNN);
    var RNNCell = (
      /** @class */
      function(_super) {
        __extends(RNNCell2, _super);
        function RNNCell2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        return RNNCell2;
      }(Layer)
    );
    var SimpleRNNCell = (
      /** @class */
      function(_super) {
        __extends(SimpleRNNCell2, _super);
        function SimpleRNNCell2(args) {
          var _this = _super.call(this, args) || this;
          _this.DEFAULT_ACTIVATION = "tanh";
          _this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal";
          _this.DEFAULT_RECURRENT_INITIALIZER = "orthogonal";
          _this.DEFAULT_BIAS_INITIALIZER = "zeros";
          _this.units = args.units;
          assertPositiveInteger(_this.units, "units");
          _this.activation = getActivation(args.activation == null ? _this.DEFAULT_ACTIVATION : args.activation);
          _this.useBias = args.useBias == null ? true : args.useBias;
          _this.kernelInitializer = getInitializer(args.kernelInitializer || _this.DEFAULT_KERNEL_INITIALIZER);
          _this.recurrentInitializer = getInitializer(args.recurrentInitializer || _this.DEFAULT_RECURRENT_INITIALIZER);
          _this.biasInitializer = getInitializer(args.biasInitializer || _this.DEFAULT_BIAS_INITIALIZER);
          _this.kernelRegularizer = getRegularizer(args.kernelRegularizer);
          _this.recurrentRegularizer = getRegularizer(args.recurrentRegularizer);
          _this.biasRegularizer = getRegularizer(args.biasRegularizer);
          _this.kernelConstraint = getConstraint(args.kernelConstraint);
          _this.recurrentConstraint = getConstraint(args.recurrentConstraint);
          _this.biasConstraint = getConstraint(args.biasConstraint);
          _this.dropout = min([1, max([0, args.dropout == null ? 0 : args.dropout])]);
          _this.recurrentDropout = min([
            1,
            max([0, args.recurrentDropout == null ? 0 : args.recurrentDropout])
          ]);
          _this.dropoutFunc = args.dropoutFunc;
          _this.stateSize = _this.units;
          _this.dropoutMask = null;
          _this.recurrentDropoutMask = null;
          return _this;
        }
        SimpleRNNCell2.prototype.build = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          this.kernel = this.addWeight("kernel", [inputShape[inputShape.length - 1], this.units], null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint);
          this.recurrentKernel = this.addWeight("recurrent_kernel", [this.units, this.units], null, this.recurrentInitializer, this.recurrentRegularizer, true, this.recurrentConstraint);
          if (this.useBias) {
            this.bias = this.addWeight("bias", [this.units], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint);
          } else {
            this.bias = null;
          }
          this.built = true;
        };
        SimpleRNNCell2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            inputs = inputs;
            if (inputs.length !== 2) {
              throw new ValueError("SimpleRNNCell expects 2 input Tensors, got ".concat(inputs.length, "."));
            }
            var prevOutput = inputs[1];
            inputs = inputs[0];
            var training = kwargs["training"] == null ? false : kwargs["training"];
            if (0 < _this.dropout && _this.dropout < 1 && _this.dropoutMask == null) {
              _this.dropoutMask = generateDropoutMask({
                ones: function() {
                  return tfc__namespace.onesLike(inputs);
                },
                rate: _this.dropout,
                training,
                dropoutFunc: _this.dropoutFunc
              });
            }
            if (0 < _this.recurrentDropout && _this.recurrentDropout < 1 && _this.recurrentDropoutMask == null) {
              _this.recurrentDropoutMask = generateDropoutMask({
                ones: function() {
                  return tfc__namespace.onesLike(prevOutput);
                },
                rate: _this.recurrentDropout,
                training,
                dropoutFunc: _this.dropoutFunc
              });
            }
            var h;
            var dpMask = _this.dropoutMask;
            var recDpMask = _this.recurrentDropoutMask;
            if (dpMask != null) {
              h = dot$1(tfc__namespace.mul(inputs, dpMask), _this.kernel.read());
            } else {
              h = dot$1(inputs, _this.kernel.read());
            }
            if (_this.bias != null) {
              h = biasAdd(h, _this.bias.read());
            }
            if (recDpMask != null) {
              prevOutput = tfc__namespace.mul(prevOutput, recDpMask);
            }
            var output = tfc__namespace.add(h, dot$1(prevOutput, _this.recurrentKernel.read()));
            if (_this.activation != null) {
              output = _this.activation.apply(output);
            }
            return [output, output];
          });
        };
        SimpleRNNCell2.prototype.getConfig = function() {
          var baseConfig = _super.prototype.getConfig.call(this);
          var config = {
            units: this.units,
            activation: serializeActivation(this.activation),
            useBias: this.useBias,
            kernelInitializer: serializeInitializer(this.kernelInitializer),
            recurrentInitializer: serializeInitializer(this.recurrentInitializer),
            biasInitializer: serializeInitializer(this.biasInitializer),
            kernelRegularizer: serializeRegularizer(this.kernelRegularizer),
            recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer),
            biasRegularizer: serializeRegularizer(this.biasRegularizer),
            activityRegularizer: serializeRegularizer(this.activityRegularizer),
            kernelConstraint: serializeConstraint(this.kernelConstraint),
            recurrentConstraint: serializeConstraint(this.recurrentConstraint),
            biasConstraint: serializeConstraint(this.biasConstraint),
            dropout: this.dropout,
            recurrentDropout: this.recurrentDropout
          };
          return Object.assign(Object.assign({}, baseConfig), config);
        };
        return SimpleRNNCell2;
      }(RNNCell)
    );
    SimpleRNNCell.className = "SimpleRNNCell";
    tfc.serialization.registerClass(SimpleRNNCell);
    var SimpleRNN = (
      /** @class */
      function(_super) {
        __extends(SimpleRNN2, _super);
        function SimpleRNN2(args) {
          args.cell = new SimpleRNNCell(args);
          return _super.call(this, args) || this;
        }
        SimpleRNN2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            if (_this.cell.dropoutMask != null) {
              tfc__namespace.dispose(_this.cell.dropoutMask);
              _this.cell.dropoutMask = null;
            }
            if (_this.cell.recurrentDropoutMask != null) {
              tfc__namespace.dispose(_this.cell.recurrentDropoutMask);
              _this.cell.recurrentDropoutMask = null;
            }
            var mask = kwargs == null ? null : kwargs["mask"];
            var training = kwargs == null ? null : kwargs["training"];
            var initialState = kwargs == null ? null : kwargs["initialState"];
            return _super.prototype.call.call(_this, inputs, { mask, training, initialState });
          });
        };
        SimpleRNN2.fromConfig = function(cls, config) {
          return new cls(config);
        };
        return SimpleRNN2;
      }(RNN)
    );
    SimpleRNN.className = "SimpleRNN";
    tfc.serialization.registerClass(SimpleRNN);
    var GRUCell = (
      /** @class */
      function(_super) {
        __extends(GRUCell2, _super);
        function GRUCell2(args) {
          var _this = _super.call(this, args) || this;
          _this.DEFAULT_ACTIVATION = "tanh";
          _this.DEFAULT_RECURRENT_ACTIVATION = "hardSigmoid";
          _this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal";
          _this.DEFAULT_RECURRENT_INITIALIZER = "orthogonal";
          _this.DEFAULT_BIAS_INITIALIZER = "zeros";
          if (args.resetAfter) {
            throw new ValueError("GRUCell does not support reset_after parameter set to true.");
          }
          _this.units = args.units;
          assertPositiveInteger(_this.units, "units");
          _this.activation = getActivation(args.activation === void 0 ? _this.DEFAULT_ACTIVATION : args.activation);
          _this.recurrentActivation = getActivation(args.recurrentActivation === void 0 ? _this.DEFAULT_RECURRENT_ACTIVATION : args.recurrentActivation);
          _this.useBias = args.useBias == null ? true : args.useBias;
          _this.kernelInitializer = getInitializer(args.kernelInitializer || _this.DEFAULT_KERNEL_INITIALIZER);
          _this.recurrentInitializer = getInitializer(args.recurrentInitializer || _this.DEFAULT_RECURRENT_INITIALIZER);
          _this.biasInitializer = getInitializer(args.biasInitializer || _this.DEFAULT_BIAS_INITIALIZER);
          _this.kernelRegularizer = getRegularizer(args.kernelRegularizer);
          _this.recurrentRegularizer = getRegularizer(args.recurrentRegularizer);
          _this.biasRegularizer = getRegularizer(args.biasRegularizer);
          _this.kernelConstraint = getConstraint(args.kernelConstraint);
          _this.recurrentConstraint = getConstraint(args.recurrentConstraint);
          _this.biasConstraint = getConstraint(args.biasConstraint);
          _this.dropout = min([1, max([0, args.dropout == null ? 0 : args.dropout])]);
          _this.recurrentDropout = min([
            1,
            max([0, args.recurrentDropout == null ? 0 : args.recurrentDropout])
          ]);
          _this.dropoutFunc = args.dropoutFunc;
          _this.implementation = args.implementation;
          _this.stateSize = _this.units;
          _this.dropoutMask = null;
          _this.recurrentDropoutMask = null;
          return _this;
        }
        GRUCell2.prototype.build = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          var inputDim = inputShape[inputShape.length - 1];
          this.kernel = this.addWeight("kernel", [inputDim, this.units * 3], null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint);
          this.recurrentKernel = this.addWeight("recurrent_kernel", [this.units, this.units * 3], null, this.recurrentInitializer, this.recurrentRegularizer, true, this.recurrentConstraint);
          if (this.useBias) {
            this.bias = this.addWeight("bias", [this.units * 3], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint);
          } else {
            this.bias = null;
          }
          this.built = true;
        };
        GRUCell2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            inputs = inputs;
            if (inputs.length !== 2) {
              throw new ValueError("GRUCell expects 2 input Tensors (inputs, h, c), got " + "".concat(inputs.length, "."));
            }
            var training = kwargs["training"] == null ? false : kwargs["training"];
            var hTMinus1 = inputs[1];
            inputs = inputs[0];
            if (0 < _this.dropout && _this.dropout < 1 && _this.dropoutMask == null) {
              _this.dropoutMask = generateDropoutMask({
                ones: function() {
                  return tfc__namespace.onesLike(inputs);
                },
                rate: _this.dropout,
                training,
                count: 3,
                dropoutFunc: _this.dropoutFunc
              });
            }
            if (0 < _this.recurrentDropout && _this.recurrentDropout < 1 && _this.recurrentDropoutMask == null) {
              _this.recurrentDropoutMask = generateDropoutMask({
                ones: function() {
                  return tfc__namespace.onesLike(hTMinus1);
                },
                rate: _this.recurrentDropout,
                training,
                count: 3,
                dropoutFunc: _this.dropoutFunc
              });
            }
            var dpMask = _this.dropoutMask;
            var recDpMask = _this.recurrentDropoutMask;
            var z;
            var r;
            var hh;
            if (0 < _this.dropout && _this.dropout < 1) {
              inputs = tfc__namespace.mul(inputs, dpMask[0]);
            }
            var matrixX = dot$1(inputs, _this.kernel.read());
            if (_this.useBias) {
              matrixX = biasAdd(matrixX, _this.bias.read());
            }
            if (0 < _this.recurrentDropout && _this.recurrentDropout < 1) {
              hTMinus1 = tfc__namespace.mul(hTMinus1, recDpMask[0]);
            }
            var recurrentKernelValue = _this.recurrentKernel.read();
            var _b = __read(tfc__namespace.split(recurrentKernelValue, [2 * _this.units, _this.units], recurrentKernelValue.rank - 1), 2), rk1 = _b[0], rk2 = _b[1];
            var matrixInner = dot$1(hTMinus1, rk1);
            var _c = __read(tfc__namespace.split(matrixX, 3, matrixX.rank - 1), 3), xZ = _c[0], xR = _c[1], xH = _c[2];
            var _d = __read(tfc__namespace.split(matrixInner, 2, matrixInner.rank - 1), 2), recurrentZ = _d[0], recurrentR = _d[1];
            z = _this.recurrentActivation.apply(tfc__namespace.add(xZ, recurrentZ));
            r = _this.recurrentActivation.apply(tfc__namespace.add(xR, recurrentR));
            var recurrentH = dot$1(tfc__namespace.mul(r, hTMinus1), rk2);
            hh = _this.activation.apply(tfc__namespace.add(xH, recurrentH));
            var h = tfc__namespace.add(tfc__namespace.mul(z, hTMinus1), tfc__namespace.mul(tfc__namespace.add(1, tfc__namespace.neg(z)), hh));
            return [h, h];
          });
        };
        GRUCell2.prototype.getConfig = function() {
          var baseConfig = _super.prototype.getConfig.call(this);
          var config = {
            units: this.units,
            activation: serializeActivation(this.activation),
            recurrentActivation: serializeActivation(this.recurrentActivation),
            useBias: this.useBias,
            kernelInitializer: serializeInitializer(this.kernelInitializer),
            recurrentInitializer: serializeInitializer(this.recurrentInitializer),
            biasInitializer: serializeInitializer(this.biasInitializer),
            kernelRegularizer: serializeRegularizer(this.kernelRegularizer),
            recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer),
            biasRegularizer: serializeRegularizer(this.biasRegularizer),
            activityRegularizer: serializeRegularizer(this.activityRegularizer),
            kernelConstraint: serializeConstraint(this.kernelConstraint),
            recurrentConstraint: serializeConstraint(this.recurrentConstraint),
            biasConstraint: serializeConstraint(this.biasConstraint),
            dropout: this.dropout,
            recurrentDropout: this.recurrentDropout,
            implementation: this.implementation,
            resetAfter: false
          };
          return Object.assign(Object.assign({}, baseConfig), config);
        };
        return GRUCell2;
      }(RNNCell)
    );
    GRUCell.className = "GRUCell";
    tfc.serialization.registerClass(GRUCell);
    var GRU = (
      /** @class */
      function(_super) {
        __extends(GRU2, _super);
        function GRU2(args) {
          if (args.implementation === 0) {
            console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call.");
          }
          args.cell = new GRUCell(args);
          return _super.call(this, args) || this;
        }
        GRU2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            if (_this.cell.dropoutMask != null) {
              tfc__namespace.dispose(_this.cell.dropoutMask);
              _this.cell.dropoutMask = null;
            }
            if (_this.cell.recurrentDropoutMask != null) {
              tfc__namespace.dispose(_this.cell.recurrentDropoutMask);
              _this.cell.recurrentDropoutMask = null;
            }
            var mask = kwargs == null ? null : kwargs["mask"];
            var training = kwargs == null ? null : kwargs["training"];
            var initialState = kwargs == null ? null : kwargs["initialState"];
            return _super.prototype.call.call(_this, inputs, { mask, training, initialState });
          });
        };
        GRU2.fromConfig = function(cls, config) {
          if (config["implmentation"] === 0) {
            config["implementation"] = 1;
          }
          return new cls(config);
        };
        return GRU2;
      }(RNN)
    );
    GRU.className = "GRU";
    tfc.serialization.registerClass(GRU);
    var LSTMCell = (
      /** @class */
      function(_super) {
        __extends(LSTMCell2, _super);
        function LSTMCell2(args) {
          var _this = _super.call(this, args) || this;
          _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 = args.units;
          assertPositiveInteger(_this.units, "units");
          _this.activation = getActivation(args.activation === void 0 ? _this.DEFAULT_ACTIVATION : args.activation);
          _this.recurrentActivation = getActivation(args.recurrentActivation === void 0 ? _this.DEFAULT_RECURRENT_ACTIVATION : args.recurrentActivation);
          _this.useBias = args.useBias == null ? true : args.useBias;
          _this.kernelInitializer = getInitializer(args.kernelInitializer || _this.DEFAULT_KERNEL_INITIALIZER);
          _this.recurrentInitializer = getInitializer(args.recurrentInitializer || _this.DEFAULT_RECURRENT_INITIALIZER);
          _this.biasInitializer = getInitializer(args.biasInitializer || _this.DEFAULT_BIAS_INITIALIZER);
          _this.unitForgetBias = args.unitForgetBias;
          _this.kernelRegularizer = getRegularizer(args.kernelRegularizer);
          _this.recurrentRegularizer = getRegularizer(args.recurrentRegularizer);
          _this.biasRegularizer = getRegularizer(args.biasRegularizer);
          _this.kernelConstraint = getConstraint(args.kernelConstraint);
          _this.recurrentConstraint = getConstraint(args.recurrentConstraint);
          _this.biasConstraint = getConstraint(args.biasConstraint);
          _this.dropout = min([1, max([0, args.dropout == null ? 0 : args.dropout])]);
          _this.recurrentDropout = min([
            1,
            max([0, args.recurrentDropout == null ? 0 : args.recurrentDropout])
          ]);
          _this.dropoutFunc = args.dropoutFunc;
          _this.implementation = args.implementation;
          _this.stateSize = [_this.units, _this.units];
          _this.dropoutMask = null;
          _this.recurrentDropoutMask = null;
          return _this;
        }
        LSTMCell2.prototype.build = function(inputShape) {
          var _a2;
          inputShape = getExactlyOneShape(inputShape);
          var inputDim = inputShape[inputShape.length - 1];
          this.kernel = this.addWeight("kernel", [inputDim, this.units * 4], null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint);
          this.recurrentKernel = this.addWeight("recurrent_kernel", [this.units, this.units * 4], null, this.recurrentInitializer, this.recurrentRegularizer, true, this.recurrentConstraint);
          var biasInitializer;
          if (this.useBias) {
            if (this.unitForgetBias) {
              var capturedBiasInit_1 = this.biasInitializer;
              var capturedUnits_1 = this.units;
              biasInitializer = new (_a2 = /** @class */
              function(_super2) {
                __extends(CustomInit, _super2);
                function CustomInit() {
                  return _super2 !== null && _super2.apply(this, arguments) || this;
                }
                CustomInit.prototype.apply = function(shape, dtype) {
                  var bI = capturedBiasInit_1.apply([capturedUnits_1]);
                  var bF = new Ones().apply([capturedUnits_1]);
                  var bCAndH = capturedBiasInit_1.apply([capturedUnits_1 * 2]);
                  return concatAlongFirstAxis(concatAlongFirstAxis(bI, bF), bCAndH);
                };
                return CustomInit;
              }(Initializer), /** @nocollapse */
              _a2.className = "CustomInit", _a2)();
            } else {
              biasInitializer = this.biasInitializer;
            }
            this.bias = this.addWeight("bias", [this.units * 4], null, biasInitializer, this.biasRegularizer, true, this.biasConstraint);
          } else {
            this.bias = null;
          }
          this.built = true;
        };
        LSTMCell2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            var training = kwargs["training"] == null ? false : kwargs["training"];
            inputs = inputs;
            if (inputs.length !== 3) {
              throw new ValueError("LSTMCell expects 3 input Tensors (inputs, h, c), got " + "".concat(inputs.length, "."));
            }
            var hTMinus1 = inputs[1];
            var cTMinus1 = inputs[2];
            inputs = inputs[0];
            if (0 < _this.dropout && _this.dropout < 1 && _this.dropoutMask == null) {
              _this.dropoutMask = generateDropoutMask({
                ones: function() {
                  return tfc__namespace.onesLike(inputs);
                },
                rate: _this.dropout,
                training,
                count: 4,
                dropoutFunc: _this.dropoutFunc
              });
            }
            if (0 < _this.recurrentDropout && _this.recurrentDropout < 1 && _this.recurrentDropoutMask == null) {
              _this.recurrentDropoutMask = generateDropoutMask({
                ones: function() {
                  return tfc__namespace.onesLike(hTMinus1);
                },
                rate: _this.recurrentDropout,
                training,
                count: 4,
                dropoutFunc: _this.dropoutFunc
              });
            }
            var dpMask = _this.dropoutMask;
            var recDpMask = _this.recurrentDropoutMask;
            var i;
            var f;
            var c;
            var o;
            if (0 < _this.dropout && _this.dropout < 1) {
              inputs = tfc__namespace.mul(inputs, dpMask[0]);
            }
            var z = dot$1(inputs, _this.kernel.read());
            if (0 < _this.recurrentDropout && _this.recurrentDropout < 1) {
              hTMinus1 = tfc__namespace.mul(hTMinus1, recDpMask[0]);
            }
            z = tfc__namespace.add(z, dot$1(hTMinus1, _this.recurrentKernel.read()));
            if (_this.useBias) {
              z = biasAdd(z, _this.bias.read());
            }
            var _b = __read(tfc__namespace.split(z, 4, z.rank - 1), 4), z0 = _b[0], z1 = _b[1], z2 = _b[2], z3 = _b[3];
            i = _this.recurrentActivation.apply(z0);
            f = _this.recurrentActivation.apply(z1);
            c = tfc__namespace.add(tfc__namespace.mul(f, cTMinus1), tfc__namespace.mul(i, _this.activation.apply(z2)));
            o = _this.recurrentActivation.apply(z3);
            var h = tfc__namespace.mul(o, _this.activation.apply(c));
            return [h, h, c];
          });
        };
        LSTMCell2.prototype.getConfig = function() {
          var baseConfig = _super.prototype.getConfig.call(this);
          var config = {
            units: this.units,
            activation: serializeActivation(this.activation),
            recurrentActivation: serializeActivation(this.recurrentActivation),
            useBias: this.useBias,
            kernelInitializer: serializeInitializer(this.kernelInitializer),
            recurrentInitializer: serializeInitializer(this.recurrentInitializer),
            biasInitializer: serializeInitializer(this.biasInitializer),
            unitForgetBias: this.unitForgetBias,
            kernelRegularizer: serializeRegularizer(this.kernelRegularizer),
            recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer),
            biasRegularizer: serializeRegularizer(this.biasRegularizer),
            activityRegularizer: serializeRegularizer(this.activityRegularizer),
            kernelConstraint: serializeConstraint(this.kernelConstraint),
            recurrentConstraint: serializeConstraint(this.recurrentConstraint),
            biasConstraint: serializeConstraint(this.biasConstraint),
            dropout: this.dropout,
            recurrentDropout: this.recurrentDropout,
            implementation: this.implementation
          };
          return Object.assign(Object.assign({}, baseConfig), config);
        };
        return LSTMCell2;
      }(RNNCell)
    );
    LSTMCell.className = "LSTMCell";
    tfc.serialization.registerClass(LSTMCell);
    var LSTM = (
      /** @class */
      function(_super) {
        __extends(LSTM2, _super);
        function LSTM2(args) {
          if (args.implementation === 0) {
            console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call.");
          }
          args.cell = new LSTMCell(args);
          return _super.call(this, args) || this;
        }
        LSTM2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            if (_this.cell.dropoutMask != null) {
              tfc__namespace.dispose(_this.cell.dropoutMask);
              _this.cell.dropoutMask = null;
            }
            if (_this.cell.recurrentDropoutMask != null) {
              tfc__namespace.dispose(_this.cell.recurrentDropoutMask);
              _this.cell.recurrentDropoutMask = null;
            }
            var mask = kwargs == null ? null : kwargs["mask"];
            var training = kwargs == null ? null : kwargs["training"];
            var initialState = kwargs == null ? null : kwargs["initialState"];
            return _super.prototype.call.call(_this, inputs, { mask, training, initialState });
          });
        };
        LSTM2.fromConfig = function(cls, config) {
          if (config["implmentation"] === 0) {
            config["implementation"] = 1;
          }
          return new cls(config);
        };
        return LSTM2;
      }(RNN)
    );
    LSTM.className = "LSTM";
    tfc.serialization.registerClass(LSTM);
    var StackedRNNCells = (
      /** @class */
      function(_super) {
        __extends(StackedRNNCells2, _super);
        function StackedRNNCells2(args) {
          var _this = _super.call(this, args) || this;
          _this.cells = args.cells;
          return _this;
        }
        Object.defineProperty(StackedRNNCells2.prototype, "stateSize", {
          get: function() {
            var e_3, _b;
            var stateSize = [];
            try {
              for (var _c = __values(this.cells.slice().reverse()), _d = _c.next(); !_d.done; _d = _c.next()) {
                var cell = _d.value;
                if (Array.isArray(cell.stateSize)) {
                  stateSize.push.apply(stateSize, __spreadArray([], __read(cell.stateSize), false));
                } else {
                  stateSize.push(cell.stateSize);
                }
              }
            } catch (e_3_1) {
              e_3 = { error: e_3_1 };
            } finally {
              try {
                if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
              } finally {
                if (e_3) throw e_3.error;
              }
            }
            return stateSize;
          },
          enumerable: false,
          configurable: true
        });
        StackedRNNCells2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            var e_4, _b, e_5, _c;
            inputs = inputs;
            var states = inputs.slice(1);
            var nestedStates = [];
            try {
              for (var _d = __values(_this.cells.slice().reverse()), _e = _d.next(); !_e.done; _e = _d.next()) {
                var cell = _e.value;
                if (Array.isArray(cell.stateSize)) {
                  nestedStates.push(states.splice(0, cell.stateSize.length));
                } else {
                  nestedStates.push(states.splice(0, 1));
                }
              }
            } catch (e_4_1) {
              e_4 = { error: e_4_1 };
            } finally {
              try {
                if (_e && !_e.done && (_b = _d.return)) _b.call(_d);
              } finally {
                if (e_4) throw e_4.error;
              }
            }
            nestedStates.reverse();
            var newNestedStates = [];
            var callInputs;
            for (var i = 0; i < _this.cells.length; ++i) {
              var cell = _this.cells[i];
              states = nestedStates[i];
              if (i === 0) {
                callInputs = [inputs[0]].concat(states);
              } else {
                callInputs = [callInputs[0]].concat(states);
              }
              callInputs = cell.call(callInputs, kwargs);
              newNestedStates.push(callInputs.slice(1));
            }
            states = [];
            try {
              for (var _f = __values(newNestedStates.slice().reverse()), _g = _f.next(); !_g.done; _g = _f.next()) {
                var cellStates = _g.value;
                states.push.apply(states, __spreadArray([], __read(cellStates), false));
              }
            } catch (e_5_1) {
              e_5 = { error: e_5_1 };
            } finally {
              try {
                if (_g && !_g.done && (_c = _f.return)) _c.call(_f);
              } finally {
                if (e_5) throw e_5.error;
              }
            }
            return [callInputs[0]].concat(states);
          });
        };
        StackedRNNCells2.prototype.build = function(inputShape) {
          if (isArrayOfShapes(inputShape)) {
            inputShape = inputShape[0];
          }
          inputShape = inputShape;
          var outputDim;
          this.cells.forEach(function(cell, i) {
            nameScope("RNNCell_".concat(i), function() {
              cell.build(inputShape);
              if (Array.isArray(cell.stateSize)) {
                outputDim = cell.stateSize[0];
              } else {
                outputDim = cell.stateSize;
              }
              inputShape = [inputShape[0], outputDim];
            });
          });
          this.built = true;
        };
        StackedRNNCells2.prototype.getConfig = function() {
          var baseConfig = _super.prototype.getConfig.call(this);
          var getCellConfig = function(cell) {
            return {
              "className": cell.getClassName(),
              "config": cell.getConfig()
            };
          };
          var cellConfigs = this.cells.map(getCellConfig);
          var config = { "cells": cellConfigs };
          return Object.assign(Object.assign({}, baseConfig), config);
        };
        StackedRNNCells2.fromConfig = function(cls, config, customObjects) {
          var e_6, _b;
          if (customObjects === void 0) {
            customObjects = {};
          }
          var cells = [];
          try {
            for (var _c = __values(config["cells"]), _d = _c.next(); !_d.done; _d = _c.next()) {
              var cellConfig = _d.value;
              cells.push(deserialize(cellConfig, customObjects));
            }
          } catch (e_6_1) {
            e_6 = { error: e_6_1 };
          } finally {
            try {
              if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
            } finally {
              if (e_6) throw e_6.error;
            }
          }
          return new cls({ cells });
        };
        Object.defineProperty(StackedRNNCells2.prototype, "trainableWeights", {
          get: function() {
            var e_7, _b;
            if (!this.trainable) {
              return [];
            }
            var weights = [];
            try {
              for (var _c = __values(this.cells), _d = _c.next(); !_d.done; _d = _c.next()) {
                var cell = _d.value;
                weights.push.apply(weights, __spreadArray([], __read(cell.trainableWeights), false));
              }
            } catch (e_7_1) {
              e_7 = { error: e_7_1 };
            } finally {
              try {
                if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
              } finally {
                if (e_7) throw e_7.error;
              }
            }
            return weights;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(StackedRNNCells2.prototype, "nonTrainableWeights", {
          get: function() {
            var e_8, _b, e_9, _c;
            var weights = [];
            try {
              for (var _d = __values(this.cells), _e = _d.next(); !_e.done; _e = _d.next()) {
                var cell = _e.value;
                weights.push.apply(weights, __spreadArray([], __read(cell.nonTrainableWeights), false));
              }
            } catch (e_8_1) {
              e_8 = { error: e_8_1 };
            } finally {
              try {
                if (_e && !_e.done && (_b = _d.return)) _b.call(_d);
              } finally {
                if (e_8) throw e_8.error;
              }
            }
            if (!this.trainable) {
              var trainableWeights = [];
              try {
                for (var _f = __values(this.cells), _g = _f.next(); !_g.done; _g = _f.next()) {
                  var cell = _g.value;
                  trainableWeights.push.apply(trainableWeights, __spreadArray([], __read(cell.trainableWeights), false));
                }
              } catch (e_9_1) {
                e_9 = { error: e_9_1 };
              } finally {
                try {
                  if (_g && !_g.done && (_c = _f.return)) _c.call(_f);
                } finally {
                  if (e_9) throw e_9.error;
                }
              }
              return trainableWeights.concat(weights);
            }
            return weights;
          },
          enumerable: false,
          configurable: true
        });
        StackedRNNCells2.prototype.getWeights = function() {
          var e_10, _b;
          var weights = [];
          try {
            for (var _c = __values(this.cells), _d = _c.next(); !_d.done; _d = _c.next()) {
              var cell = _d.value;
              weights.push.apply(weights, __spreadArray([], __read(cell.weights), false));
            }
          } catch (e_10_1) {
            e_10 = { error: e_10_1 };
          } finally {
            try {
              if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
            } finally {
              if (e_10) throw e_10.error;
            }
          }
          return batchGetValue(weights);
        };
        StackedRNNCells2.prototype.setWeights = function(weights) {
          var e_11, _b;
          var tuples = [];
          try {
            for (var _c = __values(this.cells), _d = _c.next(); !_d.done; _d = _c.next()) {
              var cell = _d.value;
              var numParams = cell.weights.length;
              var inputWeights = weights.splice(numParams);
              for (var i = 0; i < cell.weights.length; ++i) {
                tuples.push([cell.weights[i], inputWeights[i]]);
              }
            }
          } catch (e_11_1) {
            e_11 = { error: e_11_1 };
          } finally {
            try {
              if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
            } finally {
              if (e_11) throw e_11.error;
            }
          }
          batchSetValue(tuples);
        };
        return StackedRNNCells2;
      }(RNNCell)
    );
    StackedRNNCells.className = "StackedRNNCells";
    tfc.serialization.registerClass(StackedRNNCells);
    function generateDropoutMask(args) {
      var ones2 = args.ones, rate = args.rate, _b = args.training, training = _b === void 0 ? false : _b, _c = args.count, count2 = _c === void 0 ? 1 : _c, dropoutFunc = args.dropoutFunc;
      var droppedInputs = function() {
        return dropoutFunc != null ? dropoutFunc(ones2(), rate) : dropout$1(ones2(), rate);
      };
      var createMask = function() {
        return inTrainPhase(droppedInputs, ones2, training);
      };
      if (!count2 || count2 <= 1) {
        return tfc__namespace.keep(createMask().clone());
      }
      var masks = Array(count2).fill(void 0).map(createMask);
      return masks.map(function(m) {
        return tfc__namespace.keep(m.clone());
      });
    }
    var __rest = function(s, e) {
      var t = {};
      for (var p in s)
        if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
          t[p] = s[p];
      if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
          if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
            t[p[i]] = s[p[i]];
        }
      return t;
    };
    (function(_super) {
      __extends(ConvRNN2DCell, _super);
      function ConvRNN2DCell() {
        return _super !== null && _super.apply(this, arguments) || this;
      }
      return ConvRNN2DCell;
    })(RNNCell);
    var ConvRNN2D = (
      /** @class */
      function(_super) {
        __extends(ConvRNN2D2, _super);
        function ConvRNN2D2(args) {
          var _this = this;
          if (args.unroll) {
            throw new NotImplementedError("Unrolling is not possible with convolutional RNNs.");
          }
          if (Array.isArray(args.cell)) {
            throw new NotImplementedError("It is not possible at the moment to stack convolutional cells.");
          }
          _this = _super.call(this, args) || this;
          _this.inputSpec = [new InputSpec({ ndim: 5 })];
          return _this;
        }
        ConvRNN2D2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc__namespace.tidy(function() {
            if (_this.cell.dropoutMask != null) {
              tfc__namespace.dispose(_this.cell.dropoutMask);
              _this.cell.dropoutMask = null;
            }
            if (_this.cell.recurrentDropoutMask != null) {
              tfc__namespace.dispose(_this.cell.recurrentDropoutMask);
              _this.cell.recurrentDropoutMask = null;
            }
            if (kwargs && kwargs["constants"]) {
              throw new ValueError("ConvRNN2D cell does not support constants");
            }
            var mask = kwargs == null ? null : kwargs["mask"];
            var training = kwargs == null ? null : kwargs["training"];
            var initialState = kwargs == null ? null : kwargs["initialState"];
            return _super.prototype.call.call(_this, inputs, { mask, training, initialState });
          });
        };
        ConvRNN2D2.prototype.computeOutputShape = function(inputShape) {
          var outShape = this.computeSingleOutputShape(inputShape);
          if (!this.returnSequences) {
            outShape = __spreadArray([outShape[0]], __read(outShape.slice(2)), false);
          }
          if (this.returnState) {
            outShape = __spreadArray([outShape], __read(Array(2).fill(__spreadArray([inputShape[0]], __read(outShape.slice(-3)), false))), false);
          }
          return outShape;
        };
        ConvRNN2D2.prototype.getInitialState = function(inputs) {
          var _this = this;
          return tfc__namespace.tidy(function() {
            var stateSize = _this.cell.stateSize;
            var inputShape = inputs.shape;
            var outputShape = _this.computeSingleOutputShape(inputShape);
            var stateShape = __spreadArray([outputShape[0]], __read(outputShape.slice(2)), false);
            var initialState = tfc__namespace.zeros(stateShape);
            if (Array.isArray(stateSize)) {
              return Array(stateSize.length).fill(initialState);
            }
            return [initialState];
          });
        };
        ConvRNN2D2.prototype.resetStates = function(states, training) {
          var _this = this;
          if (training === void 0) {
            training = false;
          }
          tfc__namespace.tidy(function() {
            if (!_this.stateful) {
              throw new AttributeError("Cannot call resetStates() on an RNN Layer that is not stateful.");
            }
            var inputShape = _this.inputSpec[0].shape;
            var outputShape = _this.computeSingleOutputShape(inputShape);
            var stateShape = __spreadArray([outputShape[0]], __read(outputShape.slice(2)), false);
            var batchSize = inputShape[0];
            if (batchSize == null) {
              throw new ValueError("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");
            }
            if (_this.getStates() == null) {
              if (Array.isArray(_this.cell.stateSize)) {
                _this.states_ = _this.cell.stateSize.map(function() {
                  return tfc__namespace.zeros(stateShape);
                });
              } else {
                _this.states_ = [tfc__namespace.zeros(stateShape)];
              }
            } else if (states == null) {
              tfc__namespace.dispose(_this.states_);
              if (_this.keptStates != null) {
                tfc__namespace.dispose(_this.keptStates);
                _this.keptStates = [];
              }
              if (Array.isArray(_this.cell.stateSize)) {
                _this.states_ = _this.cell.stateSize.map(function() {
                  return tfc__namespace.zeros(stateShape);
                });
              } else {
                _this.states_[0] = tfc__namespace.zeros(stateShape);
              }
            } else {
              if (!Array.isArray(states)) {
                states = [states];
              }
              if (states.length !== _this.states_.length) {
                throw new ValueError("Layer ".concat(_this.name, " expects ").concat(_this.states_.length, " state(s), ") + "but it received ".concat(states.length, " state value(s). Input ") + "received: ".concat(states));
              }
              if (training) {
                _this.keptStates.push(_this.states_.slice());
              } else {
                tfc__namespace.dispose(_this.states_);
              }
              for (var index = 0; index < _this.states_.length; ++index) {
                var value = states[index];
                var expectedShape = stateShape;
                if (!tfc.util.arraysEqual(value.shape, expectedShape)) {
                  throw new ValueError("State ".concat(index, " is incompatible with layer ").concat(_this.name, ": ") + "expected shape=".concat(expectedShape, ", received shape=").concat(value.shape));
                }
                _this.states_[index] = value;
              }
            }
            _this.states_ = _this.states_.map(function(state) {
              return tfc__namespace.keep(state.clone());
            });
          });
        };
        ConvRNN2D2.prototype.computeSingleOutputShape = function(inputShape) {
          var _b = this.cell, dataFormat = _b.dataFormat, filters = _b.filters, kernelSize = _b.kernelSize, padding = _b.padding, strides = _b.strides, dilationRate = _b.dilationRate;
          var isChannelsFirst = dataFormat === "channelsFirst";
          var h = inputShape[isChannelsFirst ? 3 : 2];
          var w = inputShape[isChannelsFirst ? 4 : 3];
          var hOut = convOutputLength(h, kernelSize[0], padding, strides[0], dilationRate[0]);
          var wOut = convOutputLength(w, kernelSize[1], padding, strides[1], dilationRate[1]);
          var outShape = __spreadArray(__spreadArray([], __read(inputShape.slice(0, 2)), false), __read(isChannelsFirst ? [filters, hOut, wOut] : [hOut, wOut, filters]), false);
          return outShape;
        };
        return ConvRNN2D2;
      }(RNN)
    );
    ConvRNN2D.className = "ConvRNN2D";
    var ConvLSTM2DCell = (
      /** @class */
      function(_super) {
        __extends(ConvLSTM2DCell2, _super);
        function ConvLSTM2DCell2(args) {
          var _this = this;
          var filters = args.filters, kernelSize = args.kernelSize, strides = args.strides, padding = args.padding, dataFormat = args.dataFormat, dilationRate = args.dilationRate;
          _this = _super.call(this, Object.assign(Object.assign({}, args), { units: filters })) || this;
          _this.filters = filters;
          assertPositiveInteger(_this.filters, "filters");
          _this.kernelSize = normalizeArray(kernelSize, 2, "kernelSize");
          _this.kernelSize.forEach(function(size) {
            return assertPositiveInteger(size, "kernelSize");
          });
          _this.strides = normalizeArray(strides || 1, 2, "strides");
          _this.strides.forEach(function(stride) {
            return assertPositiveInteger(stride, "strides");
          });
          _this.padding = padding || "valid";
          checkPaddingMode(_this.padding);
          _this.dataFormat = dataFormat || "channelsLast";
          checkDataFormat(_this.dataFormat);
          _this.dilationRate = normalizeArray(dilationRate || 1, 2, "dilationRate");
          _this.dilationRate.forEach(function(rate) {
            return assertPositiveInteger(rate, "dilationRate");
          });
          return _this;
        }
        ConvLSTM2DCell2.prototype.build = function(inputShape) {
          var _a2;
          inputShape = getExactlyOneShape(inputShape);
          var channelAxis = this.dataFormat === "channelsFirst" ? 1 : inputShape.length - 1;
          if (inputShape[channelAxis] == null) {
            throw new ValueError("The channel dimension of the input should be defined. " + "Found ".concat(inputShape[channelAxis]));
          }
          var inputDim = inputShape[channelAxis];
          var numOfKernels = 4;
          var kernelShape = this.kernelSize.concat([inputDim, this.filters * numOfKernels]);
          this.kernel = this.addWeight("kernel", kernelShape, null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint);
          var recurrentKernelShape = this.kernelSize.concat([this.filters, this.filters * numOfKernels]);
          this.recurrentKernel = this.addWeight("recurrent_kernel", recurrentKernelShape, null, this.recurrentInitializer, this.recurrentRegularizer, true, this.recurrentConstraint);
          if (this.useBias) {
            var biasInitializer = void 0;
            if (this.unitForgetBias) {
              var init_1 = this.biasInitializer;
              var filters_1 = this.filters;
              biasInitializer = new (_a2 = /** @class */
              function(_super2) {
                __extends(CustomInit, _super2);
                function CustomInit() {
                  return _super2 !== null && _super2.apply(this, arguments) || this;
                }
                CustomInit.prototype.apply = function(shape, dtype) {
                  var biasI = init_1.apply([filters_1]);
                  var biasF = tfc__namespace.ones([filters_1]);
                  var biasCAndO = init_1.apply([filters_1 * 2]);
                  return concatenate$1([biasI, biasF, biasCAndO]);
                };
                return CustomInit;
              }(Initializer), /** @nocollapse */
              _a2.className = "CustomInit", _a2)();
            } else {
              biasInitializer = this.biasInitializer;
            }
            this.bias = this.addWeight("bias", [this.filters * numOfKernels], null, biasInitializer, this.biasRegularizer, true, this.biasConstraint);
          }
          this.built = true;
        };
        ConvLSTM2DCell2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc__namespace.tidy(function() {
            if (inputs.length !== 3) {
              throw new ValueError("ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got " + "".concat(inputs.length, "."));
            }
            var training = kwargs["training"] || false;
            var x = inputs[0];
            var hTMinus1 = inputs[1];
            var cTMinus1 = inputs[2];
            var numOfKernels = 4;
            if (0 < _this.dropout && _this.dropout < 1 && _this.dropoutMask == null) {
              _this.dropoutMask = generateDropoutMask({
                ones: function() {
                  return tfc__namespace.onesLike(x);
                },
                rate: _this.dropout,
                training,
                count: numOfKernels,
                dropoutFunc: _this.dropoutFunc
              });
            }
            var dropoutMask = _this.dropoutMask;
            var applyDropout = function(x2, mask, index) {
              if (!mask || !mask[index]) {
                return x2;
              }
              return tfc__namespace.mul(mask[index], x2);
            };
            var xI = applyDropout(x, dropoutMask, 0);
            var xF = applyDropout(x, dropoutMask, 1);
            var xC = applyDropout(x, dropoutMask, 2);
            var xO = applyDropout(x, dropoutMask, 3);
            if (0 < _this.recurrentDropout && _this.recurrentDropout < 1 && _this.recurrentDropoutMask == null) {
              _this.recurrentDropoutMask = generateDropoutMask({
                ones: function() {
                  return tfc__namespace.onesLike(hTMinus1);
                },
                rate: _this.recurrentDropout,
                training,
                count: numOfKernels,
                dropoutFunc: _this.dropoutFunc
              });
            }
            var recDropoutMask = _this.recurrentDropoutMask;
            var hI = applyDropout(hTMinus1, recDropoutMask, 0);
            var hF = applyDropout(hTMinus1, recDropoutMask, 1);
            var hC = applyDropout(hTMinus1, recDropoutMask, 2);
            var hO = applyDropout(hTMinus1, recDropoutMask, 3);
            var kernelChannelAxis = 3;
            var _b = __read(tfc__namespace.split(_this.kernel.read(), numOfKernels, kernelChannelAxis), 4), kernelI = _b[0], kernelF = _b[1], kernelC = _b[2], kernelO = _b[3];
            var _c = __read(_this.useBias ? tfc__namespace.split(_this.bias.read(), numOfKernels) : [null, null, null, null], 4), biasI = _c[0], biasF = _c[1], biasC = _c[2], biasO = _c[3];
            xI = _this.inputConv(xI, kernelI, biasI, _this.padding);
            xF = _this.inputConv(xF, kernelF, biasF, _this.padding);
            xC = _this.inputConv(xC, kernelC, biasC, _this.padding);
            xO = _this.inputConv(xO, kernelO, biasO, _this.padding);
            var _d = __read(tfc__namespace.split(_this.recurrentKernel.read(), numOfKernels, kernelChannelAxis), 4), recKernelI = _d[0], recKernelF = _d[1], recKernelC = _d[2], recKernelO = _d[3];
            hI = _this.recurrentConv(hI, recKernelI);
            hF = _this.recurrentConv(hF, recKernelF);
            hC = _this.recurrentConv(hC, recKernelC);
            hO = _this.recurrentConv(hO, recKernelO);
            var i = _this.recurrentActivation.apply(tfc__namespace.add(xI, hI));
            var f = _this.recurrentActivation.apply(tfc__namespace.add(xF, hF));
            var c = tfc__namespace.add(tfc__namespace.mul(f, cTMinus1), tfc__namespace.mul(i, _this.activation.apply(tfc__namespace.add(xC, hC))));
            var h = tfc__namespace.mul(_this.recurrentActivation.apply(tfc__namespace.add(xO, hO)), _this.activation.apply(c));
            return [h, h, c];
          });
        };
        ConvLSTM2DCell2.prototype.getConfig = function() {
          var _a2 = _super.prototype.getConfig.call(this);
          _a2["units"];
          var baseConfig = __rest(_a2, ["units"]);
          var config = {
            filters: this.filters,
            kernelSize: this.kernelSize,
            padding: this.padding,
            dataFormat: this.dataFormat,
            dilationRate: this.dilationRate,
            strides: this.strides
          };
          return Object.assign(Object.assign({}, baseConfig), config);
        };
        ConvLSTM2DCell2.prototype.inputConv = function(x, w, b, padding) {
          var out = tfc__namespace.conv2d(x, w, this.strides, padding || "valid", this.dataFormat === "channelsFirst" ? "NCHW" : "NHWC", this.dilationRate);
          if (b) {
            return biasAdd(out, b, this.dataFormat);
          }
          return out;
        };
        ConvLSTM2DCell2.prototype.recurrentConv = function(x, w) {
          var strides = 1;
          return tfc__namespace.conv2d(x, w, strides, "same", this.dataFormat === "channelsFirst" ? "NCHW" : "NHWC");
        };
        return ConvLSTM2DCell2;
      }(LSTMCell)
    );
    ConvLSTM2DCell.className = "ConvLSTM2DCell";
    tfc__namespace.serialization.registerClass(ConvLSTM2DCell);
    var ConvLSTM2D = (
      /** @class */
      function(_super) {
        __extends(ConvLSTM2D2, _super);
        function ConvLSTM2D2(args) {
          var cell = new ConvLSTM2DCell(args);
          return _super.call(this, Object.assign(Object.assign({}, args), { cell })) || this;
        }
        ConvLSTM2D2.fromConfig = function(cls, config) {
          return new cls(config);
        };
        return ConvLSTM2D2;
      }(ConvRNN2D)
    );
    ConvLSTM2D.className = "ConvLSTM2D";
    tfc__namespace.serialization.registerClass(ConvLSTM2D);
    var Dropout = (
      /** @class */
      function(_super) {
        __extends(Dropout2, _super);
        function Dropout2(args) {
          var _this = _super.call(this, args) || this;
          _this.rate = Math.max(Math.min(args.rate, 1), 0);
          _this.noiseShape = args.noiseShape;
          _this.seed = args.seed;
          _this.supportsMasking = true;
          return _this;
        }
        Dropout2.prototype.getNoiseShape = function(input2) {
          if (this.noiseShape == null) {
            return this.noiseShape;
          }
          var inputShape = input2.shape;
          var noiseShape = [];
          for (var i = 0; i < this.noiseShape.length; ++i) {
            noiseShape.push(this.noiseShape[i] == null ? inputShape[i] : this.noiseShape[i]);
          }
          return noiseShape;
        };
        Dropout2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            _this.invokeCallHook(inputs, kwargs);
            var input2 = getExactlyOneTensor(inputs);
            if (0 < _this.rate && _this.rate < 1) {
              var training = kwargs["training"] == null ? false : kwargs["training"];
              var noiseShape_1 = _this.getNoiseShape(input2);
              var output = inTrainPhase(function() {
                return dropout$1(input2, _this.rate, noiseShape_1, _this.seed);
              }, function() {
                return input2;
              }, training);
              return output;
            }
            return inputs;
          });
        };
        Dropout2.prototype.getConfig = function() {
          var config = {
            rate: this.rate,
            noiseShape: this.noiseShape,
            seed: this.seed
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        Dropout2.prototype.dispose = function() {
          return _super.prototype.dispose.call(this);
        };
        return Dropout2;
      }(Layer)
    );
    Dropout.className = "Dropout";
    tfc.serialization.registerClass(Dropout);
    var SpatialDropout1D = (
      /** @class */
      function(_super) {
        __extends(SpatialDropout1D2, _super);
        function SpatialDropout1D2(args) {
          var _this = _super.call(this, args) || this;
          _this.inputSpec = [{ ndim: 3 }];
          return _this;
        }
        SpatialDropout1D2.prototype.getNoiseShape = function(input2) {
          var inputShape = input2.shape;
          return [inputShape[0], 1, inputShape[2]];
        };
        return SpatialDropout1D2;
      }(Dropout)
    );
    SpatialDropout1D.className = "SpatialDropout1D";
    tfc.serialization.registerClass(SpatialDropout1D);
    var Dense = (
      /** @class */
      function(_super) {
        __extends(Dense2, _super);
        function Dense2(args) {
          var _this = _super.call(this, args) || this;
          _this.activation = null;
          _this.useBias = true;
          _this.kernel = null;
          _this.bias = null;
          _this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal";
          _this.DEFAULT_BIAS_INITIALIZER = "zeros";
          if (args.batchInputShape == null && args.inputShape == null && args.inputDim != null) {
            var batchSize = null;
            if (args.batchSize != null) {
              batchSize = args.batchSize;
            }
            _this.batchInputShape = [batchSize, args.inputDim];
          }
          _this.units = args.units;
          assertPositiveInteger(_this.units, "units");
          _this.activation = getActivation(args.activation);
          if (args.useBias != null) {
            _this.useBias = args.useBias;
          }
          _this.kernelInitializer = getInitializer(args.kernelInitializer || _this.DEFAULT_KERNEL_INITIALIZER);
          _this.biasInitializer = getInitializer(args.biasInitializer || _this.DEFAULT_BIAS_INITIALIZER);
          _this.kernelConstraint = getConstraint(args.kernelConstraint);
          _this.biasConstraint = getConstraint(args.biasConstraint);
          _this.kernelRegularizer = getRegularizer(args.kernelRegularizer);
          _this.biasRegularizer = getRegularizer(args.biasRegularizer);
          _this.activityRegularizer = getRegularizer(args.activityRegularizer);
          _this.supportsMasking = true;
          _this.inputSpec = [{ minNDim: 2 }];
          return _this;
        }
        Dense2.prototype.build = function(inputShape) {
          var _a2;
          inputShape = getExactlyOneShape(inputShape);
          var inputLastDim = inputShape[inputShape.length - 1];
          if (this.kernel == null) {
            this.kernel = this.addWeight("kernel", [inputLastDim, this.units], null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint);
            if (this.useBias) {
              this.bias = this.addWeight("bias", [this.units], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint);
            }
          }
          this.inputSpec = [{ minNDim: 2, axes: (_a2 = {}, _a2[-1] = inputLastDim, _a2) }];
          this.built = true;
        };
        Dense2.prototype.computeOutputShape = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          var outputShape = inputShape.slice();
          outputShape[outputShape.length - 1] = this.units;
          return outputShape;
        };
        Dense2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            _this.invokeCallHook(inputs, kwargs);
            var input2 = getExactlyOneTensor(inputs);
            var fusedActivationName = mapActivationToFusedKernel(_this.activation.getClassName());
            var output;
            if (fusedActivationName != null) {
              output = dot$1(input2, _this.kernel.read(), fusedActivationName, _this.bias ? _this.bias.read() : null);
            } else {
              output = dot$1(input2, _this.kernel.read());
              if (_this.bias != null) {
                output = biasAdd(output, _this.bias.read());
              }
              if (_this.activation != null) {
                output = _this.activation.apply(output);
              }
            }
            return output;
          });
        };
        Dense2.prototype.getConfig = function() {
          var config = {
            units: this.units,
            activation: serializeActivation(this.activation),
            useBias: this.useBias,
            kernelInitializer: serializeInitializer(this.kernelInitializer),
            biasInitializer: serializeInitializer(this.biasInitializer),
            kernelRegularizer: serializeRegularizer(this.kernelRegularizer),
            biasRegularizer: serializeRegularizer(this.biasRegularizer),
            activityRegularizer: serializeRegularizer(this.activityRegularizer),
            kernelConstraint: serializeConstraint(this.kernelConstraint),
            biasConstraint: serializeConstraint(this.biasConstraint)
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return Dense2;
      }(Layer)
    );
    Dense.className = "Dense";
    tfc.serialization.registerClass(Dense);
    var Flatten = (
      /** @class */
      function(_super) {
        __extends(Flatten2, _super);
        function Flatten2(args) {
          var _this = this;
          args = args || {};
          _this = _super.call(this, args) || this;
          _this.inputSpec = [{ minNDim: 3 }];
          _this.dataFormat = args.dataFormat;
          return _this;
        }
        Flatten2.prototype.computeOutputShape = function(inputShape) {
          var e_12, _a2;
          inputShape = getExactlyOneShape(inputShape);
          try {
            for (var _b = __values(inputShape.slice(1)), _c = _b.next(); !_c.done; _c = _b.next()) {
              var dim = _c.value;
              if (dim == null) {
                throw new ValueError('The shape of the input to "Flatten" is not fully defined ' + "(got ".concat(inputShape.slice(1), "). Make sure to pass a complete ") + '"input_shape" or "batch_input_shape" argument to the first layer in your model.');
              }
            }
          } catch (e_1_1) {
            e_12 = { error: e_1_1 };
          } finally {
            try {
              if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
            } finally {
              if (e_12) throw e_12.error;
            }
          }
          return [inputShape[0], arrayProd(inputShape, 1)];
        };
        Flatten2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            _this.invokeCallHook(inputs, kwargs);
            var input2 = getExactlyOneTensor(inputs);
            if (_this.dataFormat === "channelsFirst" && input2.rank > 1) {
              var permutation = [0];
              for (var i = 2; i < input2.rank; ++i) {
                permutation.push(i);
              }
              permutation.push(1);
              input2 = tfc.transpose(input2, permutation);
            }
            return batchFlatten(input2);
          });
        };
        Flatten2.prototype.getConfig = function() {
          var config = {};
          if (this.dataFormat != null) {
            config["dataFormat"] = this.dataFormat;
          }
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return Flatten2;
      }(Layer)
    );
    Flatten.className = "Flatten";
    tfc.serialization.registerClass(Flatten);
    var Activation = (
      /** @class */
      function(_super) {
        __extends(Activation2, _super);
        function Activation2(args) {
          var _this = _super.call(this, args) || this;
          _this.supportsMasking = true;
          _this.activation = getActivation(args.activation);
          return _this;
        }
        Activation2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            _this.invokeCallHook(inputs, kwargs);
            var input2 = getExactlyOneTensor(inputs);
            return _this.activation.apply(input2);
          });
        };
        Activation2.prototype.getConfig = function() {
          var config = { activation: serializeActivation(this.activation) };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return Activation2;
      }(Layer)
    );
    Activation.className = "Activation";
    tfc.serialization.registerClass(Activation);
    var RepeatVector = (
      /** @class */
      function(_super) {
        __extends(RepeatVector2, _super);
        function RepeatVector2(args) {
          var _this = _super.call(this, args) || this;
          _this.n = args.n;
          _this.inputSpec = [{ ndim: 2 }];
          return _this;
        }
        RepeatVector2.prototype.computeOutputShape = function(inputShape) {
          return [inputShape[0], this.n, inputShape[1]];
        };
        RepeatVector2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            inputs = getExactlyOneTensor(inputs);
            return repeat(inputs, _this.n);
          });
        };
        RepeatVector2.prototype.getConfig = function() {
          var config = {
            n: this.n
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return RepeatVector2;
      }(Layer)
    );
    RepeatVector.className = "RepeatVector";
    tfc.serialization.registerClass(RepeatVector);
    var Reshape = (
      /** @class */
      function(_super) {
        __extends(Reshape2, _super);
        function Reshape2(args) {
          var _this = _super.call(this, args) || this;
          _this.targetShape = args.targetShape;
          for (var i = 0; i < _this.targetShape.length; ++i) {
            if (_this.isUnknown(_this.targetShape[i])) {
              _this.targetShape[i] = null;
            }
          }
          return _this;
        }
        Reshape2.prototype.isUnknown = function(dim) {
          return dim < 0 || dim == null;
        };
        Reshape2.prototype.fixUnknownDimension = function(inputShape, outputShape) {
          var errorMsg = "Total size of new array must be unchanged.";
          var finalShape = outputShape.slice();
          var known = 1;
          var unknown = null;
          for (var i = 0; i < finalShape.length; ++i) {
            var dim = finalShape[i];
            if (this.isUnknown(dim)) {
              if (unknown === null) {
                unknown = i;
              } else {
                throw new ValueError("Can only specifiy one unknown dimension.");
              }
            } else {
              known *= dim;
            }
          }
          var originalSize = arrayProd(inputShape);
          if (unknown !== null) {
            if (known === 0 || originalSize % known !== 0) {
              throw new ValueError(errorMsg);
            }
            finalShape[unknown] = originalSize / known;
          } else if (originalSize !== known) {
            throw new ValueError(errorMsg);
          }
          return finalShape;
        };
        Reshape2.prototype.computeOutputShape = function(inputShape) {
          var anyUnknownDims = false;
          for (var i = 0; i < inputShape.length; ++i) {
            if (this.isUnknown(inputShape[i])) {
              anyUnknownDims = true;
              break;
            }
          }
          if (anyUnknownDims) {
            return inputShape.slice(0, 1).concat(this.targetShape);
          } else {
            return inputShape.slice(0, 1).concat(this.fixUnknownDimension(inputShape.slice(1), this.targetShape));
          }
        };
        Reshape2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            _this.invokeCallHook(inputs, kwargs);
            var input2 = getExactlyOneTensor(inputs);
            var inputShape = input2.shape;
            var outputShape = inputShape.slice(0, 1).concat(_this.fixUnknownDimension(inputShape.slice(1), _this.targetShape));
            return tfc.reshape(input2, outputShape);
          });
        };
        Reshape2.prototype.getConfig = function() {
          var config = {
            targetShape: this.targetShape
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return Reshape2;
      }(Layer)
    );
    Reshape.className = "Reshape";
    tfc.serialization.registerClass(Reshape);
    var Permute = (
      /** @class */
      function(_super) {
        __extends(Permute2, _super);
        function Permute2(args) {
          var _this = _super.call(this, args) || this;
          if (args.dims == null) {
            throw new Error("Required configuration field `dims` is missing during Permute constructor call.");
          }
          if (!Array.isArray(args.dims)) {
            throw new Error("Permute constructor requires `dims` to be an Array, but received " + "".concat(args.dims, " instead."));
          }
          var expectedSortedIndices = range(1, args.dims.length + 1);
          if (!tfc.util.arraysEqual(args.dims.slice().sort(), expectedSortedIndices)) {
            throw new Error("Invalid permutation `dims`: " + JSON.stringify(args.dims) + " `dims` must contain consecutive integers starting from 1.");
          }
          _this.dims = args.dims;
          _this.dimsIncludingBatch = [0].concat(_this.dims);
          _this.inputSpec = [new InputSpec({ ndim: _this.dims.length + 1 })];
          return _this;
        }
        Permute2.prototype.computeOutputShape = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          var outputShape = inputShape.slice();
          this.dims.forEach(function(dim, i) {
            outputShape[i + 1] = inputShape[dim];
          });
          return outputShape;
        };
        Permute2.prototype.call = function(inputs, kwargs) {
          return tfc.transpose(getExactlyOneTensor(inputs), this.dimsIncludingBatch);
        };
        Permute2.prototype.getConfig = function() {
          var config = {
            dims: this.dims
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return Permute2;
      }(Layer)
    );
    Permute.className = "Permute";
    tfc.serialization.registerClass(Permute);
    var Masking = (
      /** @class */
      function(_super) {
        __extends(Masking2, _super);
        function Masking2(args) {
          var _this = _super.call(this, args == null ? {} : args) || this;
          _this.supportsMasking = true;
          if (args != null) {
            _this.maskValue = args.maskValue == null ? 0 : args.maskValue;
          } else {
            _this.maskValue = 0;
          }
          return _this;
        }
        Masking2.prototype.computeOutputShape = function(inputShape) {
          return inputShape;
        };
        Masking2.prototype.getConfig = function() {
          var baseConfig = _super.prototype.getConfig.call(this);
          var config = { maskValue: this.maskValue };
          Object.assign(config, baseConfig);
          return config;
        };
        Masking2.prototype.computeMask = function(inputs, mask) {
          var input2 = getExactlyOneTensor(inputs);
          var axis = -1;
          return tfc.any(tfc.notEqual(input2, this.maskValue), axis);
        };
        Masking2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            _this.invokeCallHook(inputs, kwargs);
            var input2 = getExactlyOneTensor(inputs);
            var axis = -1;
            var keepDims = true;
            var booleanMask = tfc.any(tfc.notEqual(input2, _this.maskValue), axis, keepDims);
            var output = tfc.mul(input2, tfc.cast(booleanMask, input2.dtype));
            return output;
          });
        };
        return Masking2;
      }(Layer)
    );
    Masking.className = "Masking";
    tfc.serialization.registerClass(Masking);
    var Embedding = (
      /** @class */
      function(_super) {
        __extends(Embedding2, _super);
        function Embedding2(args) {
          var _this = _super.call(this, args) || this;
          _this.embeddings = null;
          _this.DEFAULT_EMBEDDINGS_INITIALIZER = "randomUniform";
          if (args.batchInputShape == null && args.inputShape == null) {
            var batchSize = null;
            if (args.batchSize != null) {
              batchSize = args.batchSize;
            }
            if (args.inputLength == null) {
              _this.batchInputShape = [batchSize, null];
            } else {
              _this.batchInputShape = [batchSize].concat(toList(args.inputLength));
            }
          }
          _this.inputDim = args.inputDim;
          assertPositiveInteger(_this.inputDim, "inputDim");
          _this.outputDim = args.outputDim;
          assertPositiveInteger(_this.outputDim, "outputDim");
          _this.embeddingsInitializer = getInitializer(args.embeddingsInitializer || _this.DEFAULT_EMBEDDINGS_INITIALIZER);
          _this.embeddingsRegularizer = getRegularizer(args.embeddingsRegularizer);
          _this.activityRegularizer = getRegularizer(args.activityRegularizer);
          _this.embeddingsConstraint = getConstraint(args.embeddingsConstraint);
          _this.maskZero = args.maskZero;
          _this.supportsMasking = args.maskZero;
          _this.inputLength = args.inputLength;
          return _this;
        }
        Embedding2.prototype.build = function(inputShape) {
          this.embeddings = this.addWeight("embeddings", [this.inputDim, this.outputDim], this.dtype, this.embeddingsInitializer, this.embeddingsRegularizer, true, this.embeddingsConstraint);
          this.built = true;
        };
        Embedding2.prototype.warnOnIncompatibleInputShape = function(inputShape) {
        };
        Embedding2.prototype.computeMask = function(inputs, mask) {
          var _this = this;
          return tfc.tidy(function() {
            if (!_this.maskZero) {
              return null;
            } else {
              inputs = getExactlyOneTensor(inputs);
              return tfc.notEqual(inputs, tfc.zerosLike(inputs));
            }
          });
        };
        Embedding2.prototype.computeOutputShape = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          if (this.inputLength == null) {
            return __spreadArray(__spreadArray([], __read(inputShape), false), [this.outputDim], false);
          }
          var inLens = toList(this.inputLength);
          if (inLens.length !== inputShape.length - 1) {
            throw new ValueError('"inputLength" is '.concat(this.inputLength, ", but received ") + "input shape has shape ".concat(inputShape));
          } else {
            var i = 0;
            for (var k = 0; k < inLens.length; ++k) {
              var s1 = inLens[k];
              var s2 = inputShape[k + 1];
              if (s1 != null && s2 != null && s1 !== s2) {
                throw new ValueError('"inputLength" is '.concat(this.inputLength, ", but received ") + "input shape has shape ".concat(inputShape));
              } else if (s1 == null) {
                inLens[i] = s2;
              }
              i++;
            }
          }
          return __spreadArray(__spreadArray([inputShape[0]], __read(inLens), false), [this.outputDim], false);
        };
        Embedding2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            _this.invokeCallHook(inputs, kwargs);
            var input2 = getExactlyOneTensor(inputs);
            if (input2.dtype !== "int32") {
              input2 = cast$1(input2, "int32");
            }
            var output = gather$1(_this.embeddings.read(), tfc.reshape(input2, [input2.size]));
            return tfc.reshape(output, getExactlyOneShape(_this.computeOutputShape(input2.shape)));
          });
        };
        Embedding2.prototype.getConfig = function() {
          var config = {
            inputDim: this.inputDim,
            outputDim: this.outputDim,
            embeddingsInitializer: serializeInitializer(this.embeddingsInitializer),
            embeddingsRegularizer: serializeRegularizer(this.embeddingsRegularizer),
            activityRegularizer: serializeRegularizer(this.activityRegularizer),
            embeddingsConstraint: serializeConstraint(this.embeddingsConstraint),
            maskZero: this.maskZero,
            inputLength: this.inputLength
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return Embedding2;
      }(Layer)
    );
    Embedding.className = "Embedding";
    tfc.serialization.registerClass(Embedding);
    var Merge = (
      /** @class */
      function(_super) {
        __extends(Merge2, _super);
        function Merge2(args) {
          var _this = _super.call(this, args || {}) || this;
          _this.supportsMasking = true;
          return _this;
        }
        Merge2.prototype.mergeFunction = function(inputs) {
          throw new NotImplementedError();
        };
        Merge2.prototype.computeElementwiseOpOutputShape = function(shape1, shape2) {
          if (shape1 == null || shape2 == null) {
            return null;
          } else if (shape1.length < shape2.length) {
            return this.computeElementwiseOpOutputShape(shape2, shape1);
          } else if (shape2.length === 0) {
            return shape1;
          }
          var outputShape = shape1.slice(0, shape1.length - shape2.length);
          for (var k = 0; k < shape2.length; ++k) {
            var i = shape1[shape1.length - shape2.length + k];
            var j = shape2[k];
            if (i == null || j == null || i < 0 || j < 0) {
              outputShape.push(null);
            } else if (i === 1) {
              outputShape.push(j);
            } else if (j === 1) {
              outputShape.push(i);
            } else {
              if (i !== j) {
                throw new ValueError("Operands could not be broadcast together with shapes " + JSON.stringify(shape1) + " " + JSON.stringify(shape2));
              }
              outputShape.push(i);
            }
          }
          return outputShape;
        };
        Merge2.prototype.build = function(inputShape) {
          var e_12, _a2;
          if (Array.isArray(inputShape) && !Array.isArray(inputShape[0])) {
            inputShape = [getExactlyOneShape(inputShape)];
          }
          inputShape = inputShape;
          if (inputShape.length < 2) {
            throw new ValueError("A merge layer should be called on an Array of at least 2 inputs." + " Got ".concat(inputShape.length, " input(s)."));
          }
          var batchSizes = [];
          try {
            for (var inputShape_1 = __values(inputShape), inputShape_1_1 = inputShape_1.next(); !inputShape_1_1.done; inputShape_1_1 = inputShape_1.next()) {
              var shape = inputShape_1_1.value;
              if (shape != null && shape[0] !== null) {
                batchSizes.push(shape[0]);
              }
            }
          } catch (e_1_1) {
            e_12 = { error: e_1_1 };
          } finally {
            try {
              if (inputShape_1_1 && !inputShape_1_1.done && (_a2 = inputShape_1.return)) _a2.call(inputShape_1);
            } finally {
              if (e_12) throw e_12.error;
            }
          }
          batchSizes = unique(batchSizes);
          if (batchSizes.length > 1) {
            throw new ValueError("Can not merge tensors with different batch sizes. " + "Got tensors with shapes: ".concat(JSON.stringify(inputShape), "."));
          }
          var outputShape = inputShape[0] == null ? null : inputShape[0].slice(1);
          for (var i = 1; i < inputShape.length; ++i) {
            var shape = inputShape[i] == null ? null : inputShape[i].slice(1);
            outputShape = this.computeElementwiseOpOutputShape(outputShape, shape);
          }
          var allRanks = inputShape.map(function(shape2) {
            return shape2.length;
          });
          if (inputShape.indexOf(null) === -1 && unique(allRanks).length === 1) {
            this.reshapeRequired = false;
          } else {
            this.reshapeRequired = true;
          }
        };
        Merge2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            var e_2, _a2, e_3, _b;
            inputs = inputs;
            if (_this.reshapeRequired) {
              var reshapedInputs = [];
              var inputDims = inputs.map(function(input2) {
                return input2.rank;
              });
              if (inputDims.indexOf(null) === -1) {
                var maxNDim = max(inputDims);
                try {
                  for (var inputs_1 = __values(inputs), inputs_1_1 = inputs_1.next(); !inputs_1_1.done; inputs_1_1 = inputs_1.next()) {
                    var x = inputs_1_1.value;
                    var xNDim = x.rank;
                    for (var k = 0; k < maxNDim - xNDim; ++k) {
                      x = expandDims$1(x, 1);
                    }
                    reshapedInputs.push(x);
                  }
                } catch (e_2_1) {
                  e_2 = { error: e_2_1 };
                } finally {
                  try {
                    if (inputs_1_1 && !inputs_1_1.done && (_a2 = inputs_1.return)) _a2.call(inputs_1);
                  } finally {
                    if (e_2) throw e_2.error;
                  }
                }
                return _this.mergeFunction(reshapedInputs);
              } else {
                var transposed = false;
                try {
                  for (var inputs_2 = __values(inputs), inputs_2_1 = inputs_2.next(); !inputs_2_1.done; inputs_2_1 = inputs_2.next()) {
                    var x = inputs_2_1.value;
                    var xNDim = x.rank;
                    if (xNDim == null) {
                      var xShape = x.shape;
                      var batchSize = xShape[0];
                      var newShape = xShape.slice(1).concat([batchSize]);
                      var xTransposed = tfc__namespace.reshape(x, [batchSize].concat(arrayProd(xShape.slice(1))));
                      xTransposed = tfc__namespace.transpose(xTransposed, [1, 0]);
                      xTransposed = tfc__namespace.reshape(xTransposed, newShape);
                      reshapedInputs.push(xTransposed);
                      transposed = true;
                    } else if (xNDim > 1) {
                      var dims = range(1, xNDim).concat([0]);
                      reshapedInputs.push(tfc__namespace.transpose(x, dims));
                      transposed = true;
                    } else {
                      reshapedInputs.push(x);
                    }
                  }
                } catch (e_3_1) {
                  e_3 = { error: e_3_1 };
                } finally {
                  try {
                    if (inputs_2_1 && !inputs_2_1.done && (_b = inputs_2.return)) _b.call(inputs_2);
                  } finally {
                    if (e_3) throw e_3.error;
                  }
                }
                var y = _this.mergeFunction(reshapedInputs);
                var yNDim = y.rank;
                if (transposed) {
                  if (yNDim == null) {
                    var yShape = y.shape;
                    var yNDim_1 = yShape.length;
                    var batchSize = yShape[yNDim_1 - 1];
                    var newShape = [batchSize].concat(yShape.slice(0, yShape.length - 1));
                    y = tfc__namespace.reshape(tfc__namespace.transpose(tfc__namespace.reshape(y, [-1, batchSize]), [1, 0]), newShape);
                  } else if (yNDim > 1) {
                    var dims = [yNDim - 1].concat(range(0, yNDim - 1));
                    y = tfc__namespace.transpose(y, dims);
                  }
                }
                return y;
              }
            } else {
              return _this.mergeFunction(inputs);
            }
          });
        };
        Merge2.prototype.computeOutputShape = function(inputShape) {
          var e_4, _a2;
          inputShape = inputShape;
          var outputShape;
          if (inputShape[0] == null) {
            outputShape = null;
          } else {
            outputShape = inputShape[0].slice(1);
          }
          for (var i = 1; i < inputShape.length; ++i) {
            var shape = inputShape[i] == null ? null : inputShape[i].slice(1);
            outputShape = this.computeElementwiseOpOutputShape(outputShape, shape);
          }
          var batchSizes = [];
          try {
            for (var inputShape_2 = __values(inputShape), inputShape_2_1 = inputShape_2.next(); !inputShape_2_1.done; inputShape_2_1 = inputShape_2.next()) {
              var shape = inputShape_2_1.value;
              if (shape != null && shape[0] !== null) {
                batchSizes.push(shape[0]);
              }
            }
          } catch (e_4_1) {
            e_4 = { error: e_4_1 };
          } finally {
            try {
              if (inputShape_2_1 && !inputShape_2_1.done && (_a2 = inputShape_2.return)) _a2.call(inputShape_2);
            } finally {
              if (e_4) throw e_4.error;
            }
          }
          batchSizes = unique(batchSizes);
          if (batchSizes.length === 1) {
            outputShape = batchSizes.concat(outputShape);
          } else {
            outputShape = [null].concat(outputShape);
          }
          return outputShape;
        };
        Merge2.prototype.computeMask = function(inputs, mask) {
          return tfc__namespace.tidy(function() {
            if (mask == null) {
              return null;
            }
            if (!Array.isArray(mask)) {
              throw new ValueError("`mask` should be an Array");
            }
            if (!Array.isArray(inputs)) {
              throw new ValueError("`inputs` should be an Array");
            }
            if (mask.length !== inputs.length) {
              throw new ValueError("The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths " + "(".concat(inputs.length, " vs ").concat(mask.length, ")"));
            }
            if (mask.every(function(m) {
              return m == null;
            })) {
              return null;
            }
            mask = mask.map(function(m) {
              return m == null ? m : tfc__namespace.expandDims(m, 0);
            });
            var output = mask[0];
            for (var i = 1; i < mask.length - 1; ++i) {
              output = tfc__namespace.logicalAnd(output, mask[i]);
            }
            return output;
          });
        };
        return Merge2;
      }(Layer)
    );
    var Add = (
      /** @class */
      function(_super) {
        __extends(Add2, _super);
        function Add2(args) {
          return _super.call(this, args) || this;
        }
        Add2.prototype.mergeFunction = function(inputs) {
          return tfc.tidy(function() {
            var output = inputs[0].clone();
            for (var i = 1; i < inputs.length; ++i) {
              output = tfc__namespace.add(output, inputs[i]);
            }
            return output;
          });
        };
        return Add2;
      }(Merge)
    );
    Add.className = "Add";
    tfc.serialization.registerClass(Add);
    var Multiply = (
      /** @class */
      function(_super) {
        __extends(Multiply2, _super);
        function Multiply2(args) {
          return _super.call(this, args) || this;
        }
        Multiply2.prototype.mergeFunction = function(inputs) {
          return tfc.tidy(function() {
            var output = inputs[0].clone();
            for (var i = 1; i < inputs.length; ++i) {
              output = tfc__namespace.mul(output, inputs[i]);
            }
            return output;
          });
        };
        return Multiply2;
      }(Merge)
    );
    Multiply.className = "Multiply";
    tfc.serialization.registerClass(Multiply);
    var Average = (
      /** @class */
      function(_super) {
        __extends(Average2, _super);
        function Average2(args) {
          return _super.call(this, args) || this;
        }
        Average2.prototype.mergeFunction = function(inputs) {
          return tfc.tidy(function() {
            var output = inputs[0].clone();
            for (var i = 1; i < inputs.length; ++i) {
              output = tfc__namespace.add(output, inputs[i]);
            }
            return tfc__namespace.mul(1 / inputs.length, output);
          });
        };
        return Average2;
      }(Merge)
    );
    Average.className = "Average";
    tfc.serialization.registerClass(Average);
    var Maximum = (
      /** @class */
      function(_super) {
        __extends(Maximum2, _super);
        function Maximum2(args) {
          return _super.call(this, args) || this;
        }
        Maximum2.prototype.mergeFunction = function(inputs) {
          return tfc.tidy(function() {
            var output = inputs[0];
            for (var i = 1; i < inputs.length; ++i) {
              output = tfc__namespace.maximum(output, inputs[i]);
            }
            return output;
          });
        };
        return Maximum2;
      }(Merge)
    );
    Maximum.className = "Maximum";
    tfc.serialization.registerClass(Maximum);
    var Minimum = (
      /** @class */
      function(_super) {
        __extends(Minimum2, _super);
        function Minimum2(args) {
          return _super.call(this, args) || this;
        }
        Minimum2.prototype.mergeFunction = function(inputs) {
          return tfc.tidy(function() {
            var output = inputs[0];
            for (var i = 1; i < inputs.length; ++i) {
              output = tfc__namespace.minimum(output, inputs[i]);
            }
            return output;
          });
        };
        return Minimum2;
      }(Merge)
    );
    Minimum.className = "Minimum";
    tfc.serialization.registerClass(Minimum);
    var Concatenate = (
      /** @class */
      function(_super) {
        __extends(Concatenate2, _super);
        function Concatenate2(args) {
          var _this = _super.call(this, args) || this;
          _this.DEFAULT_AXIS = -1;
          if (args == null) {
            args = {};
          }
          _this.axis = args.axis == null ? _this.DEFAULT_AXIS : args.axis;
          _this.supportsMasking = true;
          _this.reshapeRequired = false;
          return _this;
        }
        Concatenate2.prototype.build = function(inputShape) {
          var e_5, _a2, e_6, _b;
          if (!(Array.isArray(inputShape) && Array.isArray(inputShape[0])) || inputShape.length === 1) {
            throw new ValueError("A `Concatenate` layer should be called on a list of at least 2 inputs");
          }
          inputShape = inputShape;
          var allNoneShape = true;
          try {
            for (var inputShape_3 = __values(inputShape), inputShape_3_1 = inputShape_3.next(); !inputShape_3_1.done; inputShape_3_1 = inputShape_3.next()) {
              var shape = inputShape_3_1.value;
              if (shape != null) {
                allNoneShape = false;
                break;
              }
            }
          } catch (e_5_1) {
            e_5 = { error: e_5_1 };
          } finally {
            try {
              if (inputShape_3_1 && !inputShape_3_1.done && (_a2 = inputShape_3.return)) _a2.call(inputShape_3);
            } finally {
              if (e_5) throw e_5.error;
            }
          }
          if (allNoneShape) {
            return;
          }
          var shapeSet = [];
          for (var i = 0; i < inputShape.length; ++i) {
            var shapeWithoutConcatAxis = inputShape[i].slice();
            shapeWithoutConcatAxis.splice(this.axis, 1);
            var exists = false;
            try {
              for (var shapeSet_1 = (e_6 = void 0, __values(shapeSet)), shapeSet_1_1 = shapeSet_1.next(); !shapeSet_1_1.done; shapeSet_1_1 = shapeSet_1.next()) {
                var shape = shapeSet_1_1.value;
                if (tfc.util.arraysEqual(shape, shapeWithoutConcatAxis)) {
                  exists = true;
                  break;
                }
              }
            } catch (e_6_1) {
              e_6 = { error: e_6_1 };
            } finally {
              try {
                if (shapeSet_1_1 && !shapeSet_1_1.done && (_b = shapeSet_1.return)) _b.call(shapeSet_1);
              } finally {
                if (e_6) throw e_6.error;
              }
            }
            if (!exists) {
              shapeSet.push(shapeWithoutConcatAxis);
            }
          }
          if (shapeSet.length > 1) {
            throw new ValueError("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: " + JSON.stringify(inputShape));
          }
        };
        Concatenate2.prototype.mergeFunction = function(inputs) {
          var _this = this;
          return tfc.tidy(function() {
            return concatenate$1(inputs, _this.axis);
          });
        };
        Concatenate2.prototype.computeOutputShape = function(inputShape) {
          var e_7, _a2;
          if (!(Array.isArray(inputShape) && Array.isArray(inputShape[0]))) {
            throw new ValueError("A `Concatenate` layer should be called on a list of inputs.");
          }
          var inputShapes = inputShape;
          var outputShape = inputShapes[0].slice();
          var axis = this.axis < 0 ? outputShape.length + this.axis : this.axis;
          try {
            for (var _b = __values(inputShapes.slice(1)), _c = _b.next(); !_c.done; _c = _b.next()) {
              var shape = _c.value;
              if (outputShape[axis] == null || shape[axis] == null) {
                outputShape[axis] = null;
                break;
              }
              outputShape[axis] += shape[axis];
            }
          } catch (e_7_1) {
            e_7 = { error: e_7_1 };
          } finally {
            try {
              if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
            } finally {
              if (e_7) throw e_7.error;
            }
          }
          return outputShape;
        };
        Concatenate2.prototype.computeMask = function(inputs, mask) {
          var _this = this;
          if (mask == null) {
            return null;
          }
          if (!Array.isArray(mask)) {
            throw new ValueError("`mask` should be an array for Concatenate");
          }
          if (!Array.isArray(inputs)) {
            throw new ValueError("`inputs` should be an array for Concatenate");
          }
          if (mask.length !== inputs.length) {
            throw new ValueError("Mismatch in the length of mask (".concat(mask.length, ") ") + "and the legnth of inputs (".concat(inputs.length, ")"));
          }
          return tfc__namespace.tidy(function() {
            var allNullMasks = true;
            mask.forEach(function(m) {
              if (m != null) {
                allNullMasks = false;
                return;
              }
            });
            if (allNullMasks) {
              return null;
            }
            var outputMasks = [];
            for (var i = 0; i < inputs.length; ++i) {
              if (mask[i] == null) {
                outputMasks.push(tfc__namespace.cast(tfc__namespace.onesLike(inputs[i]), "bool"));
              } else if (mask[i].rank < inputs[i].rank) {
                outputMasks.push(tfc__namespace.expandDims(mask[i], -1));
              } else {
                outputMasks.push(mask[i]);
              }
            }
            var concatenatedMasks = tfc__namespace.concat(outputMasks, _this.axis);
            return tfc__namespace.all(concatenatedMasks, -1, false);
          });
        };
        Concatenate2.prototype.getConfig = function() {
          var config = {
            "axis": this.axis
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return Concatenate2;
      }(Merge)
    );
    Concatenate.className = "Concatenate";
    tfc.serialization.registerClass(Concatenate);
    function interpretAxis(axis, dim) {
      while (axis < 0) {
        axis += dim;
      }
      return axis;
    }
    function batchDot(x, y, axes) {
      if (x.shape.length > 3 || y.shape.length > 3) {
        throw new NotImplementedError("batchDot is not implemented for tensors of 4D or higher rank yet");
      }
      tfc__namespace.util.assert(x.shape.length >= 2, function() {
        return "batchDot requires the rank of x to be >= 2, " + "but got ".concat(x.shape.length);
      });
      tfc__namespace.util.assert(x.shape.length >= 2, function() {
        return "batchDot requires the rank of y to be >= 2, " + "but got ".concat(y.shape.length);
      });
      if (typeof axes === "number") {
        axes = [axes, axes];
      }
      if (x.dtype === "complex64" || y.dtype === "complex64") {
        throw new NotImplementedError("batchDot is not implemented for complex64-type Tensors yet.");
      }
      var xNDim = x.shape.length;
      var yNDim = y.shape.length;
      if (axes == null) {
        axes = [xNDim - 1, yNDim - 2];
      }
      var axesArray = axes;
      return tfc__namespace.tidy(function() {
        var diff;
        if (xNDim > yNDim) {
          diff = xNDim - yNDim;
          var diffShape = [];
          for (var i = 0; i < diff; ++i) {
            diffShape.push(1);
          }
          y = tfc__namespace.reshape(y, y.shape.concat(diffShape));
        } else if (yNDim > xNDim) {
          diff = yNDim - xNDim;
          var diffShape = [];
          for (var i = 0; i < diff; ++i) {
            diffShape.push(1);
          }
          x = tfc__namespace.reshape(x, x.shape.concat(diffShape));
        } else {
          diff = 0;
        }
        var out;
        if (x.shape.length === 2 && y.shape.length === 2) {
          if (axesArray[0] === axesArray[1]) {
            out = tfc__namespace.sum(tfc__namespace.mul(x, y), axesArray[0]);
          } else {
            out = tfc__namespace.sum(tfc__namespace.mul(tfc__namespace.transpose(x, [1, 0]), y), axesArray[1]);
          }
        } else {
          var adjX = axesArray[0] !== x.shape.length - 1;
          var adjY = axesArray[1] === y.shape.length - 1;
          out = tfc__namespace.matMul(x, y, adjX, adjY);
        }
        if (diff > 0) {
          var idx = void 0;
          if (xNDim > yNDim) {
            idx = xNDim + yNDim - 3;
          } else {
            idx = xNDim - 1;
          }
          var squeezeAxes = [];
          for (var i = idx; i < idx + diff; ++i) {
            squeezeAxes.push(i);
          }
          out = tfc__namespace.squeeze(out, squeezeAxes);
        }
        if (out.shape.length === 1) {
          out = tfc__namespace.expandDims(out, 1);
        }
        return out;
      });
    }
    var Dot = (
      /** @class */
      function(_super) {
        __extends(Dot2, _super);
        function Dot2(args) {
          var _this = _super.call(this, args) || this;
          _this.axes = args.axes;
          _this.normalize = args.normalize == null ? false : args.normalize;
          _this.supportsMasking = true;
          _this.reshapeRequired = false;
          return _this;
        }
        Dot2.prototype.build = function(inputShape) {
          tfc__namespace.util.assert(Array.isArray(inputShape) && inputShape.length === 2 && Array.isArray(inputShape[0]) && Array.isArray(inputShape[1]), function() {
            return "A `Dot` layer should be called on a list of exactly 2 inputs.";
          });
          var shape1 = inputShape[0];
          var shape2 = inputShape[1];
          if (shape1.length > 3 || shape2.length > 3) {
            throw new NotImplementedError("Dot layer does not support tensors of 4D or higher rank yet.");
          }
          var axes = this.interpretAxes(shape1, shape2);
          if (shape1[axes[0]] !== shape2[axes[1]]) {
            throw new ValueError("Dimension incompatibility: " + "".concat(shape1[axes[0]], " !== ").concat(shape2[axes[1]]));
          }
        };
        Dot2.prototype.mergeFunction = function(inputs) {
          if (inputs.length !== 2) {
            throw new ValueError("A `Dot` layer must be called on exactly 2 inputs, " + "but received ".concat(inputs.length, " input(s)."));
          }
          var x1 = inputs[0];
          var x2 = inputs[1];
          var axes;
          if (!Array.isArray(this.axes)) {
            axes = [
              interpretAxis(this.axes, x1.shape.length),
              interpretAxis(this.axes, x2.shape.length)
            ];
          } else {
            axes = this.axes.map(function(axis, i) {
              return interpretAxis(axis, inputs[i].shape.length);
            });
          }
          if (this.normalize) {
            x1 = l2Normalize(x1, axes[0]);
            x2 = l2Normalize(x2, axes[1]);
          }
          return batchDot(x1, x2, axes);
        };
        Dot2.prototype.interpretAxes = function(shape1, shape2) {
          var axes;
          if (!Array.isArray(this.axes)) {
            axes = [
              interpretAxis(this.axes, shape1.length),
              interpretAxis(this.axes, shape2.length)
            ];
          } else {
            axes = this.axes;
          }
          return axes;
        };
        Dot2.prototype.computeOutputShape = function(inputShape) {
          tfc__namespace.util.assert(Array.isArray(inputShape) && inputShape.length === 2 && Array.isArray(inputShape[0]) && Array.isArray(inputShape[1]), function() {
            return "A `Dot` layer should be called on a list of exactly 2 inputs.";
          });
          var shape1 = inputShape[0].slice();
          var shape2 = inputShape[1].slice();
          if (shape1.length > 3 || shape2.length > 3) {
            throw new NotImplementedError("Dot layer does not support tensors of 4D or higher rank yet.");
          }
          var axes = this.interpretAxes(shape1, shape2);
          shape1.splice(axes[0], 1);
          shape2.splice(axes[1], 1);
          shape2.splice(0, 1);
          var outputShape = shape1.concat(shape2);
          if (outputShape.length === 1) {
            outputShape.push(1);
          }
          return outputShape;
        };
        Dot2.prototype.computeMask = function(inputs, mask) {
          return null;
        };
        Dot2.prototype.getConfig = function() {
          var config = {
            "axes": this.axes,
            "normalize": this.normalize
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return Dot2;
      }(Merge)
    );
    Dot.className = "Dot";
    tfc.serialization.registerClass(Dot);
    var GaussianNoise = (
      /** @class */
      function(_super) {
        __extends(GaussianNoise2, _super);
        function GaussianNoise2(args) {
          var _this = _super.call(this, args) || this;
          _this.supportsMasking = true;
          _this.stddev = args.stddev;
          return _this;
        }
        GaussianNoise2.prototype.computeOutputShape = function(inputShape) {
          return inputShape;
        };
        GaussianNoise2.prototype.getConfig = function() {
          var baseConfig = _super.prototype.getConfig.call(this);
          var config = { stddev: this.stddev };
          Object.assign(config, baseConfig);
          return config;
        };
        GaussianNoise2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            _this.invokeCallHook(inputs, kwargs);
            var input2 = getExactlyOneTensor(inputs);
            var noised = function() {
              return tfc.add(randomNormal$1(input2.shape, 0, _this.stddev), input2);
            };
            var output = inTrainPhase(noised, function() {
              return input2;
            }, kwargs["training"] || false);
            return output;
          });
        };
        return GaussianNoise2;
      }(Layer)
    );
    GaussianNoise.className = "GaussianNoise";
    tfc.serialization.registerClass(GaussianNoise);
    var GaussianDropout = (
      /** @class */
      function(_super) {
        __extends(GaussianDropout2, _super);
        function GaussianDropout2(args) {
          var _this = _super.call(this, args) || this;
          _this.supportsMasking = true;
          _this.rate = args.rate;
          return _this;
        }
        GaussianDropout2.prototype.computeOutputShape = function(inputShape) {
          return inputShape;
        };
        GaussianDropout2.prototype.getConfig = function() {
          var baseConfig = _super.prototype.getConfig.call(this);
          var config = { rate: this.rate };
          Object.assign(config, baseConfig);
          return config;
        };
        GaussianDropout2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            _this.invokeCallHook(inputs, kwargs);
            var input2 = getExactlyOneTensor(inputs);
            if (_this.rate > 0 && _this.rate < 1) {
              var noised = function() {
                var stddev = Math.sqrt(_this.rate / (1 - _this.rate));
                return tfc.mul(input2, randomNormal$1(input2.shape, 1, stddev));
              };
              return inTrainPhase(noised, function() {
                return input2;
              }, kwargs["training"] || false);
            }
            return input2;
          });
        };
        return GaussianDropout2;
      }(Layer)
    );
    GaussianDropout.className = "GaussianDropout";
    tfc.serialization.registerClass(GaussianDropout);
    var AlphaDropout = (
      /** @class */
      function(_super) {
        __extends(AlphaDropout2, _super);
        function AlphaDropout2(args) {
          var _this = _super.call(this, args) || this;
          _this.supportsMasking = true;
          _this.rate = args.rate;
          _this.noiseShape = args.noiseShape;
          return _this;
        }
        AlphaDropout2.prototype._getNoiseShape = function(inputs) {
          return this.noiseShape || getExactlyOneTensor(inputs).shape;
        };
        AlphaDropout2.prototype.computeOutputShape = function(inputShape) {
          return inputShape;
        };
        AlphaDropout2.prototype.getConfig = function() {
          var baseConfig = _super.prototype.getConfig.call(this);
          var config = { rate: this.rate };
          Object.assign(config, baseConfig);
          return config;
        };
        AlphaDropout2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            if (_this.rate < 1 && _this.rate > 0) {
              var noiseShape_1 = _this._getNoiseShape(inputs);
              var droppedInputs = function() {
                var input2 = getExactlyOneTensor(inputs);
                var alpha = 1.6732632423543772;
                var scale = 1.0507009873554805;
                var alphaP = -alpha * scale;
                var keptIdx = tfc.greaterEqual(tfc.randomUniform(noiseShape_1), _this.rate);
                keptIdx = cast$1(keptIdx, "float32");
                var a = Math.pow((1 - _this.rate) * (1 + _this.rate * Math.pow(alphaP, 2)), -0.5);
                var b = -a * alphaP * _this.rate;
                var x = tfc.add(tfc.mul(input2, keptIdx), tfc.mul(tfc.add(keptIdx, -1), alphaP));
                return tfc.add(tfc.mul(x, a), b);
              };
              return inTrainPhase(droppedInputs, function() {
                return getExactlyOneTensor(inputs);
              }, kwargs["training"] || false);
            }
            return inputs;
          });
        };
        return AlphaDropout2;
      }(Layer)
    );
    AlphaDropout.className = "AlphaDropout";
    tfc.serialization.registerClass(AlphaDropout);
    function batchNormalization$1(x, mean, variance, beta, gamma, epsilon2) {
      if (epsilon2 === void 0) {
        epsilon2 = 1e-3;
      }
      var out;
      if (x.rank === 2) {
        out = tfc__namespace.batchNorm2d(x, mean, variance, beta, gamma, epsilon2);
      } else if (x.rank === 3) {
        out = tfc__namespace.batchNorm3d(x, mean, variance, beta, gamma, epsilon2);
      } else if (x.rank === 4) {
        out = tfc__namespace.batchNorm4d(x, mean, variance, beta, gamma, epsilon2);
      } else {
        throw new NotImplementedError("batchNormalization is not implemented for array of rank ".concat(x.rank, " ") + "yet");
      }
      return out;
    }
    function regularNormalizeBatchInTraining(x, gamma, beta, reductionAxes, epsilon2) {
      if (epsilon2 === void 0) {
        epsilon2 = 1e-3;
      }
      return tfc.tidy(function() {
        var meanAndVariance = tfc__namespace.moments(x, reductionAxes);
        var mean = meanAndVariance.mean;
        var variance = meanAndVariance.variance;
        var normed = batchNormalization$1(x, mean, variance, beta, gamma, epsilon2);
        return [normed, mean, variance];
      });
    }
    function broadcastNormalizeBatchInTraining(x, gamma, beta, reductionAxes, epsilon2) {
      if (epsilon2 === void 0) {
        epsilon2 = 1e-3;
      }
      return tfc.tidy(function() {
        var e_12, _a2;
        var meanAndVariance = tfc__namespace.moments(x, reductionAxes);
        var mean = meanAndVariance.mean;
        var variance = meanAndVariance.variance;
        var targetShape = [];
        try {
          for (var _b = __values(range(0, x.rank)), _c = _b.next(); !_c.done; _c = _b.next()) {
            var axis = _c.value;
            if (reductionAxes.indexOf(axis) !== -1) {
              targetShape.push(1);
            } else {
              targetShape.push(x.shape[axis]);
            }
          }
        } catch (e_1_1) {
          e_12 = { error: e_1_1 };
        } finally {
          try {
            if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
          } finally {
            if (e_12) throw e_12.error;
          }
        }
        var broadcastMean = tfc.reshape(mean, targetShape);
        var broadcastVariance = tfc.reshape(variance, targetShape);
        var broadcastGamma = gamma == null ? null : tfc.reshape(gamma, targetShape);
        var broadcastBeta = beta == null ? null : tfc.reshape(beta, targetShape);
        var normed = batchNormalization$1(x, broadcastMean, broadcastVariance, broadcastBeta, broadcastGamma, epsilon2);
        return [normed, mean, variance];
      });
    }
    function normalizeBatchInTraining(x, gamma, beta, reductionAxes, epsilon2) {
      if (epsilon2 === void 0) {
        epsilon2 = 1e-3;
      }
      if (tfc.util.arraysEqual(reductionAxes.slice().sort(), range(0, x.rank - 1))) {
        return regularNormalizeBatchInTraining(x, gamma, beta, reductionAxes, epsilon2);
      } else {
        return broadcastNormalizeBatchInTraining(x, gamma, beta, reductionAxes, epsilon2);
      }
    }
    var BatchNormalization = (
      /** @class */
      function(_super) {
        __extends(BatchNormalization2, _super);
        function BatchNormalization2(args) {
          var _this = this;
          if (args == null) {
            args = {};
          }
          _this = _super.call(this, args) || this;
          _this.supportsMasking = true;
          _this.axis = args.axis == null ? -1 : args.axis;
          _this.momentum = args.momentum == null ? 0.99 : args.momentum;
          _this.epsilon = args.epsilon == null ? 1e-3 : args.epsilon;
          _this.center = args.center == null ? true : args.center;
          _this.scale = args.scale == null ? true : args.scale;
          _this.betaInitializer = getInitializer(args.betaInitializer || "zeros");
          _this.gammaInitializer = getInitializer(args.gammaInitializer || "ones");
          _this.movingMeanInitializer = getInitializer(args.movingMeanInitializer || "zeros");
          _this.movingVarianceInitializer = getInitializer(args.movingVarianceInitializer || "ones");
          _this.betaConstraint = getConstraint(args.betaConstraint);
          _this.gammaConstraint = getConstraint(args.gammaConstraint);
          _this.betaRegularizer = getRegularizer(args.betaRegularizer);
          _this.gammaRegularizer = getRegularizer(args.gammaRegularizer);
          return _this;
        }
        BatchNormalization2.prototype.build = function(inputShape) {
          var _a2;
          inputShape = getExactlyOneShape(inputShape);
          var axis = this.axis >= 0 ? this.axis : this.axis + inputShape.length;
          var dim = inputShape[axis];
          if (dim == null) {
            throw new ValueError("Axis ".concat(axis, " of input tensor should have a defined dimension but ") + "the layer received an input with shape " + "".concat(JSON.stringify(inputShape), "."));
          }
          this.inputSpec = [new InputSpec({ ndim: inputShape.length, axes: (_a2 = {}, _a2[axis] = dim, _a2) })];
          var shape = [dim];
          if (this.scale) {
            this.gamma = this.addWeight("gamma", shape, null, this.gammaInitializer, this.gammaRegularizer, true, this.gammaConstraint);
          }
          if (this.center) {
            this.beta = this.addWeight("beta", shape, null, this.betaInitializer, this.betaRegularizer, true, this.betaConstraint);
          }
          this.movingMean = this.addWeight("moving_mean", shape, null, this.movingMeanInitializer, null, false);
          this.movingVariance = this.addWeight("moving_variance", shape, null, this.movingVarianceInitializer, null, false);
          this.built = true;
        };
        BatchNormalization2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            var training = kwargs["training"] == null ? false : kwargs["training"];
            var input2 = getExactlyOneTensor(inputs);
            var inputShape = input2.shape;
            var ndim = inputShape.length;
            var reductionAxes = range(0, ndim);
            var axis = _this.axis >= 0 ? _this.axis : _this.axis + ndim;
            reductionAxes.splice(axis, 1);
            var broadcastShape = pyListRepeat(1, ndim);
            broadcastShape[axis] = inputShape[axis];
            var sortedReductionAxes = reductionAxes.slice();
            sortedReductionAxes.sort();
            var needsBroadcasting = !tfc.util.arraysEqual(sortedReductionAxes, range(0, ndim).slice(0, ndim - 1));
            var normalizeInference = function() {
              if (needsBroadcasting) {
                var broadcastMovingMean = tfc.reshape(_this.movingMean.read(), broadcastShape);
                var broadcastMovingVariance = tfc.reshape(_this.movingVariance.read(), broadcastShape);
                var broadcastBeta = _this.center ? tfc.reshape(_this.beta.read(), broadcastShape) : null;
                var broadcastGamma = _this.scale ? tfc.reshape(_this.gamma.read(), broadcastShape) : null;
                return batchNormalization$1(input2, broadcastMovingMean, broadcastMovingVariance, broadcastBeta, broadcastGamma, _this.epsilon);
              } else {
                return batchNormalization$1(input2, _this.movingMean.read(), _this.movingVariance.read(), _this.beta == null ? null : _this.beta.read(), _this.gamma == null ? null : _this.gamma.read(), _this.epsilon);
              }
            };
            if (!training) {
              return normalizeInference();
            }
            var _a2 = __read(normalizeBatchInTraining(input2, _this.gamma.read(), _this.beta.read(), reductionAxes, _this.epsilon), 3), normedTraining = _a2[0], mean = _a2[1], variance = _a2[2];
            var doMovingAverage = function(variable, value, momentum) {
              tfc__namespace.tidy(function() {
                var decay = 1 - momentum;
                var origValue = variable.read();
                var updateDelta = tfc__namespace.mul(tfc__namespace.sub(origValue, value), decay);
                variable.write(tfc__namespace.sub(origValue, updateDelta));
              });
            };
            var updateMovingMeanAndVariance = function() {
              doMovingAverage(_this.movingMean, mean, _this.momentum);
              doMovingAverage(_this.movingVariance, variance, _this.momentum);
            };
            updateMovingMeanAndVariance();
            return normedTraining;
          });
        };
        BatchNormalization2.prototype.getConfig = function() {
          var config = {
            axis: this.axis,
            momentum: this.momentum,
            epsilon: this.epsilon,
            center: this.center,
            scale: this.scale,
            betaInitializer: serializeInitializer(this.betaInitializer),
            gammaInitializer: serializeInitializer(this.gammaInitializer),
            movingMeanInitializer: serializeInitializer(this.movingMeanInitializer),
            movingVarianceInitializer: serializeInitializer(this.movingVarianceInitializer),
            betaRegularizer: serializeRegularizer(this.betaRegularizer),
            gammaRegularizer: serializeRegularizer(this.gammaRegularizer),
            betaConstraint: serializeConstraint(this.betaConstraint),
            gammaConstraint: serializeConstraint(this.gammaConstraint)
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return BatchNormalization2;
      }(Layer)
    );
    BatchNormalization.className = "BatchNormalization";
    tfc.serialization.registerClass(BatchNormalization);
    var LayerNormalization = (
      /** @class */
      function(_super) {
        __extends(LayerNormalization2, _super);
        function LayerNormalization2(args) {
          var e_2, _a2;
          var _this = this;
          if (args == null) {
            args = {};
          }
          _this = _super.call(this, args) || this;
          _this.axis = args.axis == null ? -1 : args.axis;
          if (typeof _this.axis === "number") {
            if (!Number.isInteger(_this.axis)) {
              throw new Error("Expected axis to be an integer, but received ".concat(_this.axis));
            }
          } else if (Array.isArray(_this.axis)) {
            try {
              for (var _b = __values(_this.axis), _c = _b.next(); !_c.done; _c = _b.next()) {
                var axis = _c.value;
                if (!Number.isInteger(axis)) {
                  throw new Error("Expected axis to be an array of integers, " + "but received ".concat(JSON.stringify(_this.axis)));
                }
              }
            } catch (e_2_1) {
              e_2 = { error: e_2_1 };
            } finally {
              try {
                if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
              } finally {
                if (e_2) throw e_2.error;
              }
            }
          } else {
            throw new Error("Expected axis to be an integer or an array of integers, " + "but received ".concat(JSON.stringify(_this.axis)));
          }
          _this.epsilon = args.epsilon == null ? 1e-3 : args.epsilon;
          _this.center = args.center == null ? true : args.center;
          _this.scale = args.scale == null ? true : args.scale;
          _this.betaInitializer = getInitializer(args.betaInitializer || "zeros");
          _this.gammaInitializer = getInitializer(args.gammaInitializer || "ones");
          _this.betaRegularizer = getRegularizer(args.betaRegularizer);
          _this.gammaRegularizer = getRegularizer(args.gammaRegularizer);
          _this.supportsMasking = true;
          return _this;
        }
        LayerNormalization2.prototype.build = function(inputShape) {
          var e_3, _a2;
          inputShape = getExactlyOneShape(inputShape);
          var nDims = inputShape.length;
          if (typeof this.axis === "number") {
            this.axis = [this.axis];
          }
          for (var i = 0; i < this.axis.length; ++i) {
            if (this.axis[i] < 0) {
              this.axis[i] += nDims;
            }
          }
          try {
            for (var _b = __values(this.axis), _c = _b.next(); !_c.done; _c = _b.next()) {
              var axis = _c.value;
              if (axis < 0 || axis >= nDims) {
                throw new Error("Invalid axis: ".concat(axis));
              }
            }
          } catch (e_3_1) {
            e_3 = { error: e_3_1 };
          } finally {
            try {
              if (_c && !_c.done && (_a2 = _b.return)) _a2.call(_b);
            } finally {
              if (e_3) throw e_3.error;
            }
          }
          if (this.axis.length !== unique(this.axis).length) {
            throw new Error("Found duplicate axes in: ".concat(this.axis));
          }
          var paramShape = this.axis.map(function(axis2) {
            return inputShape[axis2];
          });
          var trainable = true;
          if (this.scale) {
            this.gamma = this.addWeight("gamma", paramShape, "float32", this.gammaInitializer, this.gammaRegularizer, trainable);
          } else {
            this.gamma = null;
          }
          if (this.center) {
            this.beta = this.addWeight("beta", paramShape, "float32", this.betaInitializer, this.betaRegularizer, trainable);
          } else {
            this.beta = null;
          }
          this.built = true;
        };
        LayerNormalization2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          var input2 = getExactlyOneTensor(inputs);
          var inputShape = input2.shape;
          var nDims = inputShape.length;
          return tfc.tidy(function() {
            var e_4, _a2;
            var keepDims = true;
            var _b = tfc.moments(input2, _this.axis, keepDims), mean = _b.mean, variance = _b.variance;
            var broadcastShape = pyListRepeat(1, nDims);
            try {
              for (var _c = __values(_this.axis), _d = _c.next(); !_d.done; _d = _c.next()) {
                var dim = _d.value;
                broadcastShape[dim] = inputShape[dim];
              }
            } catch (e_4_1) {
              e_4 = { error: e_4_1 };
            } finally {
              try {
                if (_d && !_d.done && (_a2 = _c.return)) _a2.call(_c);
              } finally {
                if (e_4) throw e_4.error;
              }
            }
            var broadcast = function(v) {
              if (v != null && v.shape.length !== nDims) {
                return tfc__namespace.reshape(v, broadcastShape);
              } else {
                return v;
              }
            };
            var scale = _this.scale ? broadcast(_this.gamma.read()) : null;
            var offset = _this.center ? broadcast(_this.beta.read()) : null;
            var momentsTiling = [];
            var scaleOffsetTiling = [];
            for (var i = 0; i < nDims; ++i) {
              if (_this.axis.indexOf(i) !== -1) {
                momentsTiling.push(inputShape[i]);
                scaleOffsetTiling.push(1);
              } else {
                momentsTiling.push(1);
                scaleOffsetTiling.push(inputShape[i]);
              }
            }
            mean = tfc__namespace.tile(mean, momentsTiling);
            variance = tfc__namespace.tile(variance, momentsTiling);
            if (scale != null) {
              scale = tfc__namespace.tile(scale, scaleOffsetTiling);
            }
            if (offset != null) {
              offset = tfc__namespace.tile(offset, scaleOffsetTiling);
            }
            return batchNormalization$1(input2, mean, variance, offset, scale, _this.epsilon);
          });
        };
        LayerNormalization2.prototype.getConfig = function() {
          var config = {
            axis: this.axis,
            epsilon: this.epsilon,
            center: this.center,
            scale: this.scale,
            betaInitializer: serializeInitializer(this.betaInitializer),
            gammaInitializer: serializeInitializer(this.gammaInitializer),
            betaRegularizer: serializeRegularizer(this.betaRegularizer),
            gammaRegularizer: serializeRegularizer(this.gammaRegularizer)
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return LayerNormalization2;
      }(Layer)
    );
    LayerNormalization.className = "LayerNormalization";
    tfc.serialization.registerClass(LayerNormalization);
    function spatial2dPadding(x, padding, dataFormat) {
      return tfc.tidy(function() {
        if (x.rank !== 4) {
          throw new ValueError("temporalPadding expects input tensor to be 4-D, but received a " + "".concat(x.rank, "-D tensor."));
        }
        if (padding == null) {
          padding = [[1, 1], [1, 1]];
        }
        if (padding.length !== 2 || padding[0].length !== 2 || padding[1].length !== 2) {
          throw new ValueError("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");
        }
        if (dataFormat == null) {
          dataFormat = imageDataFormat();
        }
        if (dataFormat !== "channelsLast" && dataFormat !== "channelsFirst") {
          throw new ValueError("Unknown data format: ".concat(dataFormat, ". ") + "Supported data formats are 'channelsLast' and 'channelsFirst.");
        }
        var pattern;
        if (dataFormat === "channelsFirst") {
          pattern = [[0, 0], [0, 0], padding[0], padding[1]];
        } else {
          pattern = [[0, 0], padding[0], padding[1], [0, 0]];
        }
        return tfc__namespace.pad(x, pattern);
      });
    }
    var ZeroPadding2D = (
      /** @class */
      function(_super) {
        __extends(ZeroPadding2D2, _super);
        function ZeroPadding2D2(args) {
          var _this = this;
          if (args == null) {
            args = {};
          }
          _this = _super.call(this, args) || this;
          _this.dataFormat = args.dataFormat == null ? imageDataFormat() : args.dataFormat;
          if (args.padding == null) {
            _this.padding = [[1, 1], [1, 1]];
          } else if (typeof args.padding === "number") {
            _this.padding = [[args.padding, args.padding], [args.padding, args.padding]];
          } else {
            args.padding = args.padding;
            if (args.padding.length !== 2) {
              throw new ValueError("ZeroPadding2D expects padding to be a length-2 array, but " + "received a length-".concat(args.padding.length, " array."));
            }
            var heightPadding = void 0;
            var widthPadding = void 0;
            if (typeof args.padding[0] === "number") {
              heightPadding = [args.padding[0], args.padding[0]];
              widthPadding = [args.padding[1], args.padding[1]];
            } else {
              args.padding = args.padding;
              if (args.padding[0].length !== 2) {
                throw new ValueError("ZeroPadding2D expects height padding to be a length-2 array, " + "but received a length-".concat(args.padding[0].length, " array."));
              }
              heightPadding = args.padding[0];
              if (args.padding[1].length !== 2) {
                throw new ValueError("ZeroPadding2D expects width padding to be a length-2 array, " + "but received a length-".concat(args.padding[1].length, " array."));
              }
              widthPadding = args.padding[1];
            }
            _this.padding = [heightPadding, widthPadding];
          }
          _this.inputSpec = [new InputSpec({ ndim: 4 })];
          return _this;
        }
        ZeroPadding2D2.prototype.computeOutputShape = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          var rows;
          var cols;
          if (this.dataFormat === "channelsFirst") {
            if (inputShape[2] != null && inputShape[2] >= 0) {
              rows = inputShape[2] + this.padding[0][0] + this.padding[0][1];
            } else {
              rows = null;
            }
            if (inputShape[3] != null && inputShape[3] >= 0) {
              cols = inputShape[3] + this.padding[1][0] + this.padding[1][1];
            } else {
              cols = null;
            }
            return [inputShape[0], inputShape[1], rows, cols];
          } else {
            if (inputShape[1] != null && inputShape[1] >= 0) {
              rows = inputShape[1] + this.padding[0][0] + this.padding[0][1];
            } else {
              rows = null;
            }
            if (inputShape[2] != null && inputShape[2] >= 0) {
              cols = inputShape[2] + this.padding[1][0] + this.padding[1][1];
            } else {
              cols = null;
            }
            return [inputShape[0], rows, cols, inputShape[3]];
          }
        };
        ZeroPadding2D2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            return spatial2dPadding(getExactlyOneTensor(inputs), _this.padding, _this.dataFormat);
          });
        };
        ZeroPadding2D2.prototype.getConfig = function() {
          var config = {
            padding: this.padding,
            dataFormat: this.dataFormat
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return ZeroPadding2D2;
      }(Layer)
    );
    ZeroPadding2D.className = "ZeroPadding2D";
    tfc.serialization.registerClass(ZeroPadding2D);
    function pool2d(x, poolSize, strides, padding, dataFormat, poolMode) {
      return tfc.tidy(function() {
        checkDataFormat(dataFormat);
        checkPoolMode(poolMode);
        checkPaddingMode(padding);
        if (strides == null) {
          strides = [1, 1];
        }
        if (padding == null) {
          padding = "valid";
        }
        if (dataFormat == null) {
          dataFormat = imageDataFormat();
        }
        if (poolMode == null) {
          poolMode = "max";
        }
        x = preprocessConv2DInput(x, dataFormat);
        var y;
        var paddingString = padding === "same" ? "same" : "valid";
        if (poolMode === "max") {
          y = tfc__namespace.maxPool(x, poolSize, strides, paddingString);
        } else {
          y = tfc__namespace.avgPool(
            // TODO(cais): Rank check?
            x,
            poolSize,
            strides,
            paddingString
          );
        }
        if (dataFormat === "channelsFirst") {
          y = tfc__namespace.transpose(y, [0, 3, 1, 2]);
        }
        return y;
      });
    }
    function pool3d(x, poolSize, strides, padding, dataFormat, poolMode) {
      return tfc.tidy(function() {
        checkDataFormat(dataFormat);
        checkPoolMode(poolMode);
        checkPaddingMode(padding);
        if (strides == null) {
          strides = [1, 1, 1];
        }
        if (padding == null) {
          padding = "valid";
        }
        if (dataFormat == null) {
          dataFormat = imageDataFormat();
        }
        if (poolMode == null) {
          poolMode = "max";
        }
        x = preprocessConv3DInput(x, dataFormat);
        var y;
        var paddingString = padding === "same" ? "same" : "valid";
        if (poolMode === "max") {
          y = tfc__namespace.maxPool3d(x, poolSize, strides, paddingString);
        } else {
          y = tfc__namespace.avgPool3d(x, poolSize, strides, paddingString);
        }
        if (dataFormat === "channelsFirst") {
          y = tfc__namespace.transpose(y, [0, 4, 1, 2, 3]);
        }
        return y;
      });
    }
    var Pooling1D = (
      /** @class */
      function(_super) {
        __extends(Pooling1D2, _super);
        function Pooling1D2(args) {
          var _this = this;
          if (args.poolSize == null) {
            args.poolSize = 2;
          }
          _this = _super.call(this, args) || this;
          if (typeof args.poolSize === "number") {
            _this.poolSize = [args.poolSize];
          } else if (Array.isArray(args.poolSize) && args.poolSize.length === 1 && typeof args.poolSize[0] === "number") {
            _this.poolSize = args.poolSize;
          } else {
            throw new ValueError("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received " + "".concat(JSON.stringify(args.poolSize)));
          }
          assertPositiveInteger(_this.poolSize, "poolSize");
          if (args.strides == null) {
            _this.strides = _this.poolSize;
          } else {
            if (typeof args.strides === "number") {
              _this.strides = [args.strides];
            } else if (Array.isArray(args.strides) && args.strides.length === 1 && typeof args.strides[0] === "number") {
              _this.strides = args.strides;
            } else {
              throw new ValueError("strides for 1D convolutional layer must be a number or an Array of a single number, but received " + "".concat(JSON.stringify(args.strides)));
            }
          }
          assertPositiveInteger(_this.strides, "strides");
          _this.padding = args.padding == null ? "valid" : args.padding;
          checkPaddingMode(_this.padding);
          _this.inputSpec = [new InputSpec({ ndim: 3 })];
          return _this;
        }
        Pooling1D2.prototype.computeOutputShape = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          var length = convOutputLength(inputShape[1], this.poolSize[0], this.padding, this.strides[0]);
          return [inputShape[0], length, inputShape[2]];
        };
        Pooling1D2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            _this.invokeCallHook(inputs, kwargs);
            inputs = expandDims$1(getExactlyOneTensor(inputs), 2);
            var output = _this.poolingFunction(getExactlyOneTensor(inputs), [_this.poolSize[0], 1], [_this.strides[0], 1], _this.padding, "channelsLast");
            return tfc__namespace.squeeze(output, [2]);
          });
        };
        Pooling1D2.prototype.getConfig = function() {
          var config = {
            poolSize: this.poolSize,
            padding: this.padding,
            strides: this.strides
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return Pooling1D2;
      }(Layer)
    );
    var MaxPooling1D = (
      /** @class */
      function(_super) {
        __extends(MaxPooling1D2, _super);
        function MaxPooling1D2(args) {
          return _super.call(this, args) || this;
        }
        MaxPooling1D2.prototype.poolingFunction = function(inputs, poolSize, strides, padding, dataFormat) {
          checkDataFormat(dataFormat);
          checkPaddingMode(padding);
          return pool2d(inputs, poolSize, strides, padding, dataFormat, "max");
        };
        return MaxPooling1D2;
      }(Pooling1D)
    );
    MaxPooling1D.className = "MaxPooling1D";
    tfc.serialization.registerClass(MaxPooling1D);
    var AveragePooling1D = (
      /** @class */
      function(_super) {
        __extends(AveragePooling1D2, _super);
        function AveragePooling1D2(args) {
          return _super.call(this, args) || this;
        }
        AveragePooling1D2.prototype.poolingFunction = function(inputs, poolSize, strides, padding, dataFormat) {
          checkDataFormat(dataFormat);
          checkPaddingMode(padding);
          return pool2d(inputs, poolSize, strides, padding, dataFormat, "avg");
        };
        return AveragePooling1D2;
      }(Pooling1D)
    );
    AveragePooling1D.className = "AveragePooling1D";
    tfc.serialization.registerClass(AveragePooling1D);
    var Pooling2D = (
      /** @class */
      function(_super) {
        __extends(Pooling2D2, _super);
        function Pooling2D2(args) {
          var _this = this;
          if (args.poolSize == null) {
            args.poolSize = [2, 2];
          }
          _this = _super.call(this, args) || this;
          _this.poolSize = Array.isArray(args.poolSize) ? args.poolSize : [args.poolSize, args.poolSize];
          if (args.strides == null) {
            _this.strides = _this.poolSize;
          } else if (Array.isArray(args.strides)) {
            if (args.strides.length !== 2) {
              throw new ValueError("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length " + "".concat(args.strides.length, "."));
            }
            _this.strides = args.strides;
          } else {
            _this.strides = [args.strides, args.strides];
          }
          assertPositiveInteger(_this.poolSize, "poolSize");
          assertPositiveInteger(_this.strides, "strides");
          _this.padding = args.padding == null ? "valid" : args.padding;
          _this.dataFormat = args.dataFormat == null ? "channelsLast" : args.dataFormat;
          checkDataFormat(_this.dataFormat);
          checkPaddingMode(_this.padding);
          _this.inputSpec = [new InputSpec({ ndim: 4 })];
          return _this;
        }
        Pooling2D2.prototype.computeOutputShape = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          var rows = this.dataFormat === "channelsFirst" ? inputShape[2] : inputShape[1];
          var cols = this.dataFormat === "channelsFirst" ? inputShape[3] : inputShape[2];
          rows = convOutputLength(rows, this.poolSize[0], this.padding, this.strides[0]);
          cols = convOutputLength(cols, this.poolSize[1], this.padding, this.strides[1]);
          if (this.dataFormat === "channelsFirst") {
            return [inputShape[0], inputShape[1], rows, cols];
          } else {
            return [inputShape[0], rows, cols, inputShape[3]];
          }
        };
        Pooling2D2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            _this.invokeCallHook(inputs, kwargs);
            return _this.poolingFunction(getExactlyOneTensor(inputs), _this.poolSize, _this.strides, _this.padding, _this.dataFormat);
          });
        };
        Pooling2D2.prototype.getConfig = function() {
          var config = {
            poolSize: this.poolSize,
            padding: this.padding,
            strides: this.strides,
            dataFormat: this.dataFormat
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return Pooling2D2;
      }(Layer)
    );
    var MaxPooling2D = (
      /** @class */
      function(_super) {
        __extends(MaxPooling2D2, _super);
        function MaxPooling2D2(args) {
          return _super.call(this, args) || this;
        }
        MaxPooling2D2.prototype.poolingFunction = function(inputs, poolSize, strides, padding, dataFormat) {
          checkDataFormat(dataFormat);
          checkPaddingMode(padding);
          return pool2d(inputs, poolSize, strides, padding, dataFormat, "max");
        };
        return MaxPooling2D2;
      }(Pooling2D)
    );
    MaxPooling2D.className = "MaxPooling2D";
    tfc.serialization.registerClass(MaxPooling2D);
    var AveragePooling2D = (
      /** @class */
      function(_super) {
        __extends(AveragePooling2D2, _super);
        function AveragePooling2D2(args) {
          return _super.call(this, args) || this;
        }
        AveragePooling2D2.prototype.poolingFunction = function(inputs, poolSize, strides, padding, dataFormat) {
          checkDataFormat(dataFormat);
          checkPaddingMode(padding);
          return pool2d(inputs, poolSize, strides, padding, dataFormat, "avg");
        };
        return AveragePooling2D2;
      }(Pooling2D)
    );
    AveragePooling2D.className = "AveragePooling2D";
    tfc.serialization.registerClass(AveragePooling2D);
    var Pooling3D = (
      /** @class */
      function(_super) {
        __extends(Pooling3D2, _super);
        function Pooling3D2(args) {
          var _this = this;
          if (args.poolSize == null) {
            args.poolSize = [2, 2, 2];
          }
          _this = _super.call(this, args) || this;
          _this.poolSize = Array.isArray(args.poolSize) ? args.poolSize : [args.poolSize, args.poolSize, args.poolSize];
          if (args.strides == null) {
            _this.strides = _this.poolSize;
          } else if (Array.isArray(args.strides)) {
            if (args.strides.length !== 3) {
              throw new ValueError("If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length " + "".concat(args.strides.length, "."));
            }
            _this.strides = args.strides;
          } else {
            _this.strides = [args.strides, args.strides, args.strides];
          }
          assertPositiveInteger(_this.poolSize, "poolSize");
          assertPositiveInteger(_this.strides, "strides");
          _this.padding = args.padding == null ? "valid" : args.padding;
          _this.dataFormat = args.dataFormat == null ? "channelsLast" : args.dataFormat;
          checkDataFormat(_this.dataFormat);
          checkPaddingMode(_this.padding);
          _this.inputSpec = [new InputSpec({ ndim: 5 })];
          return _this;
        }
        Pooling3D2.prototype.computeOutputShape = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          var depths = this.dataFormat === "channelsFirst" ? inputShape[2] : inputShape[1];
          var rows = this.dataFormat === "channelsFirst" ? inputShape[3] : inputShape[2];
          var cols = this.dataFormat === "channelsFirst" ? inputShape[4] : inputShape[3];
          depths = convOutputLength(depths, this.poolSize[0], this.padding, this.strides[0]);
          rows = convOutputLength(rows, this.poolSize[1], this.padding, this.strides[1]);
          cols = convOutputLength(cols, this.poolSize[2], this.padding, this.strides[2]);
          if (this.dataFormat === "channelsFirst") {
            return [inputShape[0], inputShape[1], depths, rows, cols];
          } else {
            return [inputShape[0], depths, rows, cols, inputShape[4]];
          }
        };
        Pooling3D2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            _this.invokeCallHook(inputs, kwargs);
            return _this.poolingFunction(getExactlyOneTensor(inputs), _this.poolSize, _this.strides, _this.padding, _this.dataFormat);
          });
        };
        Pooling3D2.prototype.getConfig = function() {
          var config = {
            poolSize: this.poolSize,
            padding: this.padding,
            strides: this.strides,
            dataFormat: this.dataFormat
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return Pooling3D2;
      }(Layer)
    );
    var MaxPooling3D = (
      /** @class */
      function(_super) {
        __extends(MaxPooling3D2, _super);
        function MaxPooling3D2(args) {
          return _super.call(this, args) || this;
        }
        MaxPooling3D2.prototype.poolingFunction = function(inputs, poolSize, strides, padding, dataFormat) {
          checkDataFormat(dataFormat);
          checkPaddingMode(padding);
          return pool3d(inputs, poolSize, strides, padding, dataFormat, "max");
        };
        return MaxPooling3D2;
      }(Pooling3D)
    );
    MaxPooling3D.className = "MaxPooling3D";
    tfc.serialization.registerClass(MaxPooling3D);
    var AveragePooling3D = (
      /** @class */
      function(_super) {
        __extends(AveragePooling3D2, _super);
        function AveragePooling3D2(args) {
          return _super.call(this, args) || this;
        }
        AveragePooling3D2.prototype.poolingFunction = function(inputs, poolSize, strides, padding, dataFormat) {
          checkDataFormat(dataFormat);
          checkPaddingMode(padding);
          return pool3d(inputs, poolSize, strides, padding, dataFormat, "avg");
        };
        return AveragePooling3D2;
      }(Pooling3D)
    );
    AveragePooling3D.className = "AveragePooling3D";
    tfc.serialization.registerClass(AveragePooling3D);
    var GlobalPooling1D = (
      /** @class */
      function(_super) {
        __extends(GlobalPooling1D2, _super);
        function GlobalPooling1D2(args) {
          var _this = _super.call(this, args) || this;
          _this.inputSpec = [new InputSpec({ ndim: 3 })];
          return _this;
        }
        GlobalPooling1D2.prototype.computeOutputShape = function(inputShape) {
          return [inputShape[0], inputShape[2]];
        };
        GlobalPooling1D2.prototype.call = function(inputs, kwargs) {
          throw new NotImplementedError();
        };
        return GlobalPooling1D2;
      }(Layer)
    );
    var GlobalAveragePooling1D = (
      /** @class */
      function(_super) {
        __extends(GlobalAveragePooling1D2, _super);
        function GlobalAveragePooling1D2(args) {
          return _super.call(this, args || {}) || this;
        }
        GlobalAveragePooling1D2.prototype.call = function(inputs, kwargs) {
          return tfc.tidy(function() {
            var input2 = getExactlyOneTensor(inputs);
            return tfc__namespace.mean(input2, 1);
          });
        };
        return GlobalAveragePooling1D2;
      }(GlobalPooling1D)
    );
    GlobalAveragePooling1D.className = "GlobalAveragePooling1D";
    tfc.serialization.registerClass(GlobalAveragePooling1D);
    var GlobalMaxPooling1D = (
      /** @class */
      function(_super) {
        __extends(GlobalMaxPooling1D2, _super);
        function GlobalMaxPooling1D2(args) {
          return _super.call(this, args || {}) || this;
        }
        GlobalMaxPooling1D2.prototype.call = function(inputs, kwargs) {
          return tfc.tidy(function() {
            var input2 = getExactlyOneTensor(inputs);
            return tfc__namespace.max(input2, 1);
          });
        };
        return GlobalMaxPooling1D2;
      }(GlobalPooling1D)
    );
    GlobalMaxPooling1D.className = "GlobalMaxPooling1D";
    tfc.serialization.registerClass(GlobalMaxPooling1D);
    var GlobalPooling2D = (
      /** @class */
      function(_super) {
        __extends(GlobalPooling2D2, _super);
        function GlobalPooling2D2(args) {
          var _this = _super.call(this, args) || this;
          _this.dataFormat = args.dataFormat == null ? "channelsLast" : args.dataFormat;
          checkDataFormat(_this.dataFormat);
          _this.inputSpec = [new InputSpec({ ndim: 4 })];
          return _this;
        }
        GlobalPooling2D2.prototype.computeOutputShape = function(inputShape) {
          inputShape = inputShape;
          if (this.dataFormat === "channelsLast") {
            return [inputShape[0], inputShape[3]];
          } else {
            return [inputShape[0], inputShape[1]];
          }
        };
        GlobalPooling2D2.prototype.call = function(inputs, kwargs) {
          throw new NotImplementedError();
        };
        GlobalPooling2D2.prototype.getConfig = function() {
          var config = { dataFormat: this.dataFormat };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return GlobalPooling2D2;
      }(Layer)
    );
    var GlobalAveragePooling2D = (
      /** @class */
      function(_super) {
        __extends(GlobalAveragePooling2D2, _super);
        function GlobalAveragePooling2D2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        GlobalAveragePooling2D2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            var input2 = getExactlyOneTensor(inputs);
            if (_this.dataFormat === "channelsLast") {
              return tfc__namespace.mean(input2, [1, 2]);
            } else {
              return tfc__namespace.mean(input2, [2, 3]);
            }
          });
        };
        return GlobalAveragePooling2D2;
      }(GlobalPooling2D)
    );
    GlobalAveragePooling2D.className = "GlobalAveragePooling2D";
    tfc.serialization.registerClass(GlobalAveragePooling2D);
    var GlobalMaxPooling2D = (
      /** @class */
      function(_super) {
        __extends(GlobalMaxPooling2D2, _super);
        function GlobalMaxPooling2D2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        GlobalMaxPooling2D2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            var input2 = getExactlyOneTensor(inputs);
            if (_this.dataFormat === "channelsLast") {
              return tfc__namespace.max(input2, [1, 2]);
            } else {
              return tfc__namespace.max(input2, [2, 3]);
            }
          });
        };
        return GlobalMaxPooling2D2;
      }(GlobalPooling2D)
    );
    GlobalMaxPooling2D.className = "GlobalMaxPooling2D";
    tfc.serialization.registerClass(GlobalMaxPooling2D);
    var Wrapper = (
      /** @class */
      function(_super) {
        __extends(Wrapper2, _super);
        function Wrapper2(args) {
          var _this = (
            // Porting Note: In PyKeras, `self.layer` is set prior to the calling
            //   `super()`. But we can't do that here due to TypeScript's restriction.
            //   See: https://github.com/Microsoft/TypeScript/issues/8277
            //   As a result, we have to add checks in `get trainable()` and
            //   `set trainable()` below in order to prevent using `this.layer` when
            //   its value is `undefined`. The super constructor does use the getter
            //   and the setter of `this.layer`.
            _super.call(this, args) || this
          );
          _this.layer = args.layer;
          return _this;
        }
        Wrapper2.prototype.build = function(inputShape) {
          this.built = true;
        };
        Object.defineProperty(Wrapper2.prototype, "trainable", {
          // TODO(cais): Implement activityRegularizer getter.
          get: function() {
            if (this.layer != null) {
              return this.layer.trainable;
            } else {
              return false;
            }
          },
          set: function(value) {
            if (this.layer != null) {
              this.layer.trainable = value;
            }
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(Wrapper2.prototype, "trainableWeights", {
          get: function() {
            return this.layer.trainableWeights;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(Wrapper2.prototype, "nonTrainableWeights", {
          // TODO(cais): Implement setter for trainableWeights.
          get: function() {
            return this.layer.nonTrainableWeights;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(Wrapper2.prototype, "updates", {
          // TODO(cais): Implement setter for nonTrainableWeights.
          get: function() {
            return this.layer._updates;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(Wrapper2.prototype, "losses", {
          // TODO(cais): Implement getUpdatesFor().
          get: function() {
            return this.layer.losses;
          },
          enumerable: false,
          configurable: true
        });
        Wrapper2.prototype.getWeights = function() {
          return this.layer.getWeights();
        };
        Wrapper2.prototype.setWeights = function(weights) {
          this.layer.setWeights(weights);
        };
        Wrapper2.prototype.getConfig = function() {
          var config = {
            "layer": {
              "className": this.layer.getClassName(),
              "config": this.layer.getConfig()
            }
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        Wrapper2.prototype.setFastWeightInitDuringBuild = function(value) {
          _super.prototype.setFastWeightInitDuringBuild.call(this, value);
          if (this.layer != null) {
            this.layer.setFastWeightInitDuringBuild(value);
          }
        };
        Wrapper2.fromConfig = function(cls, config, customObjects) {
          if (customObjects === void 0) {
            customObjects = {};
          }
          var layerConfig = config["layer"];
          var layer = deserialize(layerConfig, customObjects);
          delete config["layer"];
          var newConfig = { layer };
          Object.assign(newConfig, config);
          return new cls(newConfig);
        };
        return Wrapper2;
      }(Layer)
    );
    var TimeDistributed = (
      /** @class */
      function(_super) {
        __extends(TimeDistributed2, _super);
        function TimeDistributed2(args) {
          var _this = _super.call(this, args) || this;
          _this.supportsMasking = true;
          return _this;
        }
        TimeDistributed2.prototype.build = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          if (inputShape.length < 3) {
            throw new ValueError("TimeDistributed layer expects an input shape >= 3D, but received " + "input shape ".concat(JSON.stringify(inputShape)));
          }
          this.inputSpec = [{ shape: inputShape }];
          var childInputShape = [inputShape[0]].concat(inputShape.slice(2));
          if (!this.layer.built) {
            this.layer.build(childInputShape);
            this.layer.built = true;
          }
          _super.prototype.build.call(this, inputShape);
        };
        TimeDistributed2.prototype.computeOutputShape = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          var childInputShape = [inputShape[0]].concat(inputShape.slice(2));
          var childOutputShape = this.layer.computeOutputShape(childInputShape);
          var timesteps = inputShape[1];
          return [childOutputShape[0], timesteps].concat(childOutputShape.slice(1));
        };
        TimeDistributed2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            inputs = getExactlyOneTensor(inputs);
            var step2 = function(inputs2, states) {
              var output = getExactlyOneTensor(_this.layer.call(inputs2, kwargs));
              return [output, []];
            };
            var rnnOutputs = rnn$1(
              step2,
              inputs,
              [],
              false,
              null,
              null,
              false,
              true
              /* needPerStepOutputs */
            );
            var y = rnnOutputs[1];
            return y;
          });
        };
        return TimeDistributed2;
      }(Wrapper)
    );
    TimeDistributed.className = "TimeDistributed";
    tfc.serialization.registerClass(TimeDistributed);
    function checkBidirectionalMergeMode(value) {
      checkStringTypeUnionValue(VALID_BIDIRECTIONAL_MERGE_MODES, "BidirectionalMergeMode", value);
    }
    var DEFAULT_BIDIRECTIONAL_MERGE_MODE = "concat";
    var Bidirectional = (
      /** @class */
      function(_super) {
        __extends(Bidirectional2, _super);
        function Bidirectional2(args) {
          var _this = _super.call(this, args) || this;
          var layerConfig = args.layer.getConfig();
          var forwDict = {};
          forwDict["className"] = args.layer.getClassName();
          forwDict["config"] = layerConfig;
          _this.forwardLayer = deserialize(forwDict);
          layerConfig["goBackwards"] = layerConfig["goBackwards"] === true ? false : true;
          var backDict = {};
          backDict["className"] = args.layer.getClassName();
          backDict["config"] = layerConfig;
          _this.backwardLayer = deserialize(backDict);
          _this.forwardLayer.name = "forward_" + _this.forwardLayer.name;
          _this.backwardLayer.name = "backward_" + _this.backwardLayer.name;
          _this.mergeMode = args.mergeMode === void 0 ? DEFAULT_BIDIRECTIONAL_MERGE_MODE : args.mergeMode;
          checkBidirectionalMergeMode(_this.mergeMode);
          if (args.weights) {
            throw new NotImplementedError("weights support is not implemented for Bidirectional layer yet.");
          }
          _this._stateful = args.layer.stateful;
          _this.returnSequences = args.layer.returnSequences;
          _this.returnState = args.layer.returnState;
          _this.supportsMasking = true;
          _this._trainable = true;
          _this.inputSpec = args.layer.inputSpec;
          _this.numConstants = null;
          return _this;
        }
        Object.defineProperty(Bidirectional2.prototype, "trainable", {
          get: function() {
            return this._trainable;
          },
          set: function(value) {
            this._trainable = value;
            if (this.forwardLayer != null) {
              this.forwardLayer.trainable = value;
            }
            if (this.backwardLayer != null) {
              this.backwardLayer.trainable = value;
            }
          },
          enumerable: false,
          configurable: true
        });
        Bidirectional2.prototype.getWeights = function() {
          return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights());
        };
        Bidirectional2.prototype.setWeights = function(weights) {
          var numWeights = weights.length;
          var numeightsOver2 = Math.floor(numWeights / 2);
          this.forwardLayer.setWeights(weights.slice(0, numeightsOver2));
          this.backwardLayer.setWeights(weights.slice(numeightsOver2));
        };
        Bidirectional2.prototype.computeOutputShape = function(inputShape) {
          var layerShapes = this.forwardLayer.computeOutputShape(inputShape);
          if (!(Array.isArray(layerShapes) && Array.isArray(layerShapes[0]))) {
            layerShapes = [layerShapes];
          }
          layerShapes = layerShapes;
          var outputShape;
          var outputShapes;
          var stateShape;
          if (this.returnState) {
            stateShape = layerShapes.slice(1);
            outputShape = layerShapes[0];
          } else {
            outputShape = layerShapes[0];
          }
          outputShape = outputShape;
          if (this.mergeMode === "concat") {
            outputShape[outputShape.length - 1] *= 2;
            outputShapes = [outputShape];
          } else if (this.mergeMode == null) {
            outputShapes = [outputShape, outputShape.slice()];
          } else {
            outputShapes = [outputShape];
          }
          if (this.returnState) {
            if (this.mergeMode == null) {
              return outputShapes.concat(stateShape).concat(stateShape.slice());
            }
            return [outputShape].concat(stateShape).concat(stateShape.slice());
          }
          return singletonOrArray(outputShapes);
        };
        Bidirectional2.prototype.apply = function(inputs, kwargs) {
          var e_12, _a2;
          var initialState = kwargs == null ? null : kwargs["initialState"];
          var constants = kwargs == null ? null : kwargs["constants"];
          if (kwargs == null) {
            kwargs = {};
          }
          var standardized = standardizeArgs(inputs, initialState, constants, this.numConstants);
          inputs = standardized.inputs;
          initialState = standardized.initialState;
          constants = standardized.constants;
          if (Array.isArray(inputs)) {
            initialState = inputs.slice(1);
            inputs = inputs[0];
          }
          if ((initialState == null || initialState.length === 0) && constants == null) {
            return _super.prototype.apply.call(this, inputs, kwargs);
          }
          var additionalInputs = [];
          var additionalSpecs = [];
          if (initialState != null) {
            var numStates = initialState.length;
            if (numStates % 2 > 0) {
              throw new ValueError("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");
            }
            kwargs["initialState"] = initialState;
            additionalInputs.push.apply(additionalInputs, __spreadArray([], __read(initialState), false));
            var stateSpecs = initialState.map(function(state) {
              return new InputSpec({ shape: state.shape });
            });
            this.forwardLayer.stateSpec = stateSpecs.slice(0, numStates / 2);
            this.backwardLayer.stateSpec = stateSpecs.slice(numStates / 2);
            additionalSpecs.push.apply(additionalSpecs, __spreadArray([], __read(stateSpecs), false));
          }
          if (constants != null) {
            throw new NotImplementedError("Support for constants in Bidirectional layers is not implemented yet.");
          }
          var isSymbolicTensor = additionalInputs[0] instanceof SymbolicTensor;
          try {
            for (var additionalInputs_1 = __values(additionalInputs), additionalInputs_1_1 = additionalInputs_1.next(); !additionalInputs_1_1.done; additionalInputs_1_1 = additionalInputs_1.next()) {
              var tensor = additionalInputs_1_1.value;
              if (tensor instanceof SymbolicTensor !== isSymbolicTensor) {
                throw new ValueError("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");
              }
            }
          } catch (e_1_1) {
            e_12 = { error: e_1_1 };
          } finally {
            try {
              if (additionalInputs_1_1 && !additionalInputs_1_1.done && (_a2 = additionalInputs_1.return)) _a2.call(additionalInputs_1);
            } finally {
              if (e_12) throw e_12.error;
            }
          }
          if (isSymbolicTensor) {
            var fullInput = [inputs].concat(additionalInputs);
            var fullInputSpec = this.inputSpec.concat(additionalSpecs);
            var originalInputSpec = this.inputSpec;
            this.inputSpec = fullInputSpec;
            var output = _super.prototype.apply.call(this, fullInput, kwargs);
            this.inputSpec = originalInputSpec;
            return output;
          } else {
            return _super.prototype.apply.call(this, inputs, kwargs);
          }
        };
        Bidirectional2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            var initialState = kwargs["initialState"];
            var y;
            var yRev;
            if (initialState == null) {
              y = _this.forwardLayer.call(inputs, kwargs);
              yRev = _this.backwardLayer.call(inputs, kwargs);
            } else {
              var forwardState = initialState.slice(0, initialState.length / 2);
              var backwardState = initialState.slice(initialState.length / 2);
              y = _this.forwardLayer.call(inputs, Object.assign(kwargs, { initialState: forwardState }));
              yRev = _this.backwardLayer.call(inputs, Object.assign(kwargs, { initialState: backwardState }));
            }
            var states;
            if (_this.returnState) {
              if (Array.isArray(y)) {
                states = y.slice(1).concat(yRev.slice(1));
              }
              y = y[0];
              yRev = yRev[0];
            }
            if (_this.returnSequences) {
              yRev = tfc__namespace.reverse(yRev, 1);
            }
            var output;
            if (_this.mergeMode === "concat") {
              output = concatenate$1([y, yRev]);
            } else if (_this.mergeMode === "sum") {
              output = tfc__namespace.add(y, yRev);
            } else if (_this.mergeMode === "ave") {
              output = tfc__namespace.mul(0.5, tfc__namespace.add(y, yRev));
            } else if (_this.mergeMode === "mul") {
              output = tfc__namespace.mul(y, yRev);
            } else if (_this.mergeMode == null) {
              output = [y, yRev];
            }
            if (_this.returnState) {
              if (_this.mergeMode == null) {
                return output.concat(states);
              }
              return [output].concat(states);
            }
            return output;
          });
        };
        Bidirectional2.prototype.resetStates = function(states) {
          this.forwardLayer.resetStates();
          this.backwardLayer.resetStates();
        };
        Bidirectional2.prototype.build = function(inputShape) {
          var _this = this;
          nameScope(this.forwardLayer.name, function() {
            _this.forwardLayer.build(inputShape);
          });
          nameScope(this.backwardLayer.name, function() {
            _this.backwardLayer.build(inputShape);
          });
          this.built = true;
        };
        Bidirectional2.prototype.computeMask = function(inputs, mask) {
          if (Array.isArray(mask)) {
            mask = mask[0];
          }
          var outputMask;
          if (this.returnSequences) {
            if (this.mergeMode == null) {
              outputMask = [mask, mask];
            } else {
              outputMask = mask;
            }
          } else {
            if (this.mergeMode == null) {
              outputMask = [null, null];
            } else {
              outputMask = null;
            }
          }
          if (this.returnState) {
            var states = this.forwardLayer.states;
            var stateMask = states.map(function(state) {
              return null;
            });
            if (Array.isArray(outputMask)) {
              return outputMask.concat(stateMask).concat(stateMask);
            } else {
              return [outputMask].concat(stateMask).concat(stateMask);
            }
          } else {
            return outputMask;
          }
        };
        Object.defineProperty(Bidirectional2.prototype, "trainableWeights", {
          get: function() {
            return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights);
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(Bidirectional2.prototype, "nonTrainableWeights", {
          get: function() {
            return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights);
          },
          enumerable: false,
          configurable: true
        });
        Bidirectional2.prototype.setFastWeightInitDuringBuild = function(value) {
          _super.prototype.setFastWeightInitDuringBuild.call(this, value);
          if (this.forwardLayer != null) {
            this.forwardLayer.setFastWeightInitDuringBuild(value);
          }
          if (this.backwardLayer != null) {
            this.backwardLayer.setFastWeightInitDuringBuild(value);
          }
        };
        Bidirectional2.prototype.getConfig = function() {
          var config = {
            "mergeMode": this.mergeMode
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        Bidirectional2.fromConfig = function(cls, config) {
          var rnnLayer = deserialize(config["layer"]);
          delete config["layer"];
          if (config["numConstants"] != null) {
            throw new NotImplementedError("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");
          }
          var newConfig = config;
          newConfig["layer"] = rnnLayer;
          return new cls(newConfig);
        };
        return Bidirectional2;
      }(Wrapper)
    );
    Bidirectional.className = "Bidirectional";
    tfc.serialization.registerClass(Bidirectional);
    var Rescaling = (
      /** @class */
      function(_super) {
        __extends(Rescaling2, _super);
        function Rescaling2(args) {
          var _this = _super.call(this, args) || this;
          _this.scale = args.scale;
          if (args.offset) {
            _this.offset = args.offset;
          } else {
            _this.offset = 0;
          }
          return _this;
        }
        Rescaling2.prototype.getConfig = function() {
          var config = {
            "scale": this.scale,
            "offset": this.offset
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        Rescaling2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            inputs = getExactlyOneTensor(inputs);
            if (inputs.dtype !== "float32") {
              inputs = cast$1(inputs, "float32");
            }
            return tfc.add(tfc.mul(inputs, _this.scale), _this.offset);
          });
        };
        return Rescaling2;
      }(Layer)
    );
    Rescaling.className = "Rescaling";
    tfc.serialization.registerClass(Rescaling);
    var resizeBilinear = tfc.image.resizeBilinear;
    var cropAndResize = tfc.image.cropAndResize;
    var CenterCrop = (
      /** @class */
      function(_super) {
        __extends(CenterCrop2, _super);
        function CenterCrop2(args) {
          var _this = _super.call(this, args) || this;
          _this.height = args.height;
          _this.width = args.width;
          return _this;
        }
        CenterCrop2.prototype.centerCrop = function(inputs, hBuffer, wBuffer, height, width, inputHeight, inputWidth, dtype) {
          return tfc.tidy(function() {
            var input2;
            var isRank3 = false;
            var top = hBuffer / inputHeight;
            var left = wBuffer / inputWidth;
            var bottom = (height + hBuffer) / inputHeight;
            var right = (width + wBuffer) / inputWidth;
            var bound = [top, left, bottom, right];
            var boxesArr = [];
            if (inputs.rank === 3) {
              isRank3 = true;
              input2 = tfc.stack([inputs]);
            } else {
              input2 = inputs;
            }
            for (var i = 0; i < input2.shape[0]; i++) {
              boxesArr.push(bound);
            }
            var boxes = tfc.tensor(boxesArr, [boxesArr.length, 4]);
            var boxInd = tfc.range(0, boxesArr.length, 1, "int32");
            var cropSize = [height, width];
            var cropped = cropAndResize(input2, boxes, boxInd, cropSize, "nearest");
            if (isRank3) {
              return cast$1(getExactlyOneTensor(tfc.unstack(cropped)), dtype);
            }
            return cast$1(cropped, dtype);
          });
        };
        CenterCrop2.prototype.upsize = function(inputs, height, width, dtype) {
          return tfc.tidy(function() {
            var outputs = resizeBilinear(inputs, [height, width]);
            return cast$1(outputs, dtype);
          });
        };
        CenterCrop2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            var rankedInputs = getExactlyOneTensor(inputs);
            var dtype = rankedInputs.dtype;
            var inputShape = rankedInputs.shape;
            var inputHeight = inputShape[inputShape.length - 3];
            var inputWidth = inputShape[inputShape.length - 2];
            var hBuffer = 0;
            if (inputHeight !== _this.height) {
              hBuffer = Math.floor((inputHeight - _this.height) / 2);
            }
            var wBuffer = 0;
            if (inputWidth !== _this.width) {
              wBuffer = Math.floor((inputWidth - _this.width) / 2);
              if (wBuffer === 0) {
                wBuffer = 1;
              }
            }
            if (hBuffer >= 0 && wBuffer >= 0) {
              return _this.centerCrop(rankedInputs, hBuffer, wBuffer, _this.height, _this.width, inputHeight, inputWidth, dtype);
            } else {
              return _this.upsize(inputs, _this.height, _this.width, dtype);
            }
          });
        };
        CenterCrop2.prototype.getConfig = function() {
          var config = {
            "height": this.height,
            "width": this.width
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        CenterCrop2.prototype.computeOutputShape = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          var hAxis = inputShape.length - 3;
          var wAxis = inputShape.length - 2;
          inputShape[hAxis] = this.height;
          inputShape[wAxis] = this.width;
          return inputShape;
        };
        return CenterCrop2;
      }(Layer)
    );
    CenterCrop.className = "CenterCrop";
    tfc.serialization.registerClass(CenterCrop);
    function encodeCategoricalInputs(inputs, outputMode, depth, weights) {
      var input2 = getExactlyOneTensor(inputs);
      if (input2.dtype !== "int32") {
        input2 = cast$1(input2, "int32");
      }
      if (outputMode === "int") {
        return input2;
      }
      var originalShape = input2.shape;
      if (input2.rank === 0) {
        input2 = tfc.expandDims(input2, -1);
      }
      if (outputMode === "oneHot") {
        if (input2.shape[input2.shape.length - 1] !== 1) {
          input2 = tfc.expandDims(input2, -1);
        }
      }
      if (input2.rank > 2) {
        throw new ValueError("When outputMode is not int, maximum output rank is 2" + " Received outputMode ".concat(outputMode, " and input shape ").concat(originalShape) + " which would result in output rank ".concat(input2.rank, "."));
      }
      var binaryOutput = ["multiHot", "oneHot"].includes(outputMode);
      var denseBincountInput = input2;
      var binCounts;
      if (typeof weights !== "undefined" && outputMode === "count") {
        binCounts = tfc.denseBincount(denseBincountInput, weights, depth, binaryOutput);
      } else {
        binCounts = tfc.denseBincount(denseBincountInput, [], depth, binaryOutput);
      }
      if (outputMode !== "tfIdf") {
        return binCounts;
      }
      if (weights) {
        return tfc.mul(binCounts, weights);
      } else {
        throw new ValueError("When outputMode is 'tfIdf', weights must be provided.");
      }
    }
    var CategoryEncoding = (
      /** @class */
      function(_super) {
        __extends(CategoryEncoding2, _super);
        function CategoryEncoding2(args) {
          var _this = _super.call(this, args) || this;
          _this.numTokens = args.numTokens;
          if (args.outputMode) {
            _this.outputMode = args.outputMode;
          } else {
            _this.outputMode = "multiHot";
          }
          return _this;
        }
        CategoryEncoding2.prototype.getConfig = function() {
          var config = {
            "numTokens": this.numTokens,
            "outputMode": this.outputMode
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        CategoryEncoding2.prototype.computeOutputShape = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          if (inputShape == null) {
            return [this.numTokens];
          }
          if (this.outputMode === "oneHot" && inputShape[inputShape.length - 1] !== 1) {
            inputShape.push(this.numTokens);
            return inputShape;
          }
          inputShape[inputShape.length - 1] = this.numTokens;
          return inputShape;
        };
        CategoryEncoding2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            inputs = getExactlyOneTensor(inputs);
            if (inputs.dtype !== "int32") {
              inputs = cast$1(inputs, "int32");
            }
            var countWeights;
            if (typeof kwargs["countWeights"] !== "undefined") {
              if (_this.outputMode !== "count") {
                throw new ValueError("countWeights is not used when outputMode !== count.\n              Received countWeights=".concat(kwargs["countWeights"]));
              }
              countWeights = getExactlyOneTensor(kwargs["countWeights"]);
            }
            var maxValue = tfc.max(inputs);
            var minValue = tfc.min(inputs);
            var greaterEqualMax = tfc.greater(_this.numTokens, maxValue).bufferSync().get(0);
            var greaterMin = tfc.greaterEqual(minValue, 0).bufferSync().get(0);
            if (!(greaterEqualMax && greaterMin)) {
              throw new ValueError("Input values must be between 0 < values <=" + " numTokens with numTokens=".concat(_this.numTokens));
            }
            return encodeCategoricalInputs(inputs, _this.outputMode, _this.numTokens, countWeights);
          });
        };
        return CategoryEncoding2;
      }(Layer)
    );
    CategoryEncoding.className = "CategoryEncoding";
    tfc.serialization.registerClass(CategoryEncoding);
    var INTERPOLATION_KEYS$1 = ["bilinear", "nearest"];
    var INTERPOLATION_METHODS$1 = new Set(INTERPOLATION_KEYS$1);
    var Resizing = (
      /** @class */
      function(_super) {
        __extends(Resizing2, _super);
        function Resizing2(args) {
          var _this = _super.call(this, args) || this;
          _this.height = args.height;
          _this.width = args.width;
          if (args.interpolation) {
            if (INTERPOLATION_METHODS$1.has(args.interpolation)) {
              _this.interpolation = args.interpolation;
            } else {
              throw new ValueError("Invalid interpolation parameter: ".concat(args.interpolation, " is not implemented"));
            }
          } else {
            _this.interpolation = "bilinear";
          }
          _this.cropToAspectRatio = Boolean(args.cropToAspectRatio);
          return _this;
        }
        Resizing2.prototype.computeOutputShape = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          var numChannels = inputShape[2];
          return [this.height, this.width, numChannels];
        };
        Resizing2.prototype.getConfig = function() {
          var config = {
            "height": this.height,
            "width": this.width,
            "interpolation": this.interpolation,
            "cropToAspectRatio": this.cropToAspectRatio
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        Resizing2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            var size = [_this.height, _this.width];
            if (_this.interpolation === "bilinear") {
              return tfc.image.resizeBilinear(inputs, size, !_this.cropToAspectRatio);
            } else if (_this.interpolation === "nearest") {
              return tfc.image.resizeNearestNeighbor(inputs, size, !_this.cropToAspectRatio);
            } else {
              throw new Error("Interpolation is ".concat(_this.interpolation, " but only ").concat(__spreadArray([], __read(INTERPOLATION_METHODS$1), false), " are supported"));
            }
          });
        };
        return Resizing2;
      }(Layer)
    );
    Resizing.className = "Resizing";
    tfc.serialization.registerClass(Resizing);
    var RandomSeed = (
      /** @class */
      function() {
        function RandomSeed2(seed) {
          this.seed = seed;
        }
        RandomSeed2.prototype.next = function() {
          if (this.seed === void 0) {
            return void 0;
          }
          return this.seed++;
        };
        return RandomSeed2;
      }()
    );
    RandomSeed.className = "RandomSeed";
    var BaseRandomLayer = (
      /** @class */
      function(_super) {
        __extends(BaseRandomLayer2, _super);
        function BaseRandomLayer2(args) {
          var _this = _super.call(this, args) || this;
          _this.randomGenerator = new RandomSeed(args.seed);
          return _this;
        }
        BaseRandomLayer2.prototype.getConfig = function() {
          var config = {
            "seed": this.randomGenerator.seed
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        return BaseRandomLayer2;
      }(Layer)
    );
    BaseRandomLayer.className = "BaseRandomLayer";
    var INTERPOLATION_KEYS = ["bilinear", "nearest"];
    var INTERPOLATION_METHODS = new Set(INTERPOLATION_KEYS);
    var RandomWidth = (
      /** @class */
      function(_super) {
        __extends(RandomWidth2, _super);
        function RandomWidth2(args) {
          var _this = _super.call(this, args) || this;
          var factor = args.factor, _a2 = args.interpolation, interpolation = _a2 === void 0 ? "bilinear" : _a2;
          _this.factor = factor;
          if (Array.isArray(_this.factor) && _this.factor.length === 2) {
            _this.widthLower = _this.factor[0];
            _this.widthUpper = _this.factor[1];
          } else if (!Array.isArray(_this.factor) && _this.factor > 0) {
            _this.widthLower = -_this.factor;
            _this.widthUpper = _this.factor;
          } else {
            throw new ValueError("Invalid factor: ".concat(_this.factor, ". Must be positive number or tuple of 2 numbers"));
          }
          if (_this.widthLower < -1 || _this.widthUpper < -1) {
            throw new ValueError("factor must have values larger than -1. Got: ".concat(_this.factor));
          }
          if (_this.widthUpper < _this.widthLower) {
            throw new ValueError("factor cannot have upper bound less than lower bound.\n        Got upper bound: ".concat(_this.widthUpper, ".\n        Got lower bound: ").concat(_this.widthLower, "\n      "));
          }
          if (interpolation) {
            if (INTERPOLATION_METHODS.has(interpolation)) {
              _this.interpolation = interpolation;
            } else {
              throw new ValueError("Invalid interpolation parameter: ".concat(interpolation, " is not implemented"));
            }
          }
          return _this;
        }
        RandomWidth2.prototype.getConfig = function() {
          var config = {
            "factor": this.factor,
            "interpolation": this.interpolation
          };
          var baseConfig = _super.prototype.getConfig.call(this);
          Object.assign(config, baseConfig);
          return config;
        };
        RandomWidth2.prototype.computeOutputShape = function(inputShape) {
          inputShape = getExactlyOneShape(inputShape);
          var numChannels = inputShape[2];
          return [this.imgHeight, -1, numChannels];
        };
        RandomWidth2.prototype.call = function(inputs, kwargs) {
          var _this = this;
          return tfc.tidy(function() {
            var input2 = getExactlyOneTensor(inputs);
            _this.imgHeight = input2.shape[input2.shape.length - 3];
            var imgWidth = input2.shape[input2.shape.length - 2];
            _this.widthFactor = tfc.randomUniform([1], 1 + _this.widthLower, 1 + _this.widthUpper, "float32", _this.randomGenerator.next());
            var adjustedWidth = _this.widthFactor.dataSync()[0] * imgWidth;
            adjustedWidth = Math.round(adjustedWidth);
            var size = [_this.imgHeight, adjustedWidth];
            switch (_this.interpolation) {
              case "bilinear":
                return tfc.image.resizeBilinear(inputs, size);
              case "nearest":
                return tfc.image.resizeNearestNeighbor(inputs, size);
              default:
                throw new Error("Interpolation is ".concat(_this.interpolation, "\n          but only ").concat(__spreadArray([], __read(INTERPOLATION_METHODS), false), " are supported"));
            }
          });
        };
        return RandomWidth2;
      }(BaseRandomLayer)
    );
    RandomWidth.className = "RandomWidth";
    tfc.serialization.registerClass(RandomWidth);
    function inputLayer(args) {
      return new InputLayer(args);
    }
    function elu(args) {
      return new ELU(args);
    }
    function reLU(args) {
      return new ReLU(args);
    }
    function leakyReLU(args) {
      return new LeakyReLU(args);
    }
    function prelu(args) {
      return new PReLU(args);
    }
    function softmax(args) {
      return new Softmax(args);
    }
    function thresholdedReLU(args) {
      return new ThresholdedReLU(args);
    }
    function conv1d(args) {
      return new Conv1D(args);
    }
    function conv2d(args) {
      return new Conv2D(args);
    }
    function conv2dTranspose(args) {
      return new Conv2DTranspose(args);
    }
    function conv3d(args) {
      return new Conv3D(args);
    }
    function conv3dTranspose(args) {
      return new Conv3DTranspose(args);
    }
    function separableConv2d(args) {
      return new SeparableConv2D(args);
    }
    function cropping2D(args) {
      return new Cropping2D(args);
    }
    function upSampling2d(args) {
      return new UpSampling2D(args);
    }
    function depthwiseConv2d(args) {
      return new DepthwiseConv2D(args);
    }
    function activation(args) {
      return new Activation(args);
    }
    function dense(args) {
      return new Dense(args);
    }
    function dropout(args) {
      return new Dropout(args);
    }
    function spatialDropout1d(args) {
      return new SpatialDropout1D(args);
    }
    function flatten(args) {
      return new Flatten(args);
    }
    function repeatVector(args) {
      return new RepeatVector(args);
    }
    function reshape(args) {
      return new Reshape(args);
    }
    function permute(args) {
      return new Permute(args);
    }
    function embedding(args) {
      return new Embedding(args);
    }
    function add(args) {
      return new Add(args);
    }
    function average(args) {
      return new Average(args);
    }
    function concatenate(args) {
      return new Concatenate(args);
    }
    function maximum(args) {
      return new Maximum(args);
    }
    function minimum(args) {
      return new Minimum(args);
    }
    function multiply(args) {
      return new Multiply(args);
    }
    function dot(args) {
      return new Dot(args);
    }
    function batchNormalization(args) {
      return new BatchNormalization(args);
    }
    function layerNormalization(args) {
      return new LayerNormalization(args);
    }
    function zeroPadding2d(args) {
      return new ZeroPadding2D(args);
    }
    function averagePooling1d(args) {
      return new AveragePooling1D(args);
    }
    function avgPool1d(args) {
      return averagePooling1d(args);
    }
    function avgPooling1d(args) {
      return averagePooling1d(args);
    }
    function averagePooling2d(args) {
      return new AveragePooling2D(args);
    }
    function avgPool2d(args) {
      return averagePooling2d(args);
    }
    function avgPooling2d(args) {
      return averagePooling2d(args);
    }
    function averagePooling3d(args) {
      return new AveragePooling3D(args);
    }
    function avgPool3d(args) {
      return averagePooling3d(args);
    }
    function avgPooling3d(args) {
      return averagePooling3d(args);
    }
    function globalAveragePooling1d(args) {
      return new GlobalAveragePooling1D(args);
    }
    function globalAveragePooling2d(args) {
      return new GlobalAveragePooling2D(args);
    }
    function globalMaxPooling1d(args) {
      return new GlobalMaxPooling1D(args);
    }
    function globalMaxPooling2d(args) {
      return new GlobalMaxPooling2D(args);
    }
    function maxPooling1d(args) {
      return new MaxPooling1D(args);
    }
    function maxPooling2d(args) {
      return new MaxPooling2D(args);
    }
    function maxPooling3d(args) {
      return new MaxPooling3D(args);
    }
    function gru(args) {
      return new GRU(args);
    }
    function gruCell(args) {
      return new GRUCell(args);
    }
    function lstm(args) {
      return new LSTM(args);
    }
    function lstmCell(args) {
      return new LSTMCell(args);
    }
    function simpleRNN(args) {
      return new SimpleRNN(args);
    }
    function simpleRNNCell(args) {
      return new SimpleRNNCell(args);
    }
    function convLstm2d(args) {
      return new ConvLSTM2D(args);
    }
    function convLstm2dCell(args) {
      return new ConvLSTM2DCell(args);
    }
    function rnn(args) {
      return new RNN(args);
    }
    function stackedRNNCells(args) {
      return new StackedRNNCells(args);
    }
    function bidirectional(args) {
      return new Bidirectional(args);
    }
    function timeDistributed(args) {
      return new TimeDistributed(args);
    }
    var globalMaxPool1d = globalMaxPooling1d;
    var globalMaxPool2d = globalMaxPooling2d;
    var maxPool1d = maxPooling1d;
    var maxPool2d = maxPooling2d;
    function gaussianNoise(args) {
      return new GaussianNoise(args);
    }
    function gaussianDropout(args) {
      return new GaussianDropout(args);
    }
    function alphaDropout(args) {
      return new AlphaDropout(args);
    }
    function masking(args) {
      return new Masking(args);
    }
    function rescaling(args) {
      return new Rescaling(args);
    }
    function centerCrop(args) {
      return new CenterCrop(args);
    }
    function resizing(args) {
      return new Resizing(args);
    }
    function categoryEncoding(args) {
      return new CategoryEncoding(args);
    }
    function randomWidth(args) {
      return new RandomWidth(args);
    }
    var exports_layers = {
      __proto__: null,
      Layer,
      RNN,
      RNNCell,
      activation,
      add,
      alphaDropout,
      average,
      averagePooling1d,
      averagePooling2d,
      averagePooling3d,
      avgPool1d,
      avgPool2d,
      avgPool3d,
      avgPooling1d,
      avgPooling2d,
      avgPooling3d,
      batchNormalization,
      bidirectional,
      categoryEncoding,
      centerCrop,
      concatenate,
      conv1d,
      conv2d,
      conv2dTranspose,
      conv3d,
      conv3dTranspose,
      convLstm2d,
      convLstm2dCell,
      cropping2D,
      dense,
      depthwiseConv2d,
      dot,
      dropout,
      elu,
      embedding,
      flatten,
      gaussianDropout,
      gaussianNoise,
      globalAveragePooling1d,
      globalAveragePooling2d,
      globalMaxPool1d,
      globalMaxPool2d,
      globalMaxPooling1d,
      globalMaxPooling2d,
      gru,
      gruCell,
      input,
      inputLayer,
      layerNormalization,
      leakyReLU,
      lstm,
      lstmCell,
      masking,
      maxPool1d,
      maxPool2d,
      maxPooling1d,
      maxPooling2d,
      maxPooling3d,
      maximum,
      minimum,
      multiply,
      permute,
      prelu,
      randomWidth,
      reLU,
      repeatVector,
      rescaling,
      reshape,
      resizing,
      rnn,
      separableConv2d,
      simpleRNN,
      simpleRNNCell,
      softmax,
      spatialDropout1d,
      stackedRNNCells,
      thresholdedReLU,
      timeDistributed,
      upSampling2d,
      zeroPadding2d
    };
    function binaryAccuracy(yTrue, yPred) {
      return binaryAccuracy$1(yTrue, yPred);
    }
    function binaryCrossentropy(yTrue, yPred) {
      return binaryCrossentropy$1(yTrue, yPred);
    }
    function sparseCategoricalAccuracy(yTrue, yPred) {
      return sparseCategoricalAccuracy$1(yTrue, yPred);
    }
    function categoricalAccuracy(yTrue, yPred) {
      return categoricalAccuracy$1(yTrue, yPred);
    }
    function categoricalCrossentropy(yTrue, yPred) {
      return categoricalCrossentropy$1(yTrue, yPred);
    }
    function precision(yTrue, yPred) {
      return precision$1(yTrue, yPred);
    }
    function recall(yTrue, yPred) {
      return recall$1(yTrue, yPred);
    }
    function cosineProximity(yTrue, yPred) {
      return cosineProximity$1(yTrue, yPred);
    }
    function meanAbsoluteError(yTrue, yPred) {
      return meanAbsoluteError$1(yTrue, yPred);
    }
    function meanAbsolutePercentageError(yTrue, yPred) {
      return meanAbsolutePercentageError$1(yTrue, yPred);
    }
    function MAPE(yTrue, yPred) {
      return meanAbsolutePercentageError$1(yTrue, yPred);
    }
    function mape(yTrue, yPred) {
      return meanAbsolutePercentageError$1(yTrue, yPred);
    }
    function meanSquaredError(yTrue, yPred) {
      return meanSquaredError$1(yTrue, yPred);
    }
    function MSE(yTrue, yPred) {
      return meanSquaredError$1(yTrue, yPred);
    }
    function mse(yTrue, yPred) {
      return meanSquaredError$1(yTrue, yPred);
    }
    function r2Score(yTrue, yPred) {
      return r2Score$1(yTrue, yPred);
    }
    var exports_metrics = {
      __proto__: null,
      MAPE,
      MSE,
      binaryAccuracy,
      binaryCrossentropy,
      categoricalAccuracy,
      categoricalCrossentropy,
      cosineProximity,
      mape,
      meanAbsoluteError,
      meanAbsolutePercentageError,
      meanSquaredError,
      mse,
      precision,
      r2Score,
      recall,
      sparseCategoricalAccuracy
    };
    var exports_models = {
      __proto__: null,
      modelFromJSON
    };
    function l1l2(config) {
      return new L1L2(config);
    }
    function l1(config) {
      return l1$1(config);
    }
    function l2(config) {
      return l2$1(config);
    }
    var exports_regularizers = {
      __proto__: null,
      l1,
      l1l2,
      l2
    };
    var Callback = (
      /** @class */
      function(_super) {
        __extends(Callback2, _super);
        function Callback2() {
          var _this = _super.apply(this, __spreadArray([], __read(arguments), false)) || this;
          _this.model = null;
          return _this;
        }
        Callback2.prototype.setModel = function(model2) {
          if (!(model2 instanceof LayersModel)) {
            throw new Error("model must be a LayersModel, not some other Container");
          }
          this.model = model2;
        };
        return Callback2;
      }(BaseCallback)
    );
    function less(currVal, prevVal) {
      return currVal < prevVal;
    }
    function greater(currVal, prevVal) {
      return currVal > prevVal;
    }
    var EarlyStopping = (
      /** @class */
      function(_super) {
        __extends(EarlyStopping2, _super);
        function EarlyStopping2(args) {
          var _this = _super.call(this) || this;
          if (args == null) {
            args = {};
          }
          if (args.restoreBestWeights) {
            throw new NotImplementedError("restoreBestWeights = True is not implemented in EarlyStopping yet.");
          }
          _this.monitor = args.monitor || "val_loss";
          _this.minDelta = Math.abs(args.minDelta || 0);
          _this.patience = args.patience || 0;
          _this.verbose = args.verbose || 0;
          _this.mode = args.mode || "auto";
          _this.baseline = args.baseline;
          if (["auto", "min", "max"].indexOf(_this.mode) === -1) {
            console.warn("EarlyStopping mode '".concat(_this.mode, "' is invalid. ") + "Falling back to mode 'auto'.");
            _this.mode = "auto";
          }
          if (_this.mode === "min") {
            _this.monitorFunc = less;
          } else if (_this.mode === "max") {
            _this.monitorFunc = greater;
          } else {
            if (_this.monitor.indexOf("acc") !== -1) {
              _this.monitorFunc = greater;
            } else {
              _this.monitorFunc = less;
            }
          }
          if (_this.monitorFunc === less) {
            _this.minDelta *= -1;
          }
          return _this;
        }
        EarlyStopping2.prototype.onTrainBegin = function(logs) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              this.wait = 0;
              this.stoppedEpoch = 0;
              if (this.baseline != null) {
                this.best = this.baseline;
              } else {
                this.best = this.monitorFunc === less ? Infinity : -Infinity;
              }
              return [
                2
                /*return*/
              ];
            });
          });
        };
        EarlyStopping2.prototype.onEpochEnd = function(epoch, logs) {
          return __awaiter(this, void 0, void 0, function() {
            var current;
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  return [4, resolveScalarsInLogs(logs)];
                case 1:
                  _a2.sent();
                  current = this.getMonitorValue(logs);
                  if (current == null) {
                    return [
                      2
                      /*return*/
                    ];
                  }
                  if (this.monitorFunc(current - this.minDelta, this.best)) {
                    this.best = current;
                    this.wait = 0;
                  } else {
                    this.wait++;
                    if (this.wait >= this.patience) {
                      this.stoppedEpoch = epoch;
                      this.model.stopTraining = true;
                    }
                  }
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        EarlyStopping2.prototype.onTrainEnd = function(logs) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a2) {
              if (this.stoppedEpoch > 0 && this.verbose) {
                console.log("Epoch ".concat(this.stoppedEpoch, ": early stopping."));
              }
              return [
                2
                /*return*/
              ];
            });
          });
        };
        EarlyStopping2.prototype.getMonitorValue = function(logs) {
          if (logs == null) {
            logs = {};
          }
          var monitorValue = logs[this.monitor];
          if (monitorValue == null) {
            console.warn("Metric for EarlyStopping ".concat(this.monitor, " is not available. ") + "Available metrics are: ".concat(Object.keys(logs)));
          }
          return monitorValue;
        };
        return EarlyStopping2;
      }(Callback)
    );
    function earlyStopping(args) {
      return new EarlyStopping(args);
    }
    var callbacks = { earlyStopping };
    exports2.Callback = Callback;
    exports2.CallbackList = CallbackList;
    exports2.CustomCallback = CustomCallback;
    exports2.EarlyStopping = EarlyStopping;
    exports2.History = History;
    exports2.InputSpec = InputSpec;
    exports2.LayerVariable = LayerVariable;
    exports2.LayersModel = LayersModel;
    exports2.RNN = RNN;
    exports2.Sequential = Sequential;
    exports2.SymbolicTensor = SymbolicTensor;
    exports2.callbacks = callbacks;
    exports2.constraints = exports_constraints;
    exports2.initializers = exports_initializers;
    exports2.input = input;
    exports2.layers = exports_layers;
    exports2.loadLayersModel = loadLayersModel;
    exports2.metrics = exports_metrics;
    exports2.model = model;
    exports2.models = exports_models;
    exports2.registerCallbackConstructor = registerCallbackConstructor;
    exports2.regularizers = exports_regularizers;
    exports2.sequential = sequential;
    exports2.version_layers = version;
  }
});

// node_modules/@tensorflow/tfjs-converter/dist/tf-converter.node.js
var require_tf_converter_node = __commonJS({
  "node_modules/@tensorflow/tfjs-converter/dist/tf-converter.node.js"(exports2) {
    "use strict";
    var tfc = require_tf_core_node();
    function _interopNamespaceDefault(e) {
      var n = /* @__PURE__ */ Object.create(null);
      if (e) {
        Object.keys(e).forEach(function(k) {
          if (k !== "default") {
            var d = Object.getOwnPropertyDescriptor(e, k);
            Object.defineProperty(n, k, d.get ? d : {
              enumerable: true,
              get: function() {
                return e[k];
              }
            });
          }
        });
      }
      n.default = e;
      return n;
    }
    function _mergeNamespaces(n, m) {
      m.forEach(function(e) {
        e && typeof e !== "string" && !Array.isArray(e) && Object.keys(e).forEach(function(k) {
          if (k !== "default" && !(k in n)) {
            var d = Object.getOwnPropertyDescriptor(e, k);
            Object.defineProperty(n, k, d.get ? d : {
              enumerable: true,
              get: function() {
                return e[k];
              }
            });
          }
        });
      });
      return n;
    }
    var tfc__namespace = /* @__PURE__ */ _interopNamespaceDefault(tfc);
    var ENV$1 = tfc.env();
    ENV$1.registerFlag("KEEP_INTERMEDIATE_TENSORS", function() {
      return false;
    }, function(debugValue) {
      if (debugValue) {
        console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.");
      }
    });
    var extendStatics = function(d, b) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
        d2.__proto__ = b2;
      } || function(d2, b2) {
        for (var p in b2)
          if (Object.prototype.hasOwnProperty.call(b2, p))
            d2[p] = b2[p];
      };
      return extendStatics(d, b);
    };
    function __extends(d, b) {
      if (typeof b !== "function" && b !== null)
        throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
      extendStatics(d, b);
      function __() {
        this.constructor = d;
      }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }
    function __awaiter(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step2(generator.next(value));
          } catch (e) {
            reject(e);
          }
        }
        function rejected(value) {
          try {
            step2(generator["throw"](value));
          } catch (e) {
            reject(e);
          }
        }
        function step2(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step2((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    }
    function __generator(thisArg, body) {
      var _ = { label: 0, sent: function() {
        if (t[0] & 1)
          throw t[1];
        return t[1];
      }, trys: [], ops: [] }, f, y, t, g;
      return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
        return this;
      }), g;
      function verb(n) {
        return function(v) {
          return step2([n, v]);
        };
      }
      function step2(op2) {
        if (f)
          throw new TypeError("Generator is already executing.");
        while (_)
          try {
            if (f = 1, y && (t = op2[0] & 2 ? y["return"] : op2[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op2[1])).done)
              return t;
            if (y = 0, t)
              op2 = [op2[0] & 2, t.value];
            switch (op2[0]) {
              case 0:
              case 1:
                t = op2;
                break;
              case 4:
                _.label++;
                return { value: op2[1], done: false };
              case 5:
                _.label++;
                y = op2[1];
                op2 = [0];
                continue;
              case 7:
                op2 = _.ops.pop();
                _.trys.pop();
                continue;
              default:
                if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op2[0] === 6 || op2[0] === 2)) {
                  _ = 0;
                  continue;
                }
                if (op2[0] === 3 && (!t || op2[1] > t[0] && op2[1] < t[3])) {
                  _.label = op2[1];
                  break;
                }
                if (op2[0] === 6 && _.label < t[1]) {
                  _.label = t[1];
                  t = op2;
                  break;
                }
                if (t && _.label < t[2]) {
                  _.label = t[2];
                  _.ops.push(op2);
                  break;
                }
                if (t[2])
                  _.ops.pop();
                _.trys.pop();
                continue;
            }
            op2 = body.call(thisArg, _);
          } catch (e) {
            op2 = [6, e];
            y = 0;
          } finally {
            f = t = 0;
          }
        if (op2[0] & 5)
          throw op2[1];
        return { value: op2[0] ? op2[1] : void 0, done: true };
      }
    }
    function __values(o) {
      var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
      if (m)
        return m.call(o);
      if (o && typeof o.length === "number")
        return {
          next: function() {
            if (o && i >= o.length)
              o = void 0;
            return { value: o && o[i++], done: !o };
          }
        };
      throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    }
    function __read(o, n) {
      var m = typeof Symbol === "function" && o[Symbol.iterator];
      if (!m)
        return o;
      var i = m.call(o), r, ar = [], e;
      try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
          ar.push(r.value);
      } catch (error) {
        e = { error };
      } finally {
        try {
          if (r && !r.done && (m = i["return"]))
            m.call(i);
        } finally {
          if (e)
            throw e.error;
        }
      }
      return ar;
    }
    function __spreadArray(to, from, pack) {
      if (pack || arguments.length === 2)
        for (var i = 0, l = from.length, ar; i < l; i++) {
          if (ar || !(i in from)) {
            if (!ar)
              ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
          }
        }
      return to.concat(ar || Array.prototype.slice.call(from));
    }
    var DataType;
    (function(DataType2) {
      DataType2[DataType2["DT_INVALID"] = 0] = "DT_INVALID";
      DataType2[DataType2["DT_FLOAT"] = 1] = "DT_FLOAT";
      DataType2[DataType2["DT_DOUBLE"] = 2] = "DT_DOUBLE";
      DataType2[DataType2["DT_INT32"] = 3] = "DT_INT32";
      DataType2[DataType2["DT_UINT8"] = 4] = "DT_UINT8";
      DataType2[DataType2["DT_INT16"] = 5] = "DT_INT16";
      DataType2[DataType2["DT_INT8"] = 6] = "DT_INT8";
      DataType2[DataType2["DT_STRING"] = 7] = "DT_STRING";
      DataType2[DataType2["DT_COMPLEX64"] = 8] = "DT_COMPLEX64";
      DataType2[DataType2["DT_INT64"] = 9] = "DT_INT64";
      DataType2[DataType2["DT_BOOL"] = 10] = "DT_BOOL";
      DataType2[DataType2["DT_QINT8"] = 11] = "DT_QINT8";
      DataType2[DataType2["DT_QUINT8"] = 12] = "DT_QUINT8";
      DataType2[DataType2["DT_QINT32"] = 13] = "DT_QINT32";
      DataType2[DataType2["DT_BFLOAT16"] = 14] = "DT_BFLOAT16";
      DataType2[DataType2["DT_QINT16"] = 15] = "DT_QINT16";
      DataType2[DataType2["DT_QUINT16"] = 16] = "DT_QUINT16";
      DataType2[DataType2["DT_UINT16"] = 17] = "DT_UINT16";
      DataType2[DataType2["DT_COMPLEX128"] = 18] = "DT_COMPLEX128";
      DataType2[DataType2["DT_HALF"] = 19] = "DT_HALF";
      DataType2[DataType2["DT_RESOURCE"] = 20] = "DT_RESOURCE";
      DataType2[DataType2["DT_VARIANT"] = 21] = "DT_VARIANT";
      DataType2[DataType2["DT_UINT32"] = 22] = "DT_UINT32";
      DataType2[DataType2["DT_UINT64"] = 23] = "DT_UINT64";
      DataType2[DataType2["DT_FLOAT_REF"] = 101] = "DT_FLOAT_REF";
      DataType2[DataType2["DT_DOUBLE_REF"] = 102] = "DT_DOUBLE_REF";
      DataType2[DataType2["DT_INT32_REF"] = 103] = "DT_INT32_REF";
      DataType2[DataType2["DT_UINT8_REF"] = 104] = "DT_UINT8_REF";
      DataType2[DataType2["DT_INT16_REF"] = 105] = "DT_INT16_REF";
      DataType2[DataType2["DT_INT8_REF"] = 106] = "DT_INT8_REF";
      DataType2[DataType2["DT_STRING_REF"] = 107] = "DT_STRING_REF";
      DataType2[DataType2["DT_COMPLEX64_REF"] = 108] = "DT_COMPLEX64_REF";
      DataType2[DataType2["DT_INT64_REF"] = 109] = "DT_INT64_REF";
      DataType2[DataType2["DT_BOOL_REF"] = 110] = "DT_BOOL_REF";
      DataType2[DataType2["DT_QINT8_REF"] = 111] = "DT_QINT8_REF";
      DataType2[DataType2["DT_QUINT8_REF"] = 112] = "DT_QUINT8_REF";
      DataType2[DataType2["DT_QINT32_REF"] = 113] = "DT_QINT32_REF";
      DataType2[DataType2["DT_BFLOAT16_REF"] = 114] = "DT_BFLOAT16_REF";
      DataType2[DataType2["DT_QINT16_REF"] = 115] = "DT_QINT16_REF";
      DataType2[DataType2["DT_QUINT16_REF"] = 116] = "DT_QUINT16_REF";
      DataType2[DataType2["DT_UINT16_REF"] = 117] = "DT_UINT16_REF";
      DataType2[DataType2["DT_COMPLEX128_REF"] = 118] = "DT_COMPLEX128_REF";
      DataType2[DataType2["DT_HALF_REF"] = 119] = "DT_HALF_REF";
      DataType2[DataType2["DT_RESOURCE_REF"] = 120] = "DT_RESOURCE_REF";
      DataType2[DataType2["DT_VARIANT_REF"] = 121] = "DT_VARIANT_REF";
      DataType2[DataType2["DT_UINT32_REF"] = 122] = "DT_UINT32_REF";
      DataType2[DataType2["DT_UINT64_REF"] = 123] = "DT_UINT64_REF";
    })(DataType || (DataType = {}));
    var SaverDef;
    (function(SaverDef2) {
      (function(CheckpointFormatVersion) {
        CheckpointFormatVersion[CheckpointFormatVersion["LEGACY"] = 0] = "LEGACY";
        CheckpointFormatVersion[CheckpointFormatVersion["V1"] = 1] = "V1";
        CheckpointFormatVersion[CheckpointFormatVersion["V2"] = 2] = "V2";
      })(SaverDef2.CheckpointFormatVersion || (SaverDef2.CheckpointFormatVersion = {}));
    })(SaverDef || (SaverDef = {}));
    var CUSTOM_OPS = {};
    function registerOp(name, opFunc) {
      var opMapper = {
        tfOpName: name,
        category: "custom",
        inputs: [],
        attrs: [],
        customExecutor: opFunc
      };
      CUSTOM_OPS[name] = opMapper;
    }
    function getRegisteredOp(name) {
      return CUSTOM_OPS[name];
    }
    function deregisterOp(name) {
      delete CUSTOM_OPS[name];
    }
    function getParamValue(paramName, node, tensorMap, context, resourceManager) {
      var inputParam = node.inputParams[paramName];
      if (inputParam && inputParam.inputIndexStart !== void 0) {
        var start = inputParam.inputIndexStart;
        var end = inputParam.inputIndexEnd === 0 ? void 0 : inputParam.inputIndexEnd === void 0 ? start + 1 : inputParam.inputIndexEnd;
        var shiftedStart = start < 0 ? node.inputNames.length + start : start;
        if (inputParam.type === "tensor") {
          return getTensor(node.inputNames[shiftedStart], tensorMap, context, resourceManager);
        }
        if (inputParam.type === "tensors") {
          var inputs_1 = node.inputs.slice(start, end);
          var inputNames = node.inputNames.slice(start, end).filter(function(_name, index) {
            var _a;
            return ((_a = inputs_1[index]) === null || _a === void 0 ? void 0 : _a.op) !== "NoOp";
          });
          return inputNames.map(function(name) {
            return getTensor(name, tensorMap, context, resourceManager);
          });
        }
        var tensor2 = getTensor(node.inputNames[shiftedStart], tensorMap, context, resourceManager);
        var data = tensor2.dataSync();
        return inputParam.type === "number" ? data[0] : tfc.util.toNestedArray(tensor2.shape, data);
      }
      var attrParam = node.attrParams[paramName];
      return attrParam && attrParam.value;
    }
    function getTensor(name, tensorsMap, context, resourceManager) {
      var _b = __read(parseNodeName(name, context), 2), nodeName = _b[0], index = _b[1];
      if (resourceManager != null) {
        var tensor2 = resourceManager.getHashTableHandleByName(nodeName);
        if (tensor2 != null) {
          return tensor2;
        }
      }
      var contextId = context.currentContextIds.find(function(contextId2) {
        return !!tensorsMap[getNodeNameWithContextId(nodeName, contextId2)];
      });
      return contextId !== void 0 ? tensorsMap[getNodeNameWithContextId(nodeName, contextId)][index] : void 0;
    }
    function getTensorsForCurrentContext(name, tensorsMap, context) {
      return tensorsMap[getNodeNameWithContextId(name, context.currentContextId)];
    }
    function getNodeNameAndIndex(inputName, context) {
      var _b = __read(parseNodeName(inputName, context), 3), nodeName = _b[0], index = _b[1], outputName = _b[2];
      return [
        getNodeNameWithContextId(nodeName, context && context.currentContextId),
        index,
        outputName
      ];
    }
    function getNodeNameWithContextId(name, contextId) {
      return !!contextId ? "".concat(name, "-").concat(contextId) : name;
    }
    function parseNodeName(name, context) {
      if (name === "") {
        return ["", 0, void 0];
      }
      var isCacheEnabled = context != null && context.parseNodeNameCache != null;
      if (isCacheEnabled) {
        var cachedResult = context.parseNodeNameCache.get(name);
        if (cachedResult != null) {
          return cachedResult;
        }
      }
      var parts = name.split(":");
      var result;
      if (parts.length === 1) {
        result = [name, 0, void 0];
      } else {
        var nodeName = parts[0];
        var outputName = parts.length === 3 ? parts[1] : void 0;
        var index = Number(parts[parts.length - 1]);
        result = [nodeName, index, outputName];
      }
      if (isCacheEnabled) {
        context.parseNodeNameCache.set(name, result);
      }
      return result;
    }
    function getPadding(node, tensorMap, context) {
      var pad2 = getParamValue("pad", node, tensorMap, context);
      if (pad2 === "explicit") {
        pad2 = getParamValue("explicitPaddings", node, tensorMap, context);
        var explicitPadding = [[0, 0], [0, 0], [0, 0], [0, 0]];
        for (var i = 0; i < 4; i++) {
          explicitPadding[i][0] = pad2[i * 2];
          explicitPadding[i][1] = pad2[i * 2 + 1];
        }
        return explicitPadding;
      }
      return pad2;
    }
    function cloneTensor(tensor2) {
      return tensor2.kept ? tensor2 : tfc.clone(tensor2);
    }
    var json$i = [
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          },
          {
            "tfName": "data_format",
            "name": "dataFormat",
            "type": "string",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      }
    ];
    var arithmetic = {
      __proto__: null,
      json: json$i
    };
    var json$h = [
      {
        "tfOpName": "Abs",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Acos",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Asin",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Atan",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "tfOpName": "Ceil",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "tfOpName": "ComplexAbs",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Cos",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Cosh",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Elu",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Exp",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Floor",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Log",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Imag",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          },
          {
            "tfName": "Tout",
            "name": "outputType",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Neg",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Real",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          },
          {
            "tfName": "Tout",
            "name": "outputType",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "tfOpName": "Relu",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Relu6",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Selu",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Sigmoid",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Sin",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Sinh",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Sqrt",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Rsqrt",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Square",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Tan",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Tanh",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Sign",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Round",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Expm1",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Log1p",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Reciprocal",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Softplus",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Asinh",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Acosh",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Atanh",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "Erf",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "LeakyRelu",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "alpha",
            "name": "alpha",
            "type": "number",
            "defaultValue": 0.2
          },
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "IsNan",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "IsFinite",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "IsInf",
        "category": "basic_math",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      }
    ];
    var basicMath = {
      __proto__: null,
      json: json$h
    };
    var json$g = [
      {
        "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": true
          },
          {
            "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": true
          }
        ]
      },
      {
        "tfOpName": "NextIteration",
        "category": "control",
        "inputs": [
          {
            "start": 0,
            "name": "tensor",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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"
          }
        ]
      }
    ];
    var control = {
      __proto__: null,
      json: json$g
    };
    var json$f = [
      {
        "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": true
          },
          {
            "tfName": "ksize",
            "name": "kernelSize",
            "type": "number[]"
          },
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          },
          {
            "tfName": "ksize",
            "name": "kernelSize",
            "type": "number[]"
          },
          {
            "tfName": "explicit_paddings",
            "name": "explicitPaddings",
            "type": "number[]",
            "defaultValue": [],
            "notSupported": true
          },
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          },
          {
            "tfName": "ksize",
            "name": "kernelSize",
            "type": "number[]"
          },
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          },
          {
            "tfName": "ksize",
            "name": "kernelSize",
            "type": "number[]"
          },
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          },
          {
            "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": true
          },
          {
            "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": true
          },
          {
            "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": true
          },
          {
            "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": 0.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": true
          },
          {
            "tfName": "explicit_paddings",
            "name": "explicitPaddings",
            "type": "number[]",
            "defaultValue": []
          },
          {
            "tfName": "dilations",
            "name": "dilations",
            "type": "number[]",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          },
          {
            "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"
          }
        ]
      }
    ];
    var convolution = {
      __proto__: null,
      json: json$f
    };
    var json$e = [
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          },
          {
            "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": true
          },
          {
            "tfName": "dtype",
            "name": "dtype",
            "type": "dtype"
          },
          {
            "tfName": "T",
            "name": "T",
            "type": "number",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          },
          {
            "tfName": "T",
            "name": "T",
            "type": "number",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          },
          {
            "tfName": "dtype",
            "name": "dtype",
            "type": "dtype"
          },
          {
            "tfName": "T",
            "name": "T",
            "type": "number",
            "notSupported": true
          }
        ]
      },
      {
        "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"
          }
        ]
      }
    ];
    var creation = {
      __proto__: null,
      json: json$e
    };
    var json$d = [
      {
        "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": true
          },
          {
            "tfName": "T_threshold",
            "name": "threshold",
            "type": "dtype",
            "notSupported": true
          },
          {
            "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      }
    ];
    var dynamic = {
      __proto__: null,
      json: json$d
    };
    var json$c = [
      {
        "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"
          }
        ]
      }
    ];
    var evaluation = {
      __proto__: null,
      json: json$c
    };
    var json$b = [
      {
        "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": true
          },
          {
            "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"
          }
        ]
      }
    ];
    var graph = {
      __proto__: null,
      json: json$b
    };
    var json$a = [
      {
        "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": true
          },
          {
            "tfName": "Tout",
            "name": "tOut",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          },
          {
            "tfName": "Tout",
            "name": "tOut",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          },
          {
            "tfName": "Tout",
            "name": "tOut",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          },
          {
            "tfName": "Tout",
            "name": "tOut",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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"
          }
        ]
      }
    ];
    var hashTable = {
      __proto__: null,
      json: json$a
    };
    var json$9 = [
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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"
          }
        ]
      }
    ];
    var image$1 = {
      __proto__: null,
      json: json$9
    };
    var json$8 = [
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "tfOpName": "LogicalNot",
        "category": "logical",
        "inputs": [
          {
            "start": 0,
            "name": "a",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "tfOpName": "BitwiseAnd",
        "category": "logical",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          },
          {
            "start": 1,
            "name": "y",
            "type": "tensor"
          }
        ]
      }
    ];
    var logical = {
      __proto__: null,
      json: json$8
    };
    var json$7 = [
      {
        "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": false
          },
          {
            "tfName": "transpose_b",
            "name": "transposeB",
            "type": "bool",
            "defaultValue": false
          },
          {
            "tfName": "leakyrelu_alpha",
            "name": "leakyreluAlpha",
            "type": "number",
            "defaultValue": 0.2
          },
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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": false
          },
          {
            "tfName": "transpose_b",
            "name": "transposeB",
            "type": "bool",
            "defaultValue": false
          },
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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": false
          },
          {
            "tfName": "adj_y",
            "name": "transposeB",
            "type": "bool",
            "defaultValue": false
          },
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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": false
          },
          {
            "tfName": "adj_y",
            "name": "transposeB",
            "type": "bool",
            "defaultValue": false
          },
          {
            "tfName": "T",
            "name": "dtype",
            "type": "dtype",
            "notSupported": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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"
          }
        ]
      }
    ];
    var matrices = {
      __proto__: null,
      json: json$7
    };
    var json$6 = [
      {
        "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": false
          }
        ]
      },
      {
        "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": 1e-3
          },
          {
            "tfName": "data_format",
            "name": "dataFormat",
            "type": "string",
            "notSupported": true
          }
        ]
      },
      {
        "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": 1e-3
          },
          {
            "tfName": "data_format",
            "name": "dataFormat",
            "type": "string",
            "notSupported": true
          }
        ]
      },
      {
        "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": 1e-3
          },
          {
            "tfName": "data_format",
            "name": "dataFormat",
            "type": "string",
            "notSupported": true
          }
        ]
      },
      {
        "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": 0.5
          }
        ]
      },
      {
        "tfOpName": "Softmax",
        "category": "normalization",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ]
      },
      {
        "tfOpName": "LogSoftmax",
        "category": "normalization",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ]
      }
    ];
    var normalization = {
      __proto__: null,
      json: json$6
    };
    var json$5 = [
      {
        "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": true
          }
        ]
      },
      {
        "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"
          }
        ]
      }
    ];
    var reduction = {
      __proto__: null,
      json: json$5
    };
    var json$4 = [
      {
        "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": true
          }
        ]
      },
      {
        "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": true
          }
        ]
      },
      {
        "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": false,
            "notSupported": true
          }
        ]
      },
      {
        "tfOpName": "TensorScatterUpdate",
        "category": "slice_join",
        "inputs": [
          {
            "start": 0,
            "name": "tensor",
            "type": "tensor"
          },
          {
            "start": 1,
            "name": "indices",
            "type": "tensor"
          },
          {
            "start": 2,
            "name": "values",
            "type": "tensor"
          }
        ]
      }
    ];
    var sliceJoin = {
      __proto__: null,
      json: json$4
    };
    var json$3 = [
      {
        "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": true
          }
        ]
      },
      {
        "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"
          }
        ]
      }
    ];
    var sparse$1 = {
      __proto__: null,
      json: json$3
    };
    var json$2 = [
      {
        "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": true
          }
        ]
      },
      {
        "tfOpName": "IRFFT",
        "category": "spectral",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          },
          {
            "start": 1,
            "name": "fft_length",
            "type": "number",
            "notSupported": true
          }
        ]
      }
    ];
    var spectral$1 = {
      __proto__: null,
      json: json$2
    };
    var json$1 = [
      {
        "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"
          }
        ]
      }
    ];
    var string$1 = {
      __proto__: null,
      json: json$1
    };
    var json = [
      {
        "tfOpName": "Cast",
        "category": "transformation",
        "inputs": [
          {
            "start": 0,
            "name": "x",
            "type": "tensor"
          }
        ],
        "attrs": [
          {
            "tfName": "SrcT",
            "name": "sdtype",
            "type": "dtype",
            "notSupported": true
          },
          {
            "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 transformation = {
      __proto__: null,
      json
    };
    var OperationMapper = (
      /** @class */
      function() {
        function OperationMapper2() {
          var ops = [
            arithmetic,
            basicMath,
            control,
            convolution,
            creation,
            dynamic,
            evaluation,
            graph,
            hashTable,
            image$1,
            logical,
            matrices,
            normalization,
            reduction,
            sliceJoin,
            sparse$1,
            spectral$1,
            string$1,
            transformation
          ];
          var mappersJson = [].concat.apply([], __spreadArray([], __read(ops.map(function(op2) {
            return op2.json;
          })), false));
          this.opMappers = mappersJson.reduce(function(map, mapper) {
            map[mapper.tfOpName] = mapper;
            return map;
          }, {});
        }
        Object.defineProperty(OperationMapper2, "Instance", {
          // Singleton instance for the mapper
          get: function() {
            return this._instance || (this._instance = new this());
          },
          enumerable: false,
          configurable: true
        });
        OperationMapper2.prototype.transformGraph = function(graph2, signature) {
          var _this = this;
          if (signature === void 0) {
            signature = {};
          }
          var tfNodes = graph2.node;
          var placeholders = [];
          var weights = [];
          var initNodes = [];
          var nodes = tfNodes.reduce(function(map, node) {
            map[node.name] = _this.mapNode(node);
            if (node.op.startsWith("Placeholder")) {
              placeholders.push(map[node.name]);
            } else if (node.op === "Const") {
              weights.push(map[node.name]);
            } else if (node.input == null || node.input.length === 0) {
              initNodes.push(map[node.name]);
            }
            return map;
          }, {});
          var inputs = [];
          var outputs = [];
          var inputNodeNameToKey = {};
          var outputNodeNameToKey = {};
          if (signature != null) {
            inputNodeNameToKey = this.mapSignatureEntries(signature.inputs);
            outputNodeNameToKey = this.mapSignatureEntries(signature.outputs);
          }
          var allNodes = Object.keys(nodes);
          allNodes.forEach(function(key) {
            var node = nodes[key];
            node.inputNames.forEach(function(name, index) {
              var _a = __read(getNodeNameAndIndex(name), 3), nodeName = _a[0], outputName = _a[2];
              var inputNode = nodes[nodeName];
              if (inputNode.outputs != null) {
                var outputIndex = inputNode.outputs.indexOf(outputName);
                if (outputIndex !== -1) {
                  var inputName = "".concat(nodeName, ":").concat(outputIndex);
                  node.inputNames[index] = inputName;
                }
              }
              node.inputs.push(inputNode);
              inputNode.children.push(node);
            });
          });
          if (Object.keys(outputNodeNameToKey).length === 0) {
            allNodes.forEach(function(key) {
              var node = nodes[key];
              if (node.children.length === 0) {
                outputs.push(node);
              }
            });
          } else {
            Object.keys(outputNodeNameToKey).forEach(function(name) {
              var _a = __read(getNodeNameAndIndex(name), 1), nodeName = _a[0];
              var node = nodes[nodeName];
              if (node != null) {
                node.signatureKey = outputNodeNameToKey[name];
                outputs.push(node);
              }
            });
          }
          if (Object.keys(inputNodeNameToKey).length > 0) {
            Object.keys(inputNodeNameToKey).forEach(function(name) {
              var _a = __read(getNodeNameAndIndex(name), 1), nodeName = _a[0];
              var node = nodes[nodeName];
              if (node) {
                node.signatureKey = inputNodeNameToKey[name];
                inputs.push(node);
              }
            });
          } else {
            inputs = placeholders;
          }
          var functions = {};
          if (graph2.library != null && graph2.library.function != null) {
            functions = graph2.library.function.reduce(function(functions2, func) {
              functions2[func.signature.name] = _this.mapFunction(func);
              return functions2;
            }, {});
          }
          var result = { nodes, inputs, outputs, weights, placeholders, signature, functions };
          if (initNodes.length > 0) {
            result.initNodes = initNodes;
          }
          return result;
        };
        OperationMapper2.prototype.mapSignatureEntries = function(entries) {
          return Object.keys(entries || {}).reduce(function(prev, curr) {
            prev[entries[curr].name] = curr;
            return prev;
          }, {});
        };
        OperationMapper2.prototype.mapNode = function(node) {
          var mapper = getRegisteredOp(node.op) || this.opMappers[node.op] || {};
          if (node.attr == null) {
            node.attr = {};
          }
          var newNode = {
            name: node.name,
            op: node.op,
            category: mapper.category,
            inputNames: (node.input || []).map(function(input) {
              return input.startsWith("^") ? input.slice(1) : input;
            }),
            inputs: [],
            children: [],
            inputParams: {},
            attrParams: {},
            rawAttrs: node.attr,
            outputs: mapper.outputs
          };
          if (mapper.inputs != null) {
            newNode.inputParams = mapper.inputs.reduce(function(map, param) {
              map[param.name] = {
                type: param.type,
                inputIndexStart: param.start,
                inputIndexEnd: param.end
              };
              return map;
            }, {});
          }
          if (mapper.attrs != null) {
            newNode.attrParams = mapper.attrs.reduce(function(map, param) {
              var type = param.type;
              var value = void 0;
              switch (param.type) {
                case "string":
                  value = getStringParam(node.attr, param.tfName, param.defaultValue);
                  if (value === void 0 && !!param.tfDeprecatedName) {
                    value = getStringParam(node.attr, param.tfDeprecatedName, param.defaultValue);
                  }
                  break;
                case "string[]":
                  value = getStringArrayParam(node.attr, param.tfName, param.defaultValue);
                  if (value === void 0 && !!param.tfDeprecatedName) {
                    value = getStringArrayParam(node.attr, param.tfDeprecatedName, param.defaultValue);
                  }
                  break;
                case "number":
                  value = getNumberParam(node.attr, param.tfName, param.defaultValue || 0);
                  if (value === void 0 && !!param.tfDeprecatedName) {
                    value = getNumberParam(node.attr, param.tfDeprecatedName, param.defaultValue);
                  }
                  break;
                case "number[]":
                  value = getNumericArrayParam(node.attr, param.tfName, param.defaultValue);
                  if (value === void 0 && !!param.tfDeprecatedName) {
                    value = getNumericArrayParam(node.attr, param.tfDeprecatedName, param.defaultValue);
                  }
                  break;
                case "bool":
                  value = getBoolParam(node.attr, param.tfName, param.defaultValue);
                  if (value === void 0 && !!param.tfDeprecatedName) {
                    value = getBoolParam(node.attr, param.tfDeprecatedName, param.defaultValue);
                  }
                  break;
                case "bool[]":
                  value = getBoolArrayParam(node.attr, param.tfName, param.defaultValue);
                  if (value === void 0 && !!param.tfDeprecatedName) {
                    value = getBoolArrayParam(node.attr, param.tfDeprecatedName, param.defaultValue);
                  }
                  break;
                case "shape":
                  value = getTensorShapeParam(node.attr, param.tfName, param.defaultValue);
                  if (value === void 0 && !!param.tfDeprecatedName) {
                    value = getTensorShapeParam(node.attr, param.tfDeprecatedName, param.defaultValue);
                  }
                  break;
                case "shape[]":
                  value = getTensorShapeArrayParam(node.attr, param.tfName, param.defaultValue);
                  if (value === void 0 && !!param.tfDeprecatedName) {
                    value = getTensorShapeArrayParam(node.attr, param.tfDeprecatedName, param.defaultValue);
                  }
                  break;
                case "dtype":
                  value = getDtypeParam(node.attr, param.tfName, param.defaultValue);
                  if (value === void 0 && !!param.tfDeprecatedName) {
                    value = getDtypeParam(node.attr, param.tfDeprecatedName, param.defaultValue);
                  }
                  break;
                case "dtype[]":
                  value = getDtypeArrayParam(node.attr, param.tfName, param.defaultValue);
                  if (value === void 0 && !!param.tfDeprecatedName) {
                    value = getDtypeArrayParam(node.attr, param.tfDeprecatedName, param.defaultValue);
                  }
                  break;
                case "func":
                  value = getFuncParam(node.attr, param.tfName, param.defaultValue);
                  if (value === void 0 && !!param.tfDeprecatedName) {
                    value = getFuncParam(node.attr, param.tfDeprecatedName, param.defaultValue);
                  }
                  break;
                case "tensor":
                case "tensors":
                  break;
                default:
                  throw new Error("Unsupported param type: ".concat(param.type, " for op: ").concat(node.op));
              }
              map[param.name] = { value, type };
              return map;
            }, {});
          }
          return newNode;
        };
        OperationMapper2.prototype.mapFunction = function(functionDef) {
          var _this = this;
          var tfNodes = functionDef.nodeDef;
          var placeholders = [];
          var weights = [];
          var nodes = {};
          if (tfNodes != null) {
            nodes = tfNodes.reduce(function(map, node) {
              map[node.name] = _this.mapNode(node);
              if (node.op === "Const") {
                weights.push(map[node.name]);
              }
              return map;
            }, {});
          }
          var inputs = [];
          var outputs = [];
          functionDef.signature.inputArg.forEach(function(arg) {
            var _a = __read(getNodeNameAndIndex(arg.name), 1), nodeName = _a[0];
            var node = {
              name: nodeName,
              op: "Placeholder",
              inputs: [],
              inputNames: [],
              category: "graph",
              inputParams: {},
              attrParams: { dtype: { value: parseDtypeParam(arg.type), type: "dtype" } },
              children: []
            };
            node.signatureKey = arg.name;
            inputs.push(node);
            nodes[nodeName] = node;
          });
          var allNodes = Object.keys(nodes);
          allNodes.forEach(function(key) {
            var node = nodes[key];
            node.inputNames.forEach(function(name, index) {
              var _a = __read(getNodeNameAndIndex(name), 3), nodeName = _a[0], outputName = _a[2];
              var inputNode = nodes[nodeName];
              if (inputNode.outputs != null) {
                var outputIndex = inputNode.outputs.indexOf(outputName);
                if (outputIndex !== -1) {
                  var inputName = "".concat(nodeName, ":").concat(outputIndex);
                  node.inputNames[index] = inputName;
                }
              }
              node.inputs.push(inputNode);
              inputNode.children.push(node);
            });
          });
          var returnNodeMap = functionDef.ret;
          functionDef.signature.outputArg.forEach(function(output) {
            var _a = __read(getNodeNameAndIndex(returnNodeMap[output.name]), 2), nodeName = _a[0], index = _a[1];
            var node = nodes[nodeName];
            if (node != null) {
              node.defaultOutput = index;
              outputs.push(node);
            }
          });
          var signature = this.mapArgsToSignature(functionDef);
          return { nodes, inputs, outputs, weights, placeholders, signature };
        };
        OperationMapper2.prototype.mapArgsToSignature = function(functionDef) {
          var _this = this;
          return {
            methodName: functionDef.signature.name,
            inputs: functionDef.signature.inputArg.reduce(function(map, arg) {
              map[arg.name] = _this.mapArgToTensorInfo(arg);
              return map;
            }, {}),
            outputs: functionDef.signature.outputArg.reduce(function(map, arg) {
              map[arg.name] = _this.mapArgToTensorInfo(arg, functionDef.ret);
              return map;
            }, {})
          };
        };
        OperationMapper2.prototype.mapArgToTensorInfo = function(arg, nameMap) {
          var name = arg.name;
          if (nameMap != null) {
            name = nameMap[name];
          }
          return { name, dtype: arg.type };
        };
        return OperationMapper2;
      }()
    );
    function decodeBase64(text) {
      var global2 = tfc.env().global;
      if (typeof global2.atob !== "undefined") {
        return global2.atob(text);
      } else if (typeof Buffer !== "undefined") {
        return new Buffer(text, "base64").toString();
      } else {
        throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()");
      }
    }
    function parseStringParam(s, keepCase) {
      var value = Array.isArray(s) ? String.fromCharCode.apply(null, s) : decodeBase64(s);
      return keepCase ? value : value.toLowerCase();
    }
    function getStringParam(attrs, name, def, keepCase) {
      if (keepCase === void 0) {
        keepCase = false;
      }
      var param = attrs[name];
      if (param != null) {
        return parseStringParam(param.s, keepCase);
      }
      return def;
    }
    function getBoolParam(attrs, name, def) {
      var param = attrs[name];
      return param ? param.b : def;
    }
    function getNumberParam(attrs, name, def) {
      var param = attrs[name] || {};
      var value = param["i"] != null ? param["i"] : param["f"] != null ? param["f"] : def;
      return typeof value === "number" ? value : parseInt(value, 10);
    }
    function parseDtypeParam(value) {
      if (typeof value === "string") {
        value = DataType[value];
      }
      switch (value) {
        case DataType.DT_FLOAT:
        case DataType.DT_HALF:
          return "float32";
        case DataType.DT_INT32:
        case DataType.DT_INT64:
        case DataType.DT_INT8:
        case DataType.DT_UINT8:
          return "int32";
        case DataType.DT_BOOL:
          return "bool";
        case DataType.DT_DOUBLE:
          return "float32";
        case DataType.DT_STRING:
          return "string";
        case DataType.DT_COMPLEX64:
        case DataType.DT_COMPLEX128:
          return "complex64";
        default:
          return null;
      }
    }
    function getFuncParam(attrs, name, def) {
      var param = attrs[name];
      if (param && param.func) {
        return param.func.name;
      }
      return def;
    }
    function getDtypeParam(attrs, name, def) {
      var param = attrs[name];
      if (param && param.type) {
        return parseDtypeParam(param.type);
      }
      return def;
    }
    function getDtypeArrayParam(attrs, name, def) {
      var param = attrs[name];
      if (param && param.list && param.list.type) {
        return param.list.type.map(function(v) {
          return parseDtypeParam(v);
        });
      }
      return def;
    }
    function parseTensorShapeParam(shape) {
      if (shape.unknownRank) {
        return void 0;
      }
      if (shape.dim != null) {
        return shape.dim.map(function(dim) {
          return typeof dim.size === "number" ? dim.size : parseInt(dim.size, 10);
        });
      }
      return [];
    }
    function getTensorShapeParam(attrs, name, def) {
      var param = attrs[name];
      if (param && param.shape) {
        return parseTensorShapeParam(param.shape);
      }
      return def;
    }
    function getNumericArrayParam(attrs, name, def) {
      var param = attrs[name];
      if (param) {
        return ((param.list.f && param.list.f.length ? param.list.f : param.list.i) || []).map(function(v) {
          return typeof v === "number" ? v : parseInt(v, 10);
        });
      }
      return def;
    }
    function getStringArrayParam(attrs, name, def, keepCase) {
      if (keepCase === void 0) {
        keepCase = false;
      }
      var param = attrs[name];
      if (param && param.list && param.list.s) {
        return param.list.s.map(function(v) {
          return parseStringParam(v, keepCase);
        });
      }
      return def;
    }
    function getTensorShapeArrayParam(attrs, name, def) {
      var param = attrs[name];
      if (param && param.list && param.list.shape) {
        return param.list.shape.map(function(v) {
          return parseTensorShapeParam(v);
        });
      }
      return def;
    }
    function getBoolArrayParam(attrs, name, def) {
      var param = attrs[name];
      if (param && param.list && param.list.b) {
        return param.list.b;
      }
      return def;
    }
    var NodeValueImpl = (
      /** @class */
      function() {
        function NodeValueImpl2(node, tensorMap, context) {
          var _this = this;
          this.node = node;
          this.tensorMap = tensorMap;
          this.context = context;
          this.inputs = [];
          this.attrs = {};
          this.inputs = node.inputNames.map(function(name) {
            return _this.getInput(name);
          });
          if (node.rawAttrs != null) {
            this.attrs = Object.keys(node.rawAttrs).reduce(function(attrs, key) {
              attrs[key] = _this.getAttr(key);
              return attrs;
            }, {});
          }
        }
        NodeValueImpl2.prototype.getInput = function(name) {
          return getTensor(name, this.tensorMap, this.context);
        };
        NodeValueImpl2.prototype.getAttr = function(name, defaultValue) {
          var value = this.node.rawAttrs[name];
          if (value.tensor != null) {
            return getTensor(name, this.tensorMap, this.context);
          }
          if (value.i != null || value.f != null) {
            return getNumberParam(this.node.rawAttrs, name, defaultValue);
          }
          if (value.s != null) {
            return getStringParam(this.node.rawAttrs, name, defaultValue);
          }
          if (value.b != null) {
            return getBoolParam(this.node.rawAttrs, name, defaultValue);
          }
          if (value.shape != null) {
            return getTensorShapeParam(this.node.rawAttrs, name, defaultValue);
          }
          if (value.type != null) {
            return getDtypeParam(this.node.rawAttrs, name, defaultValue);
          }
          if (value.list != null) {
            if (value.list.i != null || value.list.f != null) {
              return getNumericArrayParam(this.node.rawAttrs, name, defaultValue);
            }
            if (value.list.s != null) {
              return getStringArrayParam(this.node.rawAttrs, name, defaultValue);
            }
            if (value.list.shape != null) {
              return getTensorShapeArrayParam(this.node.rawAttrs, name, defaultValue);
            }
            if (value.list.b != null) {
              return getBoolArrayParam(this.node.rawAttrs, name, defaultValue);
            }
            if (value.list.type != null) {
              return getDtypeArrayParam(this.node.rawAttrs, name, defaultValue);
            }
          }
          return defaultValue;
        };
        return NodeValueImpl2;
      }()
    );
    var EPSILON_FLOAT32 = 1e-7;
    var EPSILON_FLOAT16 = 1e-4;
    var KernelBackend = (
      /** @class */
      function() {
        function KernelBackend2() {
        }
        KernelBackend2.prototype.refCount = function(dataId) {
          return notYetImplemented("refCount");
        };
        KernelBackend2.prototype.incRef = function(dataId) {
          return notYetImplemented("incRef");
        };
        KernelBackend2.prototype.timerAvailable = function() {
          return true;
        };
        KernelBackend2.prototype.time = function(f) {
          return notYetImplemented("time");
        };
        KernelBackend2.prototype.read = function(dataId) {
          return notYetImplemented("read");
        };
        KernelBackend2.prototype.readSync = function(dataId) {
          return notYetImplemented("readSync");
        };
        KernelBackend2.prototype.readToGPU = function(dataId, options) {
          return notYetImplemented("readToGPU");
        };
        KernelBackend2.prototype.numDataIds = function() {
          return notYetImplemented("numDataIds");
        };
        KernelBackend2.prototype.disposeData = function(dataId, force) {
          return notYetImplemented("disposeData");
        };
        KernelBackend2.prototype.write = function(values, shape, dtype) {
          return notYetImplemented("write");
        };
        KernelBackend2.prototype.move = function(dataId, values, shape, dtype, refCount) {
          return notYetImplemented("move");
        };
        KernelBackend2.prototype.createTensorFromGPUData = function(values, shape, dtype) {
          return notYetImplemented("createTensorFromGPUData");
        };
        KernelBackend2.prototype.memory = function() {
          return notYetImplemented("memory");
        };
        KernelBackend2.prototype.floatPrecision = function() {
          return notYetImplemented("floatPrecision");
        };
        KernelBackend2.prototype.epsilon = function() {
          return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;
        };
        KernelBackend2.prototype.dispose = function() {
          return notYetImplemented("dispose");
        };
        return KernelBackend2;
      }()
    );
    function notYetImplemented(kernelName) {
      throw new Error("'".concat(kernelName, "' not yet implemented or not found in the registry. ") + "This kernel may not be supported by the tfjs backend you have chosen");
    }
    function assert(expr, msg) {
      if (!expr) {
        throw new Error(typeof msg === "string" ? msg : msg());
      }
    }
    function assertShapesMatch(shapeA, shapeB, errorMessagePrefix) {
      if (errorMessagePrefix === void 0) {
        errorMessagePrefix = "";
      }
      assert(arraysEqual(shapeA, shapeB), function() {
        return errorMessagePrefix + " Shapes ".concat(shapeA, " and ").concat(shapeB, " must match");
      });
    }
    function assertNonNull(a) {
      assert(a != null, function() {
        return "The input to the tensor constructor must be a non-null value.";
      });
    }
    function sizeFromShape(shape) {
      if (shape.length === 0) {
        return 1;
      }
      var size = shape[0];
      for (var i = 1; i < shape.length; i++) {
        size *= shape[i];
      }
      return size;
    }
    function arraysEqualWithNull(n1, n2) {
      if (n1 === n2) {
        return true;
      }
      if (n1 == null || n2 == null) {
        return false;
      }
      if (n1.length !== n2.length) {
        return false;
      }
      for (var i = 0; i < n1.length; i++) {
        if (n1[i] !== null && n2[i] !== null && n1[i] !== n2[i]) {
          return false;
        }
      }
      return true;
    }
    function arraysEqual(n1, n2) {
      if (n1 === n2) {
        return true;
      }
      if (n1 == null || n2 == null) {
        return false;
      }
      if (n1.length !== n2.length) {
        return false;
      }
      for (var i = 0; i < n1.length; i++) {
        if (n1[i] !== n2[i]) {
          return false;
        }
      }
      return true;
    }
    function isInt(a) {
      return a % 1 === 0;
    }
    function rightPad(a, size) {
      if (size <= a.length) {
        return a;
      }
      return a + " ".repeat(size - a.length);
    }
    function parseAxisParam(axis, shape) {
      var rank = shape.length;
      axis = axis == null ? shape.map(function(s, i) {
        return i;
      }) : [].concat(axis);
      assert(axis.every(function(ax) {
        return ax >= -rank && ax < rank;
      }), function() {
        return "All values in axis param must be in range [-".concat(rank, ", ").concat(rank, ") but ") + "got axis ".concat(axis);
      });
      assert(axis.every(function(ax) {
        return isInt(ax);
      }), function() {
        return "All values in axis param must be integers but " + "got axis ".concat(axis);
      });
      return axis.map(function(a) {
        return a < 0 ? rank + a : a;
      });
    }
    function squeezeShape(shape, axis) {
      var newShape = [];
      var keptDims = [];
      var isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;
      var axes = axis == null || isEmptyArray ? null : parseAxisParam(axis, shape).sort();
      var j = 0;
      for (var i = 0; i < shape.length; ++i) {
        if (axes != null) {
          if (axes[j] === i && shape[i] !== 1) {
            throw new Error("Can't squeeze axis ".concat(i, " since its dim '").concat(shape[i], "' is not 1"));
          }
          if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {
            newShape.push(shape[i]);
            keptDims.push(i);
          }
          if (axes[j] <= i) {
            j++;
          }
        }
        if (shape[i] !== 1) {
          newShape.push(shape[i]);
          keptDims.push(i);
        }
      }
      return { newShape, keptDims };
    }
    function getTypedArrayFromDType(dtype, size) {
      return getArrayFromDType(dtype, size);
    }
    function getArrayFromDType(dtype, size) {
      var values = null;
      if (dtype == null || dtype === "float32") {
        values = new Float32Array(size);
      } else if (dtype === "int32") {
        values = new Int32Array(size);
      } else if (dtype === "bool") {
        values = new Uint8Array(size);
      } else if (dtype === "string") {
        values = new Array(size);
      } else {
        throw new Error("Unknown data type ".concat(dtype));
      }
      return values;
    }
    function checkConversionForErrors(vals, dtype) {
      for (var i = 0; i < vals.length; i++) {
        var num = vals[i];
        if (isNaN(num) || !isFinite(num)) {
          throw Error("A tensor of type ".concat(dtype, " being uploaded contains ").concat(num, "."));
        }
      }
    }
    function isValidDtype(dtype) {
      return dtype === "bool" || dtype === "complex64" || dtype === "float32" || dtype === "int32" || dtype === "string";
    }
    function bytesPerElement(dtype) {
      if (dtype === "float32" || dtype === "int32") {
        return 4;
      } else if (dtype === "complex64") {
        return 8;
      } else if (dtype === "bool") {
        return 1;
      } else {
        throw new Error("Unknown dtype ".concat(dtype));
      }
    }
    function bytesFromStringArray(arr) {
      if (arr == null) {
        return 0;
      }
      var bytes = 0;
      arr.forEach(function(x) {
        return bytes += x.length;
      });
      return bytes;
    }
    function isString(value) {
      return typeof value === "string" || value instanceof String;
    }
    function isBoolean(value) {
      return typeof value === "boolean";
    }
    function isNumber(value) {
      return typeof value === "number";
    }
    function inferDtype(values) {
      if (Array.isArray(values)) {
        return inferDtype(values[0]);
      }
      if (values instanceof Float32Array) {
        return "float32";
      } else if (values instanceof Int32Array || values instanceof Uint8Array || values instanceof Uint8ClampedArray) {
        return "int32";
      } else if (isNumber(values)) {
        return "float32";
      } else if (isString(values)) {
        return "string";
      } else if (isBoolean(values)) {
        return "bool";
      }
      return "float32";
    }
    function isFunction(f) {
      return !!(f && f.constructor && f.call && f.apply);
    }
    function computeStrides(shape) {
      var rank = shape.length;
      if (rank < 2) {
        return [];
      }
      var strides = new Array(rank - 1);
      strides[rank - 2] = shape[rank - 1];
      for (var i = rank - 3; i >= 0; --i) {
        strides[i] = strides[i + 1] * shape[i + 1];
      }
      return strides;
    }
    function createNestedArray(offset, shape, a, isComplex) {
      if (isComplex === void 0) {
        isComplex = false;
      }
      var ret = new Array();
      if (shape.length === 1) {
        var d = shape[0] * (isComplex ? 2 : 1);
        for (var i = 0; i < d; i++) {
          ret[i] = a[offset + i];
        }
      } else {
        var d = shape[0];
        var rest = shape.slice(1);
        var len = rest.reduce(function(acc, c) {
          return acc * c;
        }) * (isComplex ? 2 : 1);
        for (var i = 0; i < d; i++) {
          ret[i] = createNestedArray(offset + i * len, rest, a, isComplex);
        }
      }
      return ret;
    }
    function toNestedArray(shape, a, isComplex) {
      if (isComplex === void 0) {
        isComplex = false;
      }
      if (shape.length === 0) {
        return a[0];
      }
      var size = shape.reduce(function(acc, c) {
        return acc * c;
      }) * (isComplex ? 2 : 1);
      if (size === 0) {
        return [];
      }
      if (size !== a.length) {
        throw new Error("[".concat(shape, "] does not match the input size ").concat(a.length).concat(isComplex ? " for a complex tensor" : "", "."));
      }
      return createNestedArray(0, shape, a, isComplex);
    }
    function makeOnesTypedArray(size, dtype) {
      var array = makeZerosTypedArray(size, dtype);
      for (var i = 0; i < array.length; i++) {
        array[i] = 1;
      }
      return array;
    }
    function makeZerosTypedArray(size, dtype) {
      if (dtype == null || dtype === "float32" || dtype === "complex64") {
        return new Float32Array(size);
      } else if (dtype === "int32") {
        return new Int32Array(size);
      } else if (dtype === "bool") {
        return new Uint8Array(size);
      } else {
        throw new Error("Unknown data type ".concat(dtype));
      }
    }
    function assertNonNegativeIntegerDimensions(shape) {
      shape.forEach(function(dimSize) {
        assert(Number.isInteger(dimSize) && dimSize >= 0, function() {
          return "Tensor must have a shape comprised of positive integers but got " + "shape [".concat(shape, "].");
        });
      });
    }
    function isPromise(object) {
      return object && object.then && typeof object.then === "function";
    }
    var TENSORFLOWJS_FLAGS_PREFIX = "tfjsflags";
    var Environment = (
      /** @class */
      function() {
        function Environment2(global2) {
          this.global = global2;
          this.flags = {};
          this.flagRegistry = {};
          this.urlFlags = {};
          this.getQueryParams = getQueryParams;
          this.populateURLFlags();
        }
        Environment2.prototype.setPlatform = function(platformName, platform) {
          if (this.platform != null) {
            if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) {
              console.warn("Platform ".concat(this.platformName, " has already been set. ") + "Overwriting the platform with ".concat(platformName, "."));
            }
          }
          this.platformName = platformName;
          this.platform = platform;
        };
        Environment2.prototype.registerFlag = function(flagName, evaluationFn, setHook) {
          this.flagRegistry[flagName] = { evaluationFn, setHook };
          if (this.urlFlags[flagName] != null) {
            var flagValue = this.urlFlags[flagName];
            if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) {
              console.warn("Setting feature override from URL ".concat(flagName, ": ").concat(flagValue, "."));
            }
            this.set(flagName, flagValue);
          }
        };
        Environment2.prototype.getAsync = function(flagName) {
          return __awaiter(this, void 0, void 0, function() {
            var _a, _b;
            return __generator(this, function(_c) {
              switch (_c.label) {
                case 0:
                  if (flagName in this.flags) {
                    return [2, this.flags[flagName]];
                  }
                  _a = this.flags;
                  _b = flagName;
                  return [4, this.evaluateFlag(flagName)];
                case 1:
                  _a[_b] = _c.sent();
                  return [2, this.flags[flagName]];
              }
            });
          });
        };
        Environment2.prototype.get = function(flagName) {
          if (flagName in this.flags) {
            return this.flags[flagName];
          }
          var flagValue = this.evaluateFlag(flagName);
          if (isPromise(flagValue)) {
            throw new Error("Flag ".concat(flagName, " cannot be synchronously evaluated. ") + "Please use getAsync() instead.");
          }
          this.flags[flagName] = flagValue;
          return this.flags[flagName];
        };
        Environment2.prototype.getNumber = function(flagName) {
          return this.get(flagName);
        };
        Environment2.prototype.getBool = function(flagName) {
          return this.get(flagName);
        };
        Environment2.prototype.getString = function(flagName) {
          return this.get(flagName);
        };
        Environment2.prototype.getFlags = function() {
          return this.flags;
        };
        Object.defineProperty(Environment2.prototype, "features", {
          // For backwards compatibility.
          get: function() {
            return this.flags;
          },
          enumerable: false,
          configurable: true
        });
        Environment2.prototype.set = function(flagName, value) {
          if (this.flagRegistry[flagName] == null) {
            throw new Error("Cannot set flag ".concat(flagName, " as it has not been registered."));
          }
          this.flags[flagName] = value;
          if (this.flagRegistry[flagName].setHook != null) {
            this.flagRegistry[flagName].setHook(value);
          }
        };
        Environment2.prototype.evaluateFlag = function(flagName) {
          if (this.flagRegistry[flagName] == null) {
            throw new Error("Cannot evaluate flag '".concat(flagName, "': no evaluation function found."));
          }
          return this.flagRegistry[flagName].evaluationFn();
        };
        Environment2.prototype.setFlags = function(flags) {
          this.flags = Object.assign({}, flags);
        };
        Environment2.prototype.reset = function() {
          this.flags = {};
          this.urlFlags = {};
          this.populateURLFlags();
        };
        Environment2.prototype.populateURLFlags = function() {
          var _this = this;
          if (typeof this.global === "undefined" || typeof this.global.location === "undefined" || typeof this.global.location.search === "undefined") {
            return;
          }
          var urlParams = this.getQueryParams(this.global.location.search);
          if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {
            var keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(",");
            keyValues.forEach(function(keyValue) {
              var _a = __read(keyValue.split(":"), 2), key = _a[0], value = _a[1];
              _this.urlFlags[key] = parseValue(key, value);
            });
          }
        };
        return Environment2;
      }()
    );
    function getQueryParams(queryString) {
      var params = {};
      queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, function(s) {
        var t = [];
        for (var _i = 1; _i < arguments.length; _i++) {
          t[_i - 1] = arguments[_i];
        }
        decodeParam(params, t[0], t[1]);
        return t.join("=");
      });
      return params;
    }
    function decodeParam(params, name, value) {
      params[decodeURIComponent(name)] = decodeURIComponent(value || "");
    }
    function parseValue(flagName, value) {
      var lowerCaseValue = value.toLowerCase();
      if (lowerCaseValue === "true" || lowerCaseValue === "false") {
        return lowerCaseValue === "true";
      } else if ("".concat(+lowerCaseValue) === lowerCaseValue) {
        return +lowerCaseValue;
      } else {
        return value;
      }
    }
    function env() {
      return ENV;
    }
    var ENV = null;
    function setEnvironmentGlobal(environment) {
      ENV = environment;
    }
    var globalNameSpace;
    function getGlobalNamespace() {
      if (globalNameSpace == null) {
        var ns = void 0;
        if (typeof window !== "undefined") {
          ns = window;
        } else if (typeof global !== "undefined") {
          ns = global;
        } else if (typeof process !== "undefined") {
          ns = process;
        } else if (typeof self !== "undefined") {
          ns = self;
        } else {
          throw new Error("Could not find a global object");
        }
        globalNameSpace = ns;
      }
      return globalNameSpace;
    }
    function getGlobalMap() {
      var ns = getGlobalNamespace();
      if (ns._tfGlobals == null) {
        ns._tfGlobals = /* @__PURE__ */ new Map();
      }
      return ns._tfGlobals;
    }
    function getGlobal(key, init) {
      var globalMap = getGlobalMap();
      if (globalMap.has(key)) {
        return globalMap.get(key);
      } else {
        var singleton = init();
        globalMap.set(key, singleton);
        return globalMap.get(key);
      }
    }
    var Abs = "Abs";
    var Acos = "Acos";
    var Acosh = "Acosh";
    var Add = "Add";
    var AddN = "AddN";
    var All = "All";
    var Any = "Any";
    var ArgMax = "ArgMax";
    var ArgMin = "ArgMin";
    var Asin = "Asin";
    var Asinh = "Asinh";
    var Atan = "Atan";
    var Atanh = "Atanh";
    var Atan2 = "Atan2";
    var AvgPool = "AvgPool";
    var AvgPool3D = "AvgPool3D";
    var BatchMatMul = "BatchMatMul";
    var BatchToSpaceND = "BatchToSpaceND";
    var Bincount = "Bincount";
    var BitwiseAnd = "BitwiseAnd";
    var BroadcastArgs = "BroadcastArgs";
    var Cast = "Cast";
    var Ceil = "Ceil";
    var ClipByValue = "ClipByValue";
    var Complex = "Complex";
    var ComplexAbs = "ComplexAbs";
    var Concat = "Concat";
    var Conv2D = "Conv2D";
    var Conv2DBackpropFilter = "Conv2DBackpropFilter";
    var Conv2DBackpropInput = "Conv2DBackpropInput";
    var Conv3D = "Conv3D";
    var Conv3DBackpropInputV2 = "Conv3DBackpropInputV2";
    var Cos = "Cos";
    var Cosh = "Cosh";
    var Cumprod = "Cumprod";
    var Cumsum = "Cumsum";
    var CropAndResize = "CropAndResize";
    var DenseBincount = "DenseBincount";
    var DepthToSpace = "DepthToSpace";
    var DepthwiseConv2dNative = "DepthwiseConv2dNative";
    var DepthwiseConv2dNativeBackpropFilter = "DepthwiseConv2dNativeBackpropFilter";
    var DepthwiseConv2dNativeBackpropInput = "DepthwiseConv2dNativeBackpropInput";
    var Diag = "Diag";
    var Dilation2D = "Dilation2D";
    var RealDiv = "RealDiv";
    var Einsum = "Einsum";
    var Elu = "Elu";
    var Erf = "Erf";
    var Equal = "Equal";
    var Exp = "Exp";
    var ExpandDims = "ExpandDims";
    var Expm1 = "Expm1";
    var FFT = "FFT";
    var Fill = "Fill";
    var FlipLeftRight = "FlipLeftRight";
    var Floor = "Floor";
    var FloorDiv = "FloorDiv";
    var FusedBatchNorm = "FusedBatchNorm";
    var GatherV2 = "GatherV2";
    var GatherNd = "GatherNd";
    var Greater = "Greater";
    var GreaterEqual = "GreaterEqual";
    var Identity = "Identity";
    var IFFT = "IFFT";
    var Imag = "Imag";
    var IsFinite = "IsFinite";
    var IsInf = "IsInf";
    var IsNan = "IsNan";
    var LeakyRelu = "LeakyRelu";
    var Less = "Less";
    var LessEqual = "LessEqual";
    var LinSpace = "LinSpace";
    var Log = "Log";
    var Log1p = "Log1p";
    var LogicalAnd = "LogicalAnd";
    var LogicalNot = "LogicalNot";
    var LogicalOr = "LogicalOr";
    var LRN = "LRN";
    var Max = "Max";
    var Maximum = "Maximum";
    var MaxPool = "MaxPool";
    var MaxPool3D = "MaxPool3D";
    var MaxPoolWithArgmax = "MaxPoolWithArgmax";
    var Mean = "Mean";
    var Min = "Min";
    var Minimum = "Minimum";
    var MirrorPad = "MirrorPad";
    var Mod = "Mod";
    var Multinomial = "Multinomial";
    var Multiply = "Multiply";
    var Neg = "Neg";
    var NotEqual = "NotEqual";
    var NonMaxSuppressionV3 = "NonMaxSuppressionV3";
    var NonMaxSuppressionV4 = "NonMaxSuppressionV4";
    var NonMaxSuppressionV5 = "NonMaxSuppressionV5";
    var OnesLike = "OnesLike";
    var OneHot = "OneHot";
    var Pack = "Pack";
    var PadV2 = "PadV2";
    var Pow = "Pow";
    var Prelu = "Prelu";
    var Prod = "Prod";
    var RaggedGather = "RaggedGather";
    var RaggedRange = "RaggedRange";
    var RaggedTensorToTensor = "RaggedTensorToTensor";
    var Range = "Range";
    var Real = "Real";
    var Reciprocal = "Reciprocal";
    var Relu = "Relu";
    var Reshape = "Reshape";
    var ResizeNearestNeighbor = "ResizeNearestNeighbor";
    var ResizeBilinear = "ResizeBilinear";
    var Relu6 = "Relu6";
    var Reverse = "Reverse";
    var Round = "Round";
    var Rsqrt = "Rsqrt";
    var ScatterNd = "ScatterNd";
    var TensorScatterUpdate = "TensorScatterUpdate";
    var SearchSorted = "SearchSorted";
    var Select = "Select";
    var Selu = "Selu";
    var Slice = "Slice";
    var Sin = "Sin";
    var Sinh = "Sinh";
    var Sign = "Sign";
    var Sigmoid = "Sigmoid";
    var Softplus = "Softplus";
    var Sqrt = "Sqrt";
    var Sum = "Sum";
    var SpaceToBatchND = "SpaceToBatchND";
    var SplitV = "SplitV";
    var Softmax = "Softmax";
    var SparseFillEmptyRows = "SparseFillEmptyRows";
    var SparseReshape = "SparseReshape";
    var SparseSegmentMean = "SparseSegmentMean";
    var SparseSegmentSum = "SparseSegmentSum";
    var SparseToDense = "SparseToDense";
    var SquaredDifference = "SquaredDifference";
    var StaticRegexReplace = "StaticRegexReplace";
    var StridedSlice = "StridedSlice";
    var StringNGrams = "StringNGrams";
    var StringSplit = "StringSplit";
    var StringToHashBucketFast = "StringToHashBucketFast";
    var Sub = "Sub";
    var Tan = "Tan";
    var Tanh = "Tanh";
    var Tile = "Tile";
    var TopK = "TopK";
    var Transform = "Transform";
    var Transpose = "Transpose";
    var Unique = "Unique";
    var Unpack = "Unpack";
    var UnsortedSegmentSum = "UnsortedSegmentSum";
    var ZerosLike = "ZerosLike";
    var Step = "Step";
    var RotateWithOffset = "RotateWithOffset";
    var _FusedMatMul = "_FusedMatMul";
    var FusedConv2D = "FusedConv2D";
    var FusedDepthwiseConv2D = "FusedDepthwiseConv2D";
    function warn() {
      var msg = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        msg[_i] = arguments[_i];
      }
      if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) {
        console.warn.apply(console, __spreadArray([], __read(msg), false));
      }
    }
    var kernelRegistry = getGlobal("kernelRegistry", function() {
      return /* @__PURE__ */ new Map();
    });
    var gradRegistry = getGlobal("gradRegistry", function() {
      return /* @__PURE__ */ new Map();
    });
    function getKernel(kernelName, backendName) {
      var key = makeKey(kernelName, backendName);
      return kernelRegistry.get(key);
    }
    function getGradient(kernelName) {
      return gradRegistry.get(kernelName);
    }
    function getKernelsForBackend(backendName) {
      var it = kernelRegistry.entries();
      var result = [];
      while (true) {
        var _a = it.next(), done = _a.done, value = _a.value;
        if (done) {
          break;
        }
        var _b = __read(value, 2), key = _b[0], config = _b[1];
        var _c = __read(key.split("_"), 1), backend2 = _c[0];
        if (backend2 === backendName) {
          result.push(config);
        }
      }
      return result;
    }
    function makeKey(kernelName, backendName) {
      return "".concat(backendName, "_").concat(kernelName);
    }
    function isTypedArrayBrowser(a) {
      return a instanceof Float32Array || a instanceof Int32Array || a instanceof Uint8Array || a instanceof Uint8ClampedArray;
    }
    var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
    function getDefaultExportFromCjs(x) {
      return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
    }
    function getAugmentedNamespace(n) {
      if (n.__esModule)
        return n;
      var f = n.default;
      if (typeof f == "function") {
        var a = function a2() {
          if (this instanceof a2) {
            var args = [null];
            args.push.apply(args, arguments);
            var Ctor = Function.bind.apply(f, args);
            return new Ctor();
          }
          return f.apply(this, arguments);
        };
        a.prototype = f.prototype;
      } else
        a = {};
      Object.defineProperty(a, "__esModule", { value: true });
      Object.keys(n).forEach(function(k) {
        var d = Object.getOwnPropertyDescriptor(n, k);
        Object.defineProperty(a, k, d.get ? d : {
          enumerable: true,
          get: function() {
            return n[k];
          }
        });
      });
      return a;
    }
    var long = Long$1;
    var wasm = null;
    try {
      wasm = 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 Long$1(low, high, unsigned) {
      this.low = low | 0;
      this.high = high | 0;
      this.unsigned = !!unsigned;
    }
    Long$1.prototype.__isLong__;
    Object.defineProperty(Long$1.prototype, "__isLong__", { value: true });
    function isLong(obj) {
      return (obj && obj["__isLong__"]) === true;
    }
    Long$1.isLong = isLong;
    var INT_CACHE = {};
    var UINT_CACHE = {};
    function fromInt(value, unsigned) {
      var obj, cachedObj, cache;
      if (unsigned) {
        value >>>= 0;
        if (cache = 0 <= value && value < 256) {
          cachedObj = UINT_CACHE[value];
          if (cachedObj)
            return cachedObj;
        }
        obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
        if (cache)
          UINT_CACHE[value] = obj;
        return obj;
      } else {
        value |= 0;
        if (cache = -128 <= value && value < 128) {
          cachedObj = INT_CACHE[value];
          if (cachedObj)
            return cachedObj;
        }
        obj = fromBits(value, value < 0 ? -1 : 0, false);
        if (cache)
          INT_CACHE[value] = obj;
        return obj;
      }
    }
    Long$1.fromInt = fromInt;
    function fromNumber(value, unsigned) {
      if (isNaN(value))
        return unsigned ? UZERO : ZERO;
      if (unsigned) {
        if (value < 0)
          return UZERO;
        if (value >= TWO_PWR_64_DBL)
          return MAX_UNSIGNED_VALUE;
      } else {
        if (value <= -TWO_PWR_63_DBL)
          return MIN_VALUE;
        if (value + 1 >= TWO_PWR_63_DBL)
          return MAX_VALUE;
      }
      if (value < 0)
        return fromNumber(-value, unsigned).neg();
      return fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned);
    }
    Long$1.fromNumber = fromNumber;
    function fromBits(lowBits, highBits, unsigned) {
      return new Long$1(lowBits, highBits, unsigned);
    }
    Long$1.fromBits = fromBits;
    var pow_dbl = Math.pow;
    function fromString(str, unsigned, radix) {
      if (str.length === 0)
        throw Error("empty string");
      if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
        return ZERO;
      if (typeof unsigned === "number") {
        radix = unsigned, unsigned = false;
      } else {
        unsigned = !!unsigned;
      }
      radix = radix || 10;
      if (radix < 2 || 36 < radix)
        throw RangeError("radix");
      var p;
      if ((p = str.indexOf("-")) > 0)
        throw Error("interior hyphen");
      else if (p === 0) {
        return fromString(str.substring(1), unsigned, radix).neg();
      }
      var radixToPower = fromNumber(pow_dbl(radix, 8));
      var result = ZERO;
      for (var i = 0; i < str.length; i += 8) {
        var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
        if (size < 8) {
          var power = fromNumber(pow_dbl(radix, size));
          result = result.mul(power).add(fromNumber(value));
        } else {
          result = result.mul(radixToPower);
          result = result.add(fromNumber(value));
        }
      }
      result.unsigned = unsigned;
      return result;
    }
    Long$1.fromString = fromString;
    function fromValue(val, unsigned) {
      if (typeof val === "number")
        return fromNumber(val, unsigned);
      if (typeof val === "string")
        return fromString(val, unsigned);
      return fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned);
    }
    Long$1.fromValue = fromValue;
    var TWO_PWR_16_DBL = 1 << 16;
    var TWO_PWR_24_DBL = 1 << 24;
    var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
    var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
    var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
    var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
    var ZERO = fromInt(0);
    Long$1.ZERO = ZERO;
    var UZERO = fromInt(0, true);
    Long$1.UZERO = UZERO;
    var ONE = fromInt(1);
    Long$1.ONE = ONE;
    var UONE = fromInt(1, true);
    Long$1.UONE = UONE;
    var NEG_ONE = fromInt(-1);
    Long$1.NEG_ONE = NEG_ONE;
    var MAX_VALUE = fromBits(4294967295 | 0, 2147483647 | 0, false);
    Long$1.MAX_VALUE = MAX_VALUE;
    var MAX_UNSIGNED_VALUE = fromBits(4294967295 | 0, 4294967295 | 0, true);
    Long$1.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
    var MIN_VALUE = fromBits(0, 2147483648 | 0, false);
    Long$1.MIN_VALUE = MIN_VALUE;
    var LongPrototype = Long$1.prototype;
    LongPrototype.toInt = function toInt() {
      return this.unsigned ? this.low >>> 0 : this.low;
    };
    LongPrototype.toNumber = function toNumber() {
      if (this.unsigned)
        return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
      return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
    };
    LongPrototype.toString = function toString(radix) {
      radix = radix || 10;
      if (radix < 2 || 36 < radix)
        throw RangeError("radix");
      if (this.isZero())
        return "0";
      if (this.isNegative()) {
        if (this.eq(MIN_VALUE)) {
          var radixLong = fromNumber(radix), div2 = this.div(radixLong), rem1 = div2.mul(radixLong).sub(this);
          return div2.toString(radix) + rem1.toInt().toString(radix);
        } else
          return "-" + this.neg().toString(radix);
      }
      var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), rem = this;
      var result = "";
      while (true) {
        var remDiv = rem.div(radixToPower), intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, digits = intval.toString(radix);
        rem = remDiv;
        if (rem.isZero())
          return digits + result;
        else {
          while (digits.length < 6)
            digits = "0" + digits;
          result = "" + digits + result;
        }
      }
    };
    LongPrototype.getHighBits = function getHighBits() {
      return this.high;
    };
    LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
      return this.high >>> 0;
    };
    LongPrototype.getLowBits = function getLowBits() {
      return this.low;
    };
    LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
      return this.low >>> 0;
    };
    LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
      if (this.isNegative())
        return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
      var val = this.high != 0 ? this.high : this.low;
      for (var bit = 31; bit > 0; bit--)
        if ((val & 1 << bit) != 0)
          break;
      return this.high != 0 ? bit + 33 : bit + 1;
    };
    LongPrototype.isZero = function isZero() {
      return this.high === 0 && this.low === 0;
    };
    LongPrototype.eqz = LongPrototype.isZero;
    LongPrototype.isNegative = function isNegative() {
      return !this.unsigned && this.high < 0;
    };
    LongPrototype.isPositive = function isPositive() {
      return this.unsigned || this.high >= 0;
    };
    LongPrototype.isOdd = function isOdd() {
      return (this.low & 1) === 1;
    };
    LongPrototype.isEven = function isEven() {
      return (this.low & 1) === 0;
    };
    LongPrototype.equals = function equals(other) {
      if (!isLong(other))
        other = fromValue(other);
      if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
        return false;
      return this.high === other.high && this.low === other.low;
    };
    LongPrototype.eq = LongPrototype.equals;
    LongPrototype.notEquals = function notEquals(other) {
      return !this.eq(
        /* validates */
        other
      );
    };
    LongPrototype.neq = LongPrototype.notEquals;
    LongPrototype.ne = LongPrototype.notEquals;
    LongPrototype.lessThan = function lessThan(other) {
      return this.comp(
        /* validates */
        other
      ) < 0;
    };
    LongPrototype.lt = LongPrototype.lessThan;
    LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
      return this.comp(
        /* validates */
        other
      ) <= 0;
    };
    LongPrototype.lte = LongPrototype.lessThanOrEqual;
    LongPrototype.le = LongPrototype.lessThanOrEqual;
    LongPrototype.greaterThan = function greaterThan(other) {
      return this.comp(
        /* validates */
        other
      ) > 0;
    };
    LongPrototype.gt = LongPrototype.greaterThan;
    LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
      return this.comp(
        /* validates */
        other
      ) >= 0;
    };
    LongPrototype.gte = LongPrototype.greaterThanOrEqual;
    LongPrototype.ge = LongPrototype.greaterThanOrEqual;
    LongPrototype.compare = function compare(other) {
      if (!isLong(other))
        other = fromValue(other);
      if (this.eq(other))
        return 0;
      var thisNeg = this.isNegative(), otherNeg = other.isNegative();
      if (thisNeg && !otherNeg)
        return -1;
      if (!thisNeg && otherNeg)
        return 1;
      if (!this.unsigned)
        return this.sub(other).isNegative() ? -1 : 1;
      return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1;
    };
    LongPrototype.comp = LongPrototype.compare;
    LongPrototype.negate = function negate() {
      if (!this.unsigned && this.eq(MIN_VALUE))
        return MIN_VALUE;
      return this.not().add(ONE);
    };
    LongPrototype.neg = LongPrototype.negate;
    LongPrototype.add = function add2(addend) {
      if (!isLong(addend))
        addend = fromValue(addend);
      var a48 = this.high >>> 16;
      var a32 = this.high & 65535;
      var a16 = this.low >>> 16;
      var a00 = this.low & 65535;
      var b48 = addend.high >>> 16;
      var b32 = addend.high & 65535;
      var b16 = addend.low >>> 16;
      var b00 = addend.low & 65535;
      var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
      c00 += a00 + b00;
      c16 += c00 >>> 16;
      c00 &= 65535;
      c16 += a16 + b16;
      c32 += c16 >>> 16;
      c16 &= 65535;
      c32 += a32 + b32;
      c48 += c32 >>> 16;
      c32 &= 65535;
      c48 += a48 + b48;
      c48 &= 65535;
      return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
    };
    LongPrototype.subtract = function subtract(subtrahend) {
      if (!isLong(subtrahend))
        subtrahend = fromValue(subtrahend);
      return this.add(subtrahend.neg());
    };
    LongPrototype.sub = LongPrototype.subtract;
    LongPrototype.multiply = function multiply(multiplier) {
      if (this.isZero())
        return ZERO;
      if (!isLong(multiplier))
        multiplier = fromValue(multiplier);
      if (wasm) {
        var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
        return fromBits(low, wasm.get_high(), this.unsigned);
      }
      if (multiplier.isZero())
        return ZERO;
      if (this.eq(MIN_VALUE))
        return multiplier.isOdd() ? MIN_VALUE : ZERO;
      if (multiplier.eq(MIN_VALUE))
        return this.isOdd() ? MIN_VALUE : ZERO;
      if (this.isNegative()) {
        if (multiplier.isNegative())
          return this.neg().mul(multiplier.neg());
        else
          return this.neg().mul(multiplier).neg();
      } else if (multiplier.isNegative())
        return this.mul(multiplier.neg()).neg();
      if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
        return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
      var a48 = this.high >>> 16;
      var a32 = this.high & 65535;
      var a16 = this.low >>> 16;
      var a00 = this.low & 65535;
      var b48 = multiplier.high >>> 16;
      var b32 = multiplier.high & 65535;
      var b16 = multiplier.low >>> 16;
      var b00 = multiplier.low & 65535;
      var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
      c00 += a00 * b00;
      c16 += c00 >>> 16;
      c00 &= 65535;
      c16 += a16 * b00;
      c32 += c16 >>> 16;
      c16 &= 65535;
      c16 += a00 * b16;
      c32 += c16 >>> 16;
      c16 &= 65535;
      c32 += a32 * b00;
      c48 += c32 >>> 16;
      c32 &= 65535;
      c32 += a16 * b16;
      c48 += c32 >>> 16;
      c32 &= 65535;
      c32 += a00 * b32;
      c48 += c32 >>> 16;
      c32 &= 65535;
      c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
      c48 &= 65535;
      return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
    };
    LongPrototype.mul = LongPrototype.multiply;
    LongPrototype.divide = function divide(divisor) {
      if (!isLong(divisor))
        divisor = fromValue(divisor);
      if (divisor.isZero())
        throw Error("division by zero");
      if (wasm) {
        if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) {
          return this;
        }
        var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
        return fromBits(low, wasm.get_high(), this.unsigned);
      }
      if (this.isZero())
        return this.unsigned ? UZERO : ZERO;
      var approx, rem, res;
      if (!this.unsigned) {
        if (this.eq(MIN_VALUE)) {
          if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
            return MIN_VALUE;
          else if (divisor.eq(MIN_VALUE))
            return ONE;
          else {
            var halfThis = this.shr(1);
            approx = halfThis.div(divisor).shl(1);
            if (approx.eq(ZERO)) {
              return divisor.isNegative() ? ONE : NEG_ONE;
            } else {
              rem = this.sub(divisor.mul(approx));
              res = approx.add(rem.div(divisor));
              return res;
            }
          }
        } else if (divisor.eq(MIN_VALUE))
          return this.unsigned ? UZERO : ZERO;
        if (this.isNegative()) {
          if (divisor.isNegative())
            return this.neg().div(divisor.neg());
          return this.neg().div(divisor).neg();
        } else if (divisor.isNegative())
          return this.div(divisor.neg()).neg();
        res = ZERO;
      } else {
        if (!divisor.unsigned)
          divisor = divisor.toUnsigned();
        if (divisor.gt(this))
          return UZERO;
        if (divisor.gt(this.shru(1)))
          return UONE;
        res = UZERO;
      }
      rem = this;
      while (rem.gte(divisor)) {
        approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
        var log2 = Math.ceil(Math.log(approx) / Math.LN2), delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48), approxRes = fromNumber(approx), approxRem = approxRes.mul(divisor);
        while (approxRem.isNegative() || approxRem.gt(rem)) {
          approx -= delta;
          approxRes = fromNumber(approx, this.unsigned);
          approxRem = approxRes.mul(divisor);
        }
        if (approxRes.isZero())
          approxRes = ONE;
        res = res.add(approxRes);
        rem = rem.sub(approxRem);
      }
      return res;
    };
    LongPrototype.div = LongPrototype.divide;
    LongPrototype.modulo = function modulo(divisor) {
      if (!isLong(divisor))
        divisor = fromValue(divisor);
      if (wasm) {
        var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
        return fromBits(low, wasm.get_high(), this.unsigned);
      }
      return this.sub(this.div(divisor).mul(divisor));
    };
    LongPrototype.mod = LongPrototype.modulo;
    LongPrototype.rem = LongPrototype.modulo;
    LongPrototype.not = function not() {
      return fromBits(~this.low, ~this.high, this.unsigned);
    };
    LongPrototype.and = function and(other) {
      if (!isLong(other))
        other = fromValue(other);
      return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
    };
    LongPrototype.or = function or(other) {
      if (!isLong(other))
        other = fromValue(other);
      return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
    };
    LongPrototype.xor = function xor(other) {
      if (!isLong(other))
        other = fromValue(other);
      return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
    };
    LongPrototype.shiftLeft = function shiftLeft(numBits) {
      if (isLong(numBits))
        numBits = numBits.toInt();
      if ((numBits &= 63) === 0)
        return this;
      else if (numBits < 32)
        return fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned);
      else
        return fromBits(0, this.low << numBits - 32, this.unsigned);
    };
    LongPrototype.shl = LongPrototype.shiftLeft;
    LongPrototype.shiftRight = function shiftRight(numBits) {
      if (isLong(numBits))
        numBits = numBits.toInt();
      if ((numBits &= 63) === 0)
        return this;
      else if (numBits < 32)
        return fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned);
      else
        return fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned);
    };
    LongPrototype.shr = LongPrototype.shiftRight;
    LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
      if (isLong(numBits))
        numBits = numBits.toInt();
      numBits &= 63;
      if (numBits === 0)
        return this;
      else {
        var high = this.high;
        if (numBits < 32) {
          var low = this.low;
          return fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits, this.unsigned);
        } else if (numBits === 32)
          return fromBits(high, 0, this.unsigned);
        else
          return fromBits(high >>> numBits - 32, 0, this.unsigned);
      }
    };
    LongPrototype.shru = LongPrototype.shiftRightUnsigned;
    LongPrototype.shr_u = LongPrototype.shiftRightUnsigned;
    LongPrototype.toSigned = function toSigned() {
      if (!this.unsigned)
        return this;
      return fromBits(this.low, this.high, false);
    };
    LongPrototype.toUnsigned = function toUnsigned() {
      if (this.unsigned)
        return this;
      return fromBits(this.low, this.high, true);
    };
    LongPrototype.toBytes = function toBytes(le) {
      return le ? this.toBytesLE() : this.toBytesBE();
    };
    LongPrototype.toBytesLE = function toBytesLE() {
      var hi = this.high, lo = this.low;
      return [
        lo & 255,
        lo >>> 8 & 255,
        lo >>> 16 & 255,
        lo >>> 24,
        hi & 255,
        hi >>> 8 & 255,
        hi >>> 16 & 255,
        hi >>> 24
      ];
    };
    LongPrototype.toBytesBE = function toBytesBE() {
      var hi = this.high, lo = this.low;
      return [
        hi >>> 24,
        hi >>> 16 & 255,
        hi >>> 8 & 255,
        hi & 255,
        lo >>> 24,
        lo >>> 16 & 255,
        lo >>> 8 & 255,
        lo & 255
      ];
    };
    Long$1.fromBytes = function fromBytes(bytes, unsigned, le) {
      return le ? Long$1.fromBytesLE(bytes, unsigned) : Long$1.fromBytesBE(bytes, unsigned);
    };
    Long$1.fromBytesLE = function fromBytesLE(bytes, unsigned) {
      return new Long$1(bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, unsigned);
    };
    Long$1.fromBytesBE = function fromBytesBE(bytes, unsigned) {
      return new Long$1(bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], unsigned);
    };
    var long$1 = /* @__PURE__ */ getDefaultExportFromCjs(long);
    var LongExports = /* @__PURE__ */ _mergeNamespaces({
      __proto__: null,
      default: long$1
    }, [long]);
    var Long = (
      // tslint:disable-next-line
      long$1 || LongExports
    );
    function hexToLong(hex) {
      return Long.fromString(hex, true, 16);
    }
    hexToLong("c3a5c85c97cb3127");
    hexToLong("b492b66fbe98f273");
    hexToLong("9ae16a3b2f90404f");
    function noConversionNeeded(a, dtype) {
      return a instanceof Float32Array && dtype === "float32" || a instanceof Int32Array && dtype === "int32" || a instanceof Uint8Array && dtype === "bool";
    }
    function toTypedArray(a, dtype) {
      if (dtype === "string") {
        throw new Error("Cannot convert a string[] to a TypedArray");
      }
      if (Array.isArray(a)) {
        a = flatten(a);
      }
      if (env().getBool("DEBUG")) {
        checkConversionForErrors(a, dtype);
      }
      if (noConversionNeeded(a, dtype)) {
        return a;
      }
      if (dtype == null || dtype === "float32" || dtype === "complex64") {
        return new Float32Array(a);
      } else if (dtype === "int32") {
        return new Int32Array(a);
      } else if (dtype === "bool") {
        var bool = new Uint8Array(a.length);
        for (var i = 0; i < bool.length; ++i) {
          if (Math.round(a[i]) !== 0) {
            bool[i] = 1;
          }
        }
        return bool;
      } else {
        throw new Error("Unknown data type ".concat(dtype));
      }
    }
    function now() {
      return env().platform.now();
    }
    function encodeString(s, encoding) {
      if (encoding === void 0) {
        encoding = "utf-8";
      }
      encoding = encoding || "utf-8";
      return env().platform.encode(s, encoding);
    }
    function decodeString(bytes, encoding) {
      if (encoding === void 0) {
        encoding = "utf-8";
      }
      encoding = encoding || "utf-8";
      return env().platform.decode(bytes, encoding);
    }
    function isTypedArray(a) {
      if (env().platform.isTypedArray != null) {
        return env().platform.isTypedArray(a);
      } else {
        return isTypedArrayBrowser(a);
      }
    }
    function flatten(arr, result, skipTypedArray) {
      var e_1, _a;
      if (result === void 0) {
        result = [];
      }
      if (skipTypedArray === void 0) {
        skipTypedArray = false;
      }
      if (result == null) {
        result = [];
      }
      if (typeof arr === "boolean" || typeof arr === "number" || typeof arr === "string" || isPromise(arr) || arr == null || isTypedArray(arr) && skipTypedArray) {
        result.push(arr);
      } else if (Array.isArray(arr) || isTypedArray(arr)) {
        for (var i = 0; i < arr.length; ++i) {
          flatten(arr[i], result, skipTypedArray);
        }
      } else {
        var maxIndex = -1;
        try {
          for (var _b = __values(Object.keys(arr)), _c = _b.next(); !_c.done; _c = _b.next()) {
            var key = _c.value;
            if (/^([1-9]+[0-9]*|0)$/.test(key)) {
              maxIndex = Math.max(maxIndex, Number(key));
            }
          }
        } catch (e_1_1) {
          e_1 = { error: e_1_1 };
        } finally {
          try {
            if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
          } finally {
            if (e_1) throw e_1.error;
          }
        }
        for (var i = 0; i <= maxIndex; i++) {
          flatten(arr[i], result, skipTypedArray);
        }
      }
      return result;
    }
    var Profiler = (
      /** @class */
      function() {
        function Profiler2(backendTimer, logger) {
          this.backendTimer = backendTimer;
          this.logger = logger;
          if (logger == null) {
            this.logger = new Logger();
          }
        }
        Profiler2.prototype.profileKernel = function(kernelName, inputs, f) {
          var e_1, _a;
          var outputs;
          var holdResultWrapperFn = function() {
            outputs = f();
          };
          var timer;
          var start = now();
          if (this.backendTimer.timerAvailable()) {
            timer = this.backendTimer.time(holdResultWrapperFn);
          } else {
            holdResultWrapperFn();
            try {
              for (var outputs_1 = __values(outputs), outputs_1_1 = outputs_1.next(); !outputs_1_1.done; outputs_1_1 = outputs_1.next()) {
                var output = outputs_1_1.value;
                output.dataSync();
              }
            } catch (e_1_1) {
              e_1 = { error: e_1_1 };
            } finally {
              try {
                if (outputs_1_1 && !outputs_1_1.done && (_a = outputs_1.return)) _a.call(outputs_1);
              } finally {
                if (e_1) throw e_1.error;
              }
            }
            timer = Promise.resolve({ kernelMs: now() - start });
          }
          if (env().getBool("CHECK_COMPUTATION_FOR_ERRORS")) {
            var _loop_1 = function(i2) {
              var output2 = outputs[i2];
              output2.data().then(function(tensorVals) {
                checkComputationForErrors(tensorVals, output2.dtype, kernelName);
              });
            };
            for (var i = 0; i < outputs.length; i++) {
              _loop_1(i);
            }
          }
          var kernelProfile = {
            kernelName,
            outputs,
            inputs,
            timeMs: timer.then(function(timing) {
              return timing.kernelMs;
            }),
            extraInfo: timer.then(function(timing) {
              return timing.getExtraProfileInfo != null ? timing.getExtraProfileInfo() : "";
            })
          };
          return kernelProfile;
        };
        Profiler2.prototype.logKernelProfile = function(kernelProfile) {
          var _this = this;
          var kernelName = kernelProfile.kernelName, outputs = kernelProfile.outputs, timeMs = kernelProfile.timeMs, inputs = kernelProfile.inputs, extraInfo = kernelProfile.extraInfo;
          outputs.forEach(function(result) {
            Promise.all([result.data(), timeMs, extraInfo]).then(function(valueContainer) {
              _this.logger.logKernelProfile(kernelName, result, valueContainer[0], valueContainer[1], inputs, valueContainer[2]);
            });
          });
        };
        return Profiler2;
      }()
    );
    function checkComputationForErrors(vals, dtype, kernelName) {
      if (dtype !== "float32") {
        return false;
      }
      for (var i = 0; i < vals.length; i++) {
        var num = vals[i];
        if (isNaN(num) || !isFinite(num)) {
          console.warn("Found ".concat(num, " in the result of '").concat(kernelName, "'"));
          return true;
        }
      }
      return false;
    }
    var Logger = (
      /** @class */
      function() {
        function Logger2() {
        }
        Logger2.prototype.logKernelProfile = function(name, result, vals, timeMs, inputs, extraInfo) {
          var time = typeof timeMs === "number" ? rightPad("".concat(timeMs, "ms"), 9) : timeMs["error"];
          var paddedName = rightPad(name, 25);
          var rank = result.rank;
          var size = result.size;
          var shape = rightPad(result.shape.toString(), 14);
          var inputShapesDescription = "";
          for (var name_1 in inputs) {
            var input = inputs[name_1];
            if (input != null) {
              var inputShape = input.shape || result.shape;
              var inputRank = inputShape.length;
              inputShapesDescription += "".concat(name_1, ": ").concat(inputRank, "D ").concat(inputRank > 0 ? inputShape : "", " ");
            }
          }
          console.log("%c".concat(paddedName, "	%c").concat(time, "	%c").concat(rank, "D ").concat(shape, "	%c").concat(size, "	%c").concat(inputShapesDescription, "	%c").concat(extraInfo), "font-weight:bold", "color:red", "color:blue", "color: orange", "color: green", "color: steelblue");
        };
        return Logger2;
      }()
    );
    function getFilteredNodesXToY(tape, xs, y) {
      var tensorsFromX = {};
      var nodesFromX = {};
      for (var i = 0; i < xs.length; i++) {
        tensorsFromX[xs[i].id] = true;
      }
      for (var i = 0; i < tape.length; i++) {
        var node = tape[i];
        var nodeInputs = node.inputs;
        for (var inputName in nodeInputs) {
          var input = nodeInputs[inputName];
          var anyInputFromX = false;
          for (var j = 0; j < xs.length; j++) {
            if (tensorsFromX[input.id]) {
              node.outputs.forEach(function(output) {
                return tensorsFromX[output.id] = true;
              });
              anyInputFromX = true;
              nodesFromX[node.id] = true;
              break;
            }
          }
          if (anyInputFromX) {
            break;
          }
        }
      }
      var tensorsLeadToY = {};
      tensorsLeadToY[y.id] = true;
      var nodesToY = {};
      for (var i = tape.length - 1; i >= 0; i--) {
        var node = tape[i];
        var nodeInputs = node.inputs;
        for (var j = 0; j < node.outputs.length; j++) {
          if (tensorsLeadToY[node.outputs[j].id]) {
            for (var inputName in nodeInputs) {
              tensorsLeadToY[nodeInputs[inputName].id] = true;
              nodesToY[node.id] = true;
            }
            break;
          }
        }
      }
      var filteredTape = [];
      for (var i = 0; i < tape.length; i++) {
        var node = tape[i];
        if (nodesFromX[node.id] && nodesToY[node.id]) {
          var prunedInputs = {};
          for (var inputName in node.inputs) {
            var nodeInput = node.inputs[inputName];
            if (tensorsFromX[nodeInput.id]) {
              prunedInputs[inputName] = nodeInput;
            }
          }
          var prunedNode = Object.assign({}, node);
          prunedNode.inputs = prunedInputs;
          prunedNode.outputs = node.outputs;
          filteredTape.push(prunedNode);
        }
      }
      return filteredTape;
    }
    function backpropagateGradients(tensorAccumulatedGradientMap, filteredTape, tidy2, add2) {
      var _loop_1 = function(i2) {
        var node = filteredTape[i2];
        var dys = [];
        node.outputs.forEach(function(o) {
          var gradTensor = tensorAccumulatedGradientMap[o.id];
          if (gradTensor != null) {
            dys.push(gradTensor);
          } else {
            dys.push(null);
          }
        });
        if (node.gradient == null) {
          throw new Error("Cannot compute gradient: gradient function not found " + "for ".concat(node.kernelName, "."));
        }
        var inputGradients = node.gradient(dys);
        var _loop_2 = function(inputName2) {
          if (!(inputName2 in inputGradients)) {
            throw new Error("Cannot backprop through input ".concat(inputName2, ". ") + "Available gradients found: ".concat(Object.keys(inputGradients), "."));
          }
          var dx = tidy2(function() {
            return inputGradients[inputName2]();
          });
          if (dx.dtype !== "float32") {
            throw new Error("Error in gradient for op ".concat(node.kernelName, ". The gradient of input ") + "".concat(inputName2, " must have 'float32' dtype, but has '").concat(dx.dtype, "'"));
          }
          var x = node.inputs[inputName2];
          if (!arraysEqual(dx.shape, x.shape)) {
            throw new Error("Error in gradient for op ".concat(node.kernelName, ". The gradient of input ") + "'".concat(inputName2, "' has shape '").concat(dx.shape, "', which does not match ") + "the shape of the input '".concat(x.shape, "'"));
          }
          if (tensorAccumulatedGradientMap[x.id] == null) {
            tensorAccumulatedGradientMap[x.id] = dx;
          } else {
            var curGradient = tensorAccumulatedGradientMap[x.id];
            tensorAccumulatedGradientMap[x.id] = add2(curGradient, dx);
            curGradient.dispose();
          }
        };
        for (var inputName in node.inputs) {
          _loop_2(inputName);
        }
      };
      for (var i = filteredTape.length - 1; i >= 0; i--) {
        _loop_1(i);
      }
    }
    var FORMAT_LIMIT_NUM_VALS = 20;
    var FORMAT_NUM_FIRST_LAST_VALS = 3;
    var FORMAT_NUM_SIG_DIGITS = 7;
    function tensorToString(vals, shape, dtype, verbose) {
      var strides = computeStrides(shape);
      var padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides);
      var rank = shape.length;
      var valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol);
      var lines = ["Tensor"];
      if (verbose) {
        lines.push("  dtype: ".concat(dtype));
        lines.push("  rank: ".concat(rank));
        lines.push("  shape: [".concat(shape, "]"));
        lines.push("  values:");
      }
      lines.push(valsLines.map(function(l) {
        return "    " + l;
      }).join("\n"));
      return lines.join("\n");
    }
    function computeMaxSizePerColumn(vals, shape, dtype, strides) {
      var n = sizeFromShape(shape);
      var numCols = strides[strides.length - 1];
      var padPerCol = new Array(numCols).fill(0);
      var rank = shape.length;
      var valuesOrTuples = dtype === "complex64" ? createComplexTuples(vals) : vals;
      if (rank > 1) {
        for (var row = 0; row < n / numCols; row++) {
          var offset = row * numCols;
          for (var j = 0; j < numCols; j++) {
            padPerCol[j] = Math.max(padPerCol[j], valToString(valuesOrTuples[offset + j], 0, dtype).length);
          }
        }
      }
      return padPerCol;
    }
    function valToString(val, pad2, dtype) {
      var valStr;
      if (Array.isArray(val)) {
        valStr = "".concat(parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS)), " + ") + "".concat(parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS)), "j");
      } else if (isString(val)) {
        valStr = "'".concat(val, "'");
      } else if (dtype === "bool") {
        valStr = boolNumToString(val);
      } else {
        valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString();
      }
      return rightPad(valStr, pad2);
    }
    function boolNumToString(v) {
      return v === 0 ? "false" : "true";
    }
    function subTensorToString(vals, shape, dtype, strides, padPerCol, isLast) {
      if (isLast === void 0) {
        isLast = true;
      }
      var storagePerElement = dtype === "complex64" ? 2 : 1;
      var size = shape[0];
      var rank = shape.length;
      if (rank === 0) {
        if (dtype === "complex64") {
          var complexTuple = createComplexTuples(vals);
          return [valToString(complexTuple[0], 0, dtype)];
        }
        if (dtype === "bool") {
          return [boolNumToString(vals[0])];
        }
        return [vals[0].toString()];
      }
      if (rank === 1) {
        if (size > FORMAT_LIMIT_NUM_VALS) {
          var firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement;
          var firstVals = Array.from(vals.slice(0, firstValsSize));
          var lastVals = Array.from(vals.slice((size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement, size * storagePerElement));
          if (dtype === "complex64") {
            firstVals = createComplexTuples(firstVals);
            lastVals = createComplexTuples(lastVals);
          }
          return [
            "[" + firstVals.map(function(x, i2) {
              return valToString(x, padPerCol[i2], dtype);
            }).join(", ") + ", ..., " + lastVals.map(function(x, i2) {
              return valToString(x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i2], dtype);
            }).join(", ") + "]"
          ];
        }
        var displayVals = dtype === "complex64" ? createComplexTuples(vals) : Array.from(vals);
        return [
          "[" + displayVals.map(function(x, i2) {
            return valToString(x, padPerCol[i2], dtype);
          }).join(", ") + "]"
        ];
      }
      var subshape = shape.slice(1);
      var substrides = strides.slice(1);
      var stride = strides[0] * storagePerElement;
      var lines = [];
      if (size > FORMAT_LIMIT_NUM_VALS) {
        for (var i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {
          var start = i * stride;
          var end = start + stride;
          lines.push.apply(lines, __spreadArray([], __read(subTensorToString(
            vals.slice(start, end),
            subshape,
            dtype,
            substrides,
            padPerCol,
            false
            /* isLast */
          )), false));
        }
        lines.push("...");
        for (var i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {
          var start = i * stride;
          var end = start + stride;
          lines.push.apply(lines, __spreadArray([], __read(subTensorToString(
            vals.slice(start, end),
            subshape,
            dtype,
            substrides,
            padPerCol,
            i === size - 1
            /* isLast */
          )), false));
        }
      } else {
        for (var i = 0; i < size; i++) {
          var start = i * stride;
          var end = start + stride;
          lines.push.apply(lines, __spreadArray([], __read(subTensorToString(
            vals.slice(start, end),
            subshape,
            dtype,
            substrides,
            padPerCol,
            i === size - 1
            /* isLast */
          )), false));
        }
      }
      var sep = rank === 2 ? "," : "";
      lines[0] = "[" + (size > 0 ? lines[0] + sep : "");
      for (var i = 1; i < lines.length - 1; i++) {
        lines[i] = " " + lines[i] + sep;
      }
      var newLineSep = ",\n";
      for (var i = 2; i < rank; i++) {
        newLineSep += "\n";
      }
      lines[lines.length - 1] = " " + lines[lines.length - 1] + "]" + (isLast ? "" : newLineSep);
      return lines;
    }
    function createComplexTuples(vals) {
      var complexTuples = [];
      for (var i = 0; i < vals.length; i += 2) {
        complexTuples.push([vals[i], vals[i + 1]]);
      }
      return complexTuples;
    }
    var TensorBuffer = (
      /** @class */
      function() {
        function TensorBuffer2(shape, dtype, values) {
          var _this = this;
          this.dtype = dtype;
          this.shape = shape.slice();
          this.size = sizeFromShape(shape);
          if (values != null) {
            var n_1 = values.length;
            assert(n_1 === this.size, function() {
              return "Length of values '".concat(n_1, "' does not match the size ") + "inferred by the shape '".concat(_this.size, "'.");
            });
          }
          if (dtype === "complex64") {
            throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");
          }
          this.values = values || getArrayFromDType(dtype, this.size);
          this.strides = computeStrides(shape);
        }
        TensorBuffer2.prototype.set = function(value) {
          var _this = this;
          var locs = [];
          for (var _i = 1; _i < arguments.length; _i++) {
            locs[_i - 1] = arguments[_i];
          }
          if (locs.length === 0) {
            locs = [0];
          }
          assert(locs.length === this.rank, function() {
            return "The number of provided coordinates (".concat(locs.length, ") must ") + "match the rank (".concat(_this.rank, ")");
          });
          var index = this.locToIndex(locs);
          this.values[index] = value;
        };
        TensorBuffer2.prototype.get = function() {
          var e_1, _b;
          var locs = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            locs[_i] = arguments[_i];
          }
          if (locs.length === 0) {
            locs = [0];
          }
          var i = 0;
          try {
            for (var locs_1 = __values(locs), locs_1_1 = locs_1.next(); !locs_1_1.done; locs_1_1 = locs_1.next()) {
              var loc = locs_1_1.value;
              if (loc < 0 || loc >= this.shape[i]) {
                var msg = "Requested out of range element at ".concat(locs, ". ") + "  Buffer shape=".concat(this.shape);
                throw new Error(msg);
              }
              i++;
            }
          } catch (e_1_1) {
            e_1 = { error: e_1_1 };
          } finally {
            try {
              if (locs_1_1 && !locs_1_1.done && (_b = locs_1.return)) _b.call(locs_1);
            } finally {
              if (e_1) throw e_1.error;
            }
          }
          var index = locs[locs.length - 1];
          for (var i_1 = 0; i_1 < locs.length - 1; ++i_1) {
            index += this.strides[i_1] * locs[i_1];
          }
          return this.values[index];
        };
        TensorBuffer2.prototype.locToIndex = function(locs) {
          if (this.rank === 0) {
            return 0;
          } else if (this.rank === 1) {
            return locs[0];
          }
          var index = locs[locs.length - 1];
          for (var i = 0; i < locs.length - 1; ++i) {
            index += this.strides[i] * locs[i];
          }
          return index;
        };
        TensorBuffer2.prototype.indexToLoc = function(index) {
          if (this.rank === 0) {
            return [];
          } else if (this.rank === 1) {
            return [index];
          }
          var locs = new Array(this.shape.length);
          for (var i = 0; i < locs.length - 1; ++i) {
            locs[i] = Math.floor(index / this.strides[i]);
            index -= locs[i] * this.strides[i];
          }
          locs[locs.length - 1] = index;
          return locs;
        };
        Object.defineProperty(TensorBuffer2.prototype, "rank", {
          get: function() {
            return this.shape.length;
          },
          enumerable: false,
          configurable: true
        });
        TensorBuffer2.prototype.toTensor = function() {
          return trackerFn().makeTensor(this.values, this.shape, this.dtype);
        };
        return TensorBuffer2;
      }()
    );
    var trackerFn = null;
    var opHandler = null;
    function setTensorTracker(fn) {
      trackerFn = fn;
    }
    var Tensor = (
      /** @class */
      function() {
        function Tensor2(shape, dtype, dataId, id) {
          this.kept = false;
          this.isDisposedInternal = false;
          this.shape = shape.slice();
          this.dtype = dtype || "float32";
          this.size = sizeFromShape(shape);
          this.strides = computeStrides(shape);
          this.dataId = dataId;
          this.id = id;
          this.rankType = this.rank < 5 ? this.rank.toString() : "higher";
        }
        Object.defineProperty(Tensor2.prototype, "rank", {
          get: function() {
            return this.shape.length;
          },
          enumerable: false,
          configurable: true
        });
        Tensor2.prototype.buffer = function() {
          return __awaiter(this, void 0, void 0, function() {
            var vals;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  return [4, this.data()];
                case 1:
                  vals = _b.sent();
                  return [2, opHandler.buffer(this.shape, this.dtype, vals)];
              }
            });
          });
        };
        Tensor2.prototype.bufferSync = function() {
          return opHandler.buffer(this.shape, this.dtype, this.dataSync());
        };
        Tensor2.prototype.array = function() {
          return __awaiter(this, void 0, void 0, function() {
            var vals;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  return [4, this.data()];
                case 1:
                  vals = _b.sent();
                  return [2, toNestedArray(this.shape, vals, this.dtype === "complex64")];
              }
            });
          });
        };
        Tensor2.prototype.arraySync = function() {
          return toNestedArray(this.shape, this.dataSync(), this.dtype === "complex64");
        };
        Tensor2.prototype.data = function() {
          return __awaiter(this, void 0, void 0, function() {
            var data, bytes;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  this.throwIfDisposed();
                  data = trackerFn().read(this.dataId);
                  if (!(this.dtype === "string")) return [3, 2];
                  return [4, data];
                case 1:
                  bytes = _b.sent();
                  try {
                    return [2, bytes.map(function(b) {
                      return decodeString(b);
                    })];
                  } catch (_a) {
                    throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");
                  }
                  _b.label = 2;
                case 2:
                  return [2, data];
              }
            });
          });
        };
        Tensor2.prototype.dataToGPU = function(options) {
          this.throwIfDisposed();
          return trackerFn().readToGPU(this.dataId, options);
        };
        Tensor2.prototype.dataSync = function() {
          this.throwIfDisposed();
          var data = trackerFn().readSync(this.dataId);
          if (this.dtype === "string") {
            try {
              return data.map(function(b) {
                return decodeString(b);
              });
            } catch (_a) {
              throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");
            }
          }
          return data;
        };
        Tensor2.prototype.bytes = function() {
          return __awaiter(this, void 0, void 0, function() {
            var data;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  this.throwIfDisposed();
                  return [4, trackerFn().read(this.dataId)];
                case 1:
                  data = _b.sent();
                  if (this.dtype === "string") {
                    return [2, data];
                  } else {
                    return [2, new Uint8Array(data.buffer)];
                  }
              }
            });
          });
        };
        Tensor2.prototype.dispose = function() {
          if (this.isDisposed) {
            return;
          }
          if (this.kerasMask) {
            this.kerasMask.dispose();
          }
          trackerFn().disposeTensor(this);
          this.isDisposedInternal = true;
        };
        Object.defineProperty(Tensor2.prototype, "isDisposed", {
          get: function() {
            return this.isDisposedInternal;
          },
          enumerable: false,
          configurable: true
        });
        Tensor2.prototype.throwIfDisposed = function() {
          if (this.isDisposed) {
            throw new Error("Tensor is disposed.");
          }
        };
        Tensor2.prototype.print = function(verbose) {
          if (verbose === void 0) {
            verbose = false;
          }
          return opHandler.print(this, verbose);
        };
        Tensor2.prototype.clone = function() {
          this.throwIfDisposed();
          return opHandler.clone(this);
        };
        Tensor2.prototype.toString = function(verbose) {
          if (verbose === void 0) {
            verbose = false;
          }
          var vals = this.dataSync();
          return tensorToString(vals, this.shape, this.dtype, verbose);
        };
        Tensor2.prototype.cast = function(dtype) {
          this.throwIfDisposed();
          return opHandler.cast(this, dtype);
        };
        Tensor2.prototype.variable = function(trainable, name, dtype) {
          if (trainable === void 0) {
            trainable = true;
          }
          this.throwIfDisposed();
          return trackerFn().makeVariable(this, trainable, name, dtype);
        };
        return Tensor2;
      }()
    );
    Object.defineProperty(Tensor, Symbol.hasInstance, {
      value: function(instance) {
        return !!instance && instance.data != null && instance.dataSync != null && instance.throwIfDisposed != null;
      }
    });
    function getGlobalTensorClass() {
      return getGlobal("Tensor", function() {
        return Tensor;
      });
    }
    getGlobalTensorClass();
    var Variable = (
      /** @class */
      function(_super) {
        __extends(Variable2, _super);
        function Variable2(initialValue, trainable, name, tensorId) {
          var _this = _super.call(this, initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId) || this;
          _this.trainable = trainable;
          _this.name = name;
          return _this;
        }
        Variable2.prototype.assign = function(newValue) {
          if (newValue.dtype !== this.dtype) {
            throw new Error("dtype of the new value (".concat(newValue.dtype, ") and ") + "previous value (".concat(this.dtype, ") must match"));
          }
          if (!arraysEqual(newValue.shape, this.shape)) {
            throw new Error("shape of the new value (".concat(newValue.shape, ") and ") + "previous value (".concat(this.shape, ") must match"));
          }
          trackerFn().disposeTensor(this);
          this.dataId = newValue.dataId;
          trackerFn().incRef(
            this,
            null
            /* backend */
          );
        };
        Variable2.prototype.dispose = function() {
          trackerFn().disposeVariable(this);
          this.isDisposedInternal = true;
        };
        return Variable2;
      }(Tensor)
    );
    Object.defineProperty(Variable, Symbol.hasInstance, {
      value: function(instance) {
        return instance instanceof Tensor && instance.assign != null && instance.assign instanceof Function;
      }
    });
    var Rank;
    (function(Rank2) {
      Rank2["R0"] = "R0";
      Rank2["R1"] = "R1";
      Rank2["R2"] = "R2";
      Rank2["R3"] = "R3";
      Rank2["R4"] = "R4";
      Rank2["R5"] = "R5";
      Rank2["R6"] = "R6";
    })(Rank || (Rank = {}));
    var UpcastInt32AndMap;
    (function(UpcastInt32AndMap2) {
      UpcastInt32AndMap2["float32"] = "float32";
      UpcastInt32AndMap2["int32"] = "int32";
      UpcastInt32AndMap2["bool"] = "int32";
      UpcastInt32AndMap2["complex64"] = "complex64";
    })(UpcastInt32AndMap || (UpcastInt32AndMap = {}));
    var UpcastBoolAndMap;
    (function(UpcastBoolAndMap2) {
      UpcastBoolAndMap2["float32"] = "float32";
      UpcastBoolAndMap2["int32"] = "int32";
      UpcastBoolAndMap2["bool"] = "bool";
      UpcastBoolAndMap2["complex64"] = "complex64";
    })(UpcastBoolAndMap || (UpcastBoolAndMap = {}));
    var UpcastFloat32AndMap;
    (function(UpcastFloat32AndMap2) {
      UpcastFloat32AndMap2["float32"] = "float32";
      UpcastFloat32AndMap2["int32"] = "float32";
      UpcastFloat32AndMap2["bool"] = "float32";
      UpcastFloat32AndMap2["complex64"] = "complex64";
    })(UpcastFloat32AndMap || (UpcastFloat32AndMap = {}));
    var UpcastComplex64AndMap;
    (function(UpcastComplex64AndMap2) {
      UpcastComplex64AndMap2["float32"] = "complex64";
      UpcastComplex64AndMap2["int32"] = "complex64";
      UpcastComplex64AndMap2["bool"] = "complex64";
      UpcastComplex64AndMap2["complex64"] = "complex64";
    })(UpcastComplex64AndMap || (UpcastComplex64AndMap = {}));
    var upcastTypeMap = {
      "float32": UpcastFloat32AndMap,
      "int32": UpcastInt32AndMap,
      "bool": UpcastBoolAndMap,
      "complex64": UpcastComplex64AndMap
    };
    function upcastType(typeA, typeB) {
      if (typeA === "string" || typeB === "string") {
        if (typeA === "string" && typeB === "string") {
          return "string";
        }
        throw new Error("Can not upcast ".concat(typeA, " with ").concat(typeB));
      }
      return upcastTypeMap[typeA][typeB];
    }
    function isWebGLData(values) {
      return values != null && typeof values === "object" && "texture" in values && values.texture instanceof WebGLTexture;
    }
    function isWebGPUData(values) {
      return typeof GPUBuffer !== "undefined" && values != null && typeof values === "object" && "buffer" in values && values.buffer instanceof GPUBuffer;
    }
    function makeTypesMatch(a, b) {
      if (a.dtype === b.dtype) {
        return [a, b];
      }
      var dtype = upcastType(a.dtype, b.dtype);
      return [a.cast(dtype), b.cast(dtype)];
    }
    function assertTypesMatch(a, b) {
      assert(a.dtype === b.dtype, function() {
        return "The dtypes of the first(".concat(a.dtype, ") and") + " second(".concat(b.dtype, ") input must match");
      });
    }
    function getTensorsInContainer(result) {
      var list = [];
      var seen = /* @__PURE__ */ new Set();
      walkTensorContainer(result, list, seen);
      return list;
    }
    function walkTensorContainer(container, list, seen) {
      if (container == null) {
        return;
      }
      if (container instanceof Tensor) {
        list.push(container);
        return;
      }
      if (!isIterable(container)) {
        return;
      }
      var iterable = container;
      for (var k in iterable) {
        var val = iterable[k];
        if (!seen.has(val)) {
          seen.add(val);
          walkTensorContainer(val, list, seen);
        }
      }
    }
    function isIterable(obj) {
      return Array.isArray(obj) || typeof obj === "object";
    }
    function isRegisteredKernelInvocation(kernelInvocation) {
      return kernelInvocation.kernelName != null;
    }
    var EngineState = (
      /** @class */
      function() {
        function EngineState2() {
          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 = /* @__PURE__ */ new WeakMap();
          this.profiling = false;
          this.activeProfile = {
            newBytes: 0,
            newTensors: 0,
            peakBytes: 0,
            kernels: [],
            result: null,
            get kernelNames() {
              return Array.from(new Set(this.kernels.map(function(k) {
                return k.name;
              })));
            }
          };
        }
        EngineState2.prototype.dispose = function() {
          for (var variableName in this.registeredVariables) {
            this.registeredVariables[variableName].dispose();
          }
        };
        return EngineState2;
      }()
    );
    var Engine = (
      /** @class */
      function() {
        function Engine2(ENV2) {
          this.ENV = ENV2;
          this.registry = {};
          this.registryFactory = {};
          this.pendingBackendInitId = 0;
          this.state = new EngineState();
        }
        Engine2.prototype.ready = function() {
          return __awaiter(this, void 0, void 0, function() {
            var sortedBackends, i, backendName, success;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  if (this.pendingBackendInit != null) {
                    return [2, this.pendingBackendInit.then(function() {
                    })];
                  }
                  if (this.backendInstance != null) {
                    return [
                      2
                      /*return*/
                    ];
                  }
                  sortedBackends = this.getSortedBackends();
                  i = 0;
                  _a.label = 1;
                case 1:
                  if (!(i < sortedBackends.length)) return [3, 5];
                  backendName = sortedBackends[i];
                  return [4, this.initializeBackend(backendName).success];
                case 2:
                  success = _a.sent();
                  if (!success) return [3, 4];
                  return [4, this.setBackend(backendName)];
                case 3:
                  _a.sent();
                  return [
                    2
                    /*return*/
                  ];
                case 4:
                  i++;
                  return [3, 1];
                case 5:
                  throw new Error("Could not initialize any backends, all backend initializations failed.");
              }
            });
          });
        };
        Object.defineProperty(Engine2.prototype, "backend", {
          get: function() {
            if (this.pendingBackendInit != null) {
              throw new Error("Backend '".concat(this.backendName, "' has not yet been initialized. Make ") + "sure to await tf.ready() or await tf.setBackend() before calling other methods");
            }
            if (this.backendInstance == null) {
              var _a = this.initializeBackendsAndReturnBest(), name = _a.name, asyncInit = _a.asyncInit;
              if (asyncInit) {
                throw new Error("The highest priority backend '".concat(name, "' has not yet been ") + "initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods");
              }
              this.setBackend(name);
            }
            return this.backendInstance;
          },
          enumerable: false,
          configurable: true
        });
        Engine2.prototype.backendNames = function() {
          return Object.keys(this.registryFactory);
        };
        Engine2.prototype.findBackend = function(backendName) {
          if (!(backendName in this.registry)) {
            if (backendName in this.registryFactory) {
              var asyncInit = this.initializeBackend(backendName).asyncInit;
              if (asyncInit) {
                return null;
              }
            } else {
              return null;
            }
          }
          return this.registry[backendName];
        };
        Engine2.prototype.findBackendFactory = function(backendName) {
          if (!(backendName in this.registryFactory)) {
            return null;
          }
          return this.registryFactory[backendName].factory;
        };
        Engine2.prototype.registerBackend = function(backendName, factory, priority) {
          if (priority === void 0) {
            priority = 1;
          }
          if (backendName in this.registryFactory) {
            warn("".concat(backendName, " backend was already registered. ") + "Reusing existing backend factory.");
            return false;
          }
          this.registryFactory[backendName] = { factory, priority };
          return true;
        };
        Engine2.prototype.setBackend = function(backendName) {
          return __awaiter(this, void 0, void 0, function() {
            var _a, success, asyncInit, result, _b;
            return __generator(this, function(_c) {
              switch (_c.label) {
                case 0:
                  if (this.registryFactory[backendName] == null) {
                    throw new Error("Backend name '".concat(backendName, "' not found in registry"));
                  }
                  this.backendName = backendName;
                  if (!(this.registry[backendName] == null)) return [3, 4];
                  this.backendInstance = null;
                  _a = this.initializeBackend(backendName), success = _a.success, asyncInit = _a.asyncInit;
                  if (!asyncInit) return [3, 2];
                  return [4, success];
                case 1:
                  _b = _c.sent();
                  return [3, 3];
                case 2:
                  _b = success;
                  _c.label = 3;
                case 3:
                  result = _b;
                  if (!result) {
                    return [2, false];
                  }
                  _c.label = 4;
                case 4:
                  this.backendInstance = this.registry[backendName];
                  this.setupRegisteredKernels();
                  this.profiler = new Profiler(this.backendInstance);
                  return [2, true];
              }
            });
          });
        };
        Engine2.prototype.setupRegisteredKernels = function() {
          var _this = this;
          var kernels = getKernelsForBackend(this.backendName);
          kernels.forEach(function(kernel) {
            if (kernel.setupFunc != null) {
              kernel.setupFunc(_this.backendInstance);
            }
          });
        };
        Engine2.prototype.disposeRegisteredKernels = function(backendName) {
          var _this = this;
          var kernels = getKernelsForBackend(backendName);
          kernels.forEach(function(kernel) {
            if (kernel.disposeFunc != null) {
              kernel.disposeFunc(_this.registry[backendName]);
            }
          });
        };
        Engine2.prototype.initializeBackend = function(backendName) {
          var _this = this;
          var registryFactoryEntry = this.registryFactory[backendName];
          if (registryFactoryEntry == null) {
            throw new Error("Cannot initialize backend ".concat(backendName, ", no registration found."));
          }
          try {
            var backend2 = registryFactoryEntry.factory();
            if (backend2 && !(backend2 instanceof KernelBackend) && typeof backend2.then === "function") {
              var promiseId_1 = ++this.pendingBackendInitId;
              var success = backend2.then(function(backendInstance) {
                if (promiseId_1 < _this.pendingBackendInitId) {
                  return false;
                }
                _this.registry[backendName] = backendInstance;
                _this.pendingBackendInit = null;
                return true;
              }).catch(function(err) {
                if (promiseId_1 < _this.pendingBackendInitId) {
                  return false;
                }
                _this.pendingBackendInit = null;
                warn("Initialization of backend ".concat(backendName, " failed"));
                warn(err.stack || err.message);
                return false;
              });
              this.pendingBackendInit = success;
              return { success, asyncInit: true };
            } else {
              this.registry[backendName] = backend2;
              return { success: true, asyncInit: false };
            }
          } catch (err) {
            warn("Initialization of backend ".concat(backendName, " failed"));
            warn(err.stack || err.message);
            return { success: false, asyncInit: false };
          }
        };
        Engine2.prototype.removeBackend = function(backendName) {
          if (!(backendName in this.registryFactory)) {
            throw new Error("".concat(backendName, " backend not found in registry"));
          }
          if (this.backendName === backendName && this.pendingBackendInit != null) {
            this.pendingBackendInitId++;
          }
          if (backendName in this.registry) {
            this.disposeRegisteredKernels(backendName);
            this.registry[backendName].dispose();
            delete this.registry[backendName];
          }
          delete this.registryFactory[backendName];
          if (this.backendName === backendName) {
            this.pendingBackendInit = null;
            this.backendName = null;
            this.backendInstance = null;
          }
        };
        Engine2.prototype.getSortedBackends = function() {
          var _this = this;
          if (Object.keys(this.registryFactory).length === 0) {
            throw new Error("No backend found in registry.");
          }
          return Object.keys(this.registryFactory).sort(function(a, b) {
            return _this.registryFactory[b].priority - _this.registryFactory[a].priority;
          });
        };
        Engine2.prototype.initializeBackendsAndReturnBest = function() {
          var sortedBackends = this.getSortedBackends();
          for (var i = 0; i < sortedBackends.length; i++) {
            var backendName = sortedBackends[i];
            var _a = this.initializeBackend(backendName), success = _a.success, asyncInit = _a.asyncInit;
            if (asyncInit || success) {
              return { name: backendName, asyncInit };
            }
          }
          throw new Error("Could not initialize any backends, all backend initializations failed.");
        };
        Engine2.prototype.moveData = function(backend2, dataId) {
          var info = this.state.tensorInfo.get(dataId);
          var srcBackend = info.backend;
          var values = this.readSync(dataId);
          var refCount = srcBackend.refCount(dataId);
          srcBackend.disposeData(dataId, true);
          info.backend = backend2;
          backend2.move(dataId, values, info.shape, info.dtype, refCount);
          if (this.shouldCheckForMemLeaks()) {
            this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;
          }
        };
        Engine2.prototype.tidy = function(nameOrFn, fn) {
          var _this = this;
          var name = null;
          if (fn == null) {
            if (typeof nameOrFn !== "function") {
              throw new Error("Please provide a function to tidy()");
            }
            fn = nameOrFn;
          } else {
            if (typeof nameOrFn !== "string" && !(nameOrFn instanceof String)) {
              throw new Error("When calling with two arguments, the first argument to tidy() must be a string");
            }
            if (typeof fn !== "function") {
              throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");
            }
            name = nameOrFn;
          }
          var result;
          return this.scopedRun(function() {
            return _this.startScope(name);
          }, function() {
            return _this.endScope(result);
          }, function() {
            result = fn();
            if (result instanceof Promise) {
              console.error("Cannot return a Promise inside of tidy.");
            }
            return result;
          });
        };
        Engine2.prototype.scopedRun = function(start, end, f) {
          start();
          try {
            var res = f();
            end();
            return res;
          } catch (ex) {
            end();
            throw ex;
          }
        };
        Engine2.prototype.nextTensorId = function() {
          return Engine2.nextTensorId++;
        };
        Engine2.prototype.nextVariableId = function() {
          return Engine2.nextVariableId++;
        };
        Engine2.prototype.clone = function(x) {
          var y = ENGINE.runKernel(Identity, { x });
          var inputs = { x };
          var grad = function(dy) {
            return {
              x: function() {
                var dtype = "float32";
                var gradInputs = { x: dy };
                var attrs = { dtype };
                return ENGINE.runKernel(
                  Cast,
                  gradInputs,
                  // tslint:disable-next-line: no-unnecessary-type-assertion
                  attrs
                );
              }
            };
          };
          var saved = [];
          this.addTapeNode(this.state.activeScope.name, inputs, [y], grad, saved, {});
          return y;
        };
        Engine2.prototype.runKernel = function(kernelName, inputs, attrs) {
          if (this.backendName == null) {
            this.backend;
          }
          var hasKernel = getKernel(kernelName, this.backendName) != null;
          if (!hasKernel) {
            throw new Error("Kernel '".concat(kernelName, "' not registered for backend '").concat(this.backendName, "'"));
          }
          return this.runKernelFunc({ kernelName, inputs, attrs });
        };
        Engine2.prototype.shouldCheckForMemLeaks = function() {
          return this.ENV.getBool("IS_TEST");
        };
        Engine2.prototype.checkKernelForMemLeak = function(kernelName, numDataIdsBefore, outInfos) {
          var numDataIdsAfter = this.backend.numDataIds();
          var numOutputDataIds = 0;
          outInfos.forEach(function(info) {
            numOutputDataIds += info.dtype === "complex64" ? 3 : 1;
          });
          var numMoves = this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1];
          var dataIdsLeaked = numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves;
          if (dataIdsLeaked > 0) {
            throw new Error("Backend '".concat(this.backendName, "' has an internal memory leak ") + "(".concat(dataIdsLeaked, " data ids) after running '").concat(kernelName, "'"));
          }
        };
        Engine2.prototype.runKernelFunc = function(kernelParams) {
          var _this = this;
          var outputs;
          var saved = [];
          var isTapeOn = this.isTapeOn();
          var startingBytecount = this.state.numBytes;
          var startingNumTensors = this.state.numTensors;
          if (this.shouldCheckForMemLeaks()) {
            this.state.numDataMovesStack.push(0);
          }
          var kernelFunc;
          if (this.backendName == null) {
            this.backend;
          }
          var out;
          var kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ? kernelParams.kernelName : this.state.activeScope != null ? this.state.activeScope.name : "";
          if (isRegisteredKernelInvocation(kernelParams)) {
            var kernelName_1 = kernelParams.kernelName, inputs_1 = kernelParams.inputs, attrs_1 = kernelParams.attrs;
            if (this.backendName == null) {
              this.backend;
            }
            var kernel_1 = getKernel(kernelName_1, this.backendName);
            assert(kernel_1 != null, function() {
              return "Cannot find registered kernel '".concat(kernelName_1, "' for backend '").concat(_this.backendName, "'");
            });
            kernelFunc = function() {
              var numDataIdsBefore = _this.backend.numDataIds();
              out = kernel_1.kernelFunc({ inputs: inputs_1, attrs: attrs_1, backend: _this.backend });
              var outInfos = Array.isArray(out) ? out : [out];
              if (_this.shouldCheckForMemLeaks()) {
                _this.checkKernelForMemLeak(kernelName_1, numDataIdsBefore, outInfos);
              }
              var outTensors = outInfos.map(function(outInfo) {
                if (outInfo.rank != null) {
                  return outInfo;
                }
                return _this.makeTensorFromTensorInfo(outInfo);
              });
              if (isTapeOn) {
                var tensorsToSave = _this.getTensorsForGradient(kernelName_1, inputs_1, outTensors);
                saved = _this.saveTensorsForBackwardMode(tensorsToSave);
              }
              return outTensors;
            };
          } else {
            var forwardFunc_1 = kernelParams.forwardFunc;
            var saveFunc_1 = function(tensors) {
              if (!isTapeOn) {
                return;
              }
              saved = tensors.map(function(tensor2) {
                return _this.keep(_this.clone(tensor2));
              });
            };
            kernelFunc = function() {
              var numDataIdsBefore = _this.backend.numDataIds();
              out = _this.tidy(function() {
                return forwardFunc_1(_this.backend, saveFunc_1);
              });
              var outs = Array.isArray(out) ? out : [out];
              if (_this.shouldCheckForMemLeaks()) {
                _this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs);
              }
              return outs;
            };
          }
          var inputs = kernelParams.inputs, attrs = kernelParams.attrs;
          var backwardsFunc = isRegisteredKernelInvocation(kernelParams) ? null : kernelParams.backwardsFunc;
          var kernelProfile;
          this.scopedRun(
            // Stop recording to a tape when running a kernel.
            function() {
              return _this.state.kernelDepth++;
            },
            function() {
              return _this.state.kernelDepth--;
            },
            function() {
              if (!_this.ENV.getBool("DEBUG") && !_this.state.profiling) {
                outputs = kernelFunc();
              } else {
                kernelProfile = _this.profiler.profileKernel(kernelOrScopeName, inputs, function() {
                  return kernelFunc();
                });
                if (_this.ENV.getBool("DEBUG")) {
                  _this.profiler.logKernelProfile(kernelProfile);
                }
                outputs = kernelProfile.outputs;
              }
            }
          );
          if (isTapeOn) {
            this.addTapeNode(kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs);
          }
          if (this.state.profiling) {
            this.state.activeProfile.kernels.push({
              name: kernelOrScopeName,
              bytesAdded: this.state.numBytes - startingBytecount,
              totalBytesSnapshot: this.state.numBytes,
              tensorsAdded: this.state.numTensors - startingNumTensors,
              totalTensorsSnapshot: this.state.numTensors,
              inputShapes: Object.keys(inputs).map(function(key) {
                return inputs[key] != null ? inputs[key].shape : null;
              }),
              outputShapes: outputs.map(function(item) {
                return item.shape;
              }),
              kernelTimeMs: kernelProfile.timeMs,
              extraInfo: kernelProfile.extraInfo
            });
          }
          return Array.isArray(out) ? outputs : outputs[0];
        };
        Engine2.prototype.saveTensorsForBackwardMode = function(tensors) {
          var _this = this;
          var saved = tensors.map(function(tensor2) {
            return _this.keep(_this.clone(tensor2));
          });
          return saved;
        };
        Engine2.prototype.getTensorsForGradient = function(kernelName, inputs, outputs) {
          var gradConfig = getGradient(kernelName);
          if (gradConfig != null) {
            var inputsToSave = gradConfig.inputsToSave || [];
            var outputsToSave_1 = gradConfig.outputsToSave || [];
            var inputTensorsToSave = void 0;
            if (gradConfig.saveAllInputs) {
              assert(Array.isArray(inputs), function() {
                return "saveAllInputs is true, expected inputs to be an array.";
              });
              inputTensorsToSave = Object.keys(inputs).map(function(key) {
                return inputs[key];
              });
            } else {
              inputTensorsToSave = inputsToSave.map(function(inputName) {
                return inputs[inputName];
              });
            }
            var outputTensorsToSave = outputs.filter(function(_, i) {
              return outputsToSave_1[i];
            });
            return inputTensorsToSave.concat(outputTensorsToSave);
          }
          return [];
        };
        Engine2.prototype.makeTensor = function(values, shape, dtype, backend2) {
          if (values == null) {
            throw new Error("Values passed to engine.makeTensor() are null");
          }
          dtype = dtype || "float32";
          backend2 = backend2 || this.backend;
          var backendVals = values;
          if (dtype === "string" && isString(values[0])) {
            backendVals = values.map(function(d) {
              return encodeString(d);
            });
          }
          var dataId = backend2.write(backendVals, shape, dtype);
          var t = new Tensor(shape, dtype, dataId, this.nextTensorId());
          this.trackTensor(t, backend2);
          if (dtype === "string") {
            var info = this.state.tensorInfo.get(dataId);
            var newBytes = bytesFromStringArray(backendVals);
            this.state.numBytes += newBytes - info.bytes;
            info.bytes = newBytes;
          }
          return t;
        };
        Engine2.prototype.makeTensorFromDataId = function(dataId, shape, dtype, backend2) {
          dtype = dtype || "float32";
          var tensorInfo = { dataId, shape, dtype };
          return this.makeTensorFromTensorInfo(tensorInfo, backend2);
        };
        Engine2.prototype.makeTensorFromTensorInfo = function(tensorInfo, backend2) {
          var dataId = tensorInfo.dataId, shape = tensorInfo.shape, dtype = tensorInfo.dtype;
          var t = new Tensor(shape, dtype, dataId, this.nextTensorId());
          this.trackTensor(t, backend2);
          return t;
        };
        Engine2.prototype.makeVariable = function(initialValue, trainable, name, dtype) {
          if (trainable === void 0) {
            trainable = true;
          }
          name = name || this.nextVariableId().toString();
          if (dtype != null && dtype !== initialValue.dtype) {
            initialValue = initialValue.cast(dtype);
          }
          var v = new Variable(initialValue, trainable, name, this.nextTensorId());
          if (this.state.registeredVariables[v.name] != null) {
            throw new Error("Variable with name ".concat(v.name, " was already registered"));
          }
          this.state.registeredVariables[v.name] = v;
          this.incRef(v, this.backend);
          return v;
        };
        Engine2.prototype.trackTensor = function(a, backend2) {
          this.state.numTensors++;
          if (a.dtype === "string") {
            this.state.numStringTensors++;
          }
          var bytes = 0;
          if (a.dtype !== "complex64" && a.dtype !== "string") {
            bytes = a.size * bytesPerElement(a.dtype);
          }
          this.state.numBytes += bytes;
          if (!this.state.tensorInfo.has(a.dataId)) {
            this.state.numDataBuffers++;
            this.state.tensorInfo.set(a.dataId, {
              backend: backend2 || this.backend,
              dtype: a.dtype,
              shape: a.shape,
              bytes
            });
          }
          if (!(a instanceof Variable)) {
            this.track(a);
          }
        };
        Engine2.prototype.incRef = function(a, backend2) {
          this.trackTensor(a, backend2);
          this.backend.incRef(a.dataId);
        };
        Engine2.prototype.removeDataId = function(dataId, backend2) {
          if (this.state.tensorInfo.has(dataId) && this.state.tensorInfo.get(dataId).backend === backend2) {
            this.state.tensorInfo.delete(dataId);
            this.state.numDataBuffers--;
          }
        };
        Engine2.prototype.disposeTensor = function(a) {
          if (!this.state.tensorInfo.has(a.dataId)) {
            return;
          }
          var info = this.state.tensorInfo.get(a.dataId);
          this.state.numTensors--;
          if (a.dtype === "string") {
            this.state.numStringTensors--;
            this.state.numBytes -= info.bytes;
          }
          if (a.dtype !== "complex64" && a.dtype !== "string") {
            var bytes = a.size * bytesPerElement(a.dtype);
            this.state.numBytes -= bytes;
          }
          if (info.backend.disposeData(a.dataId)) {
            this.removeDataId(a.dataId, info.backend);
          }
        };
        Engine2.prototype.disposeVariables = function() {
          for (var varName in this.state.registeredVariables) {
            var v = this.state.registeredVariables[varName];
            this.disposeVariable(v);
          }
        };
        Engine2.prototype.disposeVariable = function(v) {
          this.disposeTensor(v);
          if (this.state.registeredVariables[v.name] != null) {
            delete this.state.registeredVariables[v.name];
          }
        };
        Engine2.prototype.memory = function() {
          var info = this.backend.memory();
          info.numTensors = this.state.numTensors;
          info.numDataBuffers = this.state.numDataBuffers;
          info.numBytes = this.state.numBytes;
          if (this.state.numStringTensors > 0) {
            info.unreliable = true;
            if (info.reasons == null) {
              info.reasons = [];
            }
            info.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)");
          }
          return info;
        };
        Engine2.prototype.profile = function(query) {
          return __awaiter(this, void 0, void 0, function() {
            var startBytes, startNumTensors, _a, _b, _c, kernel, _d, _e, e_1_1;
            var e_1, _f;
            return __generator(this, function(_g) {
              switch (_g.label) {
                case 0:
                  this.state.profiling = true;
                  startBytes = this.state.numBytes;
                  startNumTensors = this.state.numTensors;
                  this.state.activeProfile.kernels = [];
                  _a = this.state.activeProfile;
                  return [4, query()];
                case 1:
                  _a.result = _g.sent();
                  this.state.profiling = false;
                  this.state.activeProfile.peakBytes = Math.max.apply(Math, __spreadArray([], __read(this.state.activeProfile.kernels.map(function(d) {
                    return d.totalBytesSnapshot;
                  })), false));
                  this.state.activeProfile.newBytes = this.state.numBytes - startBytes;
                  this.state.activeProfile.newTensors = this.state.numTensors - startNumTensors;
                  _g.label = 2;
                case 2:
                  _g.trys.push([2, 8, 9, 10]);
                  _b = __values(this.state.activeProfile.kernels), _c = _b.next();
                  _g.label = 3;
                case 3:
                  if (!!_c.done) return [3, 7];
                  kernel = _c.value;
                  _d = kernel;
                  return [4, kernel.kernelTimeMs];
                case 4:
                  _d.kernelTimeMs = _g.sent();
                  _e = kernel;
                  return [4, kernel.extraInfo];
                case 5:
                  _e.extraInfo = _g.sent();
                  _g.label = 6;
                case 6:
                  _c = _b.next();
                  return [3, 3];
                case 7:
                  return [3, 10];
                case 8:
                  e_1_1 = _g.sent();
                  e_1 = { error: e_1_1 };
                  return [3, 10];
                case 9:
                  try {
                    if (_c && !_c.done && (_f = _b.return)) _f.call(_b);
                  } finally {
                    if (e_1) throw e_1.error;
                  }
                  return [
                    7
                    /*endfinally*/
                  ];
                case 10:
                  return [2, this.state.activeProfile];
              }
            });
          });
        };
        Engine2.prototype.isTapeOn = function() {
          return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;
        };
        Engine2.prototype.addTapeNode = function(kernelName, inputs, outputs, gradientsFunc, saved, attrs) {
          var _this = this;
          var tapeNode = { id: this.state.nextTapeNodeId++, kernelName, inputs, outputs, saved };
          var gradConfig = getGradient(kernelName);
          if (gradConfig != null) {
            gradientsFunc = gradConfig.gradFunc;
          }
          if (gradientsFunc != null) {
            tapeNode.gradient = function(dys) {
              dys = dys.map(function(dy, i) {
                if (dy == null) {
                  var output = outputs[i];
                  var vals = makeZerosTypedArray(output.size, output.dtype);
                  return _this.makeTensor(vals, output.shape, output.dtype);
                }
                return dy;
              });
              return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs);
            };
          }
          this.state.activeTape.push(tapeNode);
        };
        Engine2.prototype.keep = function(result) {
          result.kept = true;
          return result;
        };
        Engine2.prototype.startTape = function() {
          if (this.state.gradientDepth === 0) {
            this.state.activeTape = [];
          }
          this.state.gradientDepth++;
        };
        Engine2.prototype.endTape = function() {
          this.state.gradientDepth--;
        };
        Engine2.prototype.startScope = function(name) {
          var scopeInfo = {
            track: [],
            name: "unnamed scope",
            id: this.state.nextScopeId++
          };
          if (name) {
            scopeInfo.name = name;
          }
          this.state.scopeStack.push(scopeInfo);
          this.state.activeScope = scopeInfo;
        };
        Engine2.prototype.endScope = function(result) {
          var _this = this;
          var tensorsToTrackInParent = getTensorsInContainer(result);
          var tensorsToTrackInParentSet = new Set(tensorsToTrackInParent.map(function(t) {
            return t.id;
          }));
          for (var i = 0; i < this.state.activeScope.track.length; i++) {
            var tensor2 = this.state.activeScope.track[i];
            if (!tensor2.kept && !tensorsToTrackInParentSet.has(tensor2.id)) {
              tensor2.dispose();
            }
          }
          var oldScope = this.state.scopeStack.pop();
          this.state.activeScope = this.state.scopeStack.length === 0 ? null : this.state.scopeStack[this.state.scopeStack.length - 1];
          tensorsToTrackInParent.forEach(function(tensor3) {
            if (!tensor3.kept && tensor3.scopeId === oldScope.id) {
              _this.track(tensor3);
            }
          });
        };
        Engine2.prototype.gradients = function(f, xs, dy, allowNoGradients) {
          var _this = this;
          if (allowNoGradients === void 0) {
            allowNoGradients = false;
          }
          assert(xs.length > 0, function() {
            return "gradients() received an empty list of xs.";
          });
          if (dy != null && dy.dtype !== "float32") {
            throw new Error("dy must have 'float32' dtype, but has '".concat(dy.dtype, "'"));
          }
          var y = this.scopedRun(function() {
            return _this.startTape();
          }, function() {
            return _this.endTape();
          }, function() {
            return _this.tidy("forward", f);
          });
          assert(y instanceof Tensor, function() {
            return "The result y returned by f() must be a tensor.";
          });
          var filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y);
          if (!allowNoGradients && filteredTape.length === 0 && xs.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", function() {
            var accumulatedGradientMap = {};
            accumulatedGradientMap[y.id] = dy == null ? ones$1(y.shape) : dy;
            backpropagateGradients(
              accumulatedGradientMap,
              filteredTape,
              // Pass the tidy function to avoid circular dep with `tape.ts`.
              function(f2) {
                return _this.tidy(f2);
              },
              // Pass an add function to avoide a circular dep with `tape.ts`.
              add$1
            );
            var grads = xs.map(function(x) {
              return accumulatedGradientMap[x.id];
            });
            if (_this.state.gradientDepth === 0) {
              _this.state.activeTape.forEach(function(node) {
                var e_2, _a;
                try {
                  for (var _b = __values(node.saved), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var tensor2 = _c.value;
                    tensor2.dispose();
                  }
                } catch (e_2_1) {
                  e_2 = { error: e_2_1 };
                } finally {
                  try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                  } finally {
                    if (e_2) throw e_2.error;
                  }
                }
              });
              _this.state.activeTape = null;
            }
            return { value: y, grads };
          });
        };
        Engine2.prototype.customGrad = function(f) {
          var _this = this;
          assert(isFunction(f), function() {
            return "The f passed in customGrad(f) must be a function.";
          });
          return function() {
            var inputs = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              inputs[_i] = arguments[_i];
            }
            assert(inputs.every(function(t) {
              return t instanceof Tensor;
            }), function() {
              return "The args passed in customGrad(f)(x1, x2,...) must all be tensors";
            });
            var res;
            var inputMap = {};
            inputs.forEach(function(input, i) {
              inputMap[i] = input;
            });
            var forwardFunc = function(_, save) {
              res = f.apply(void 0, __spreadArray([], __read(__spreadArray(__spreadArray([], __read(inputs), false), [save], false)), false));
              assert(res.value instanceof Tensor, function() {
                return "The function f passed in customGrad(f) must return an object where `obj.value` is a tensor";
              });
              assert(isFunction(res.gradFunc), function() {
                return "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.";
              });
              return res.value;
            };
            var backwardsFunc = function(dy, saved) {
              var gradRes = res.gradFunc(dy, saved);
              var grads = Array.isArray(gradRes) ? gradRes : [gradRes];
              assert(grads.length === inputs.length, function() {
                return "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(...).";
              });
              assert(grads.every(function(t) {
                return t instanceof Tensor;
              }), function() {
                return "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.";
              });
              var gradMap = {};
              grads.forEach(function(grad, i) {
                gradMap[i] = function() {
                  return grad;
                };
              });
              return gradMap;
            };
            return _this.runKernelFunc({
              forwardFunc,
              backwardsFunc,
              inputs: inputMap
            });
          };
        };
        Engine2.prototype.readSync = function(dataId) {
          var info = this.state.tensorInfo.get(dataId);
          return info.backend.readSync(dataId);
        };
        Engine2.prototype.read = function(dataId) {
          var info = this.state.tensorInfo.get(dataId);
          return info.backend.read(dataId);
        };
        Engine2.prototype.readToGPU = function(dataId, options) {
          var info = this.state.tensorInfo.get(dataId);
          return info.backend.readToGPU(dataId, options);
        };
        Engine2.prototype.time = function(query) {
          return __awaiter(this, void 0, void 0, function() {
            var start, timingInfo;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  start = now();
                  return [4, this.backend.time(query)];
                case 1:
                  timingInfo = _a.sent();
                  timingInfo.wallMs = now() - start;
                  return [2, timingInfo];
              }
            });
          });
        };
        Engine2.prototype.track = function(result) {
          if (this.state.activeScope != null) {
            result.scopeId = this.state.activeScope.id;
            this.state.activeScope.track.push(result);
          }
          return result;
        };
        Object.defineProperty(Engine2.prototype, "registeredVariables", {
          get: function() {
            return this.state.registeredVariables;
          },
          enumerable: false,
          configurable: true
        });
        Engine2.prototype.reset = function() {
          this.pendingBackendInitId++;
          this.state.dispose();
          this.ENV.reset();
          this.state = new EngineState();
          for (var backendName in this.registry) {
            this.disposeRegisteredKernels(backendName);
            this.registry[backendName].dispose();
            delete this.registry[backendName];
          }
          this.backendName = null;
          this.backendInstance = null;
          this.pendingBackendInit = null;
        };
        return Engine2;
      }()
    );
    Engine.nextTensorId = 0;
    Engine.nextVariableId = 0;
    function ones$1(shape) {
      var values = makeOnesTypedArray(sizeFromShape(shape), "float32");
      return ENGINE.makeTensor(values, shape, "float32");
    }
    function getOrMakeEngine() {
      var ns = getGlobalNamespace();
      if (ns._tfengine == null) {
        var environment = new Environment(ns);
        ns._tfengine = new Engine(environment);
      }
      setEnvironmentGlobal(ns._tfengine.ENV);
      setTensorTracker(function() {
        return ns._tfengine;
      });
      return ns._tfengine;
    }
    var ENGINE = getOrMakeEngine();
    function add$1(a, b) {
      var inputs = { a, b };
      return ENGINE.runKernel(Add, inputs);
    }
    function inferShape(val, dtype) {
      var firstElem = val;
      if (isTypedArray(val)) {
        return dtype === "string" ? [] : [val.length];
      }
      if (isWebGLData(val)) {
        var usedChannels = val.channels || "RGBA";
        return [val.height, val.width * usedChannels.length];
      } else if (isWebGPUData(val)) {
        return [val.buffer.size / (dtype == null ? 4 : bytesPerElement(dtype))];
      }
      if (!Array.isArray(val)) {
        return [];
      }
      var shape = [];
      while (Array.isArray(firstElem) || isTypedArray(firstElem) && dtype !== "string") {
        shape.push(firstElem.length);
        firstElem = firstElem[0];
      }
      if (Array.isArray(val) && env().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")) {
        deepAssertShapeConsistency(val, shape, []);
      }
      return shape;
    }
    function deepAssertShapeConsistency(val, shape, indices) {
      indices = indices || [];
      if (!Array.isArray(val) && !isTypedArray(val)) {
        assert(shape.length === 0, function() {
          return "Element arr[".concat(indices.join("]["), "] is a primitive, ") + "but should be an array/TypedArray of ".concat(shape[0], " elements");
        });
        return;
      }
      assert(shape.length > 0, function() {
        return "Element arr[".concat(indices.join("]["), "] should be a primitive, ") + "but is an array of ".concat(val.length, " elements");
      });
      assert(val.length === shape[0], function() {
        return "Element arr[".concat(indices.join("]["), "] should have ").concat(shape[0], " ") + "elements, but has ".concat(val.length, " elements");
      });
      var subShape = shape.slice(1);
      for (var i = 0; i < val.length; ++i) {
        deepAssertShapeConsistency(val[i], subShape, indices.concat(i));
      }
    }
    function assertDtype(expectedDtype, actualDType, argName, functionName) {
      if (expectedDtype === "string_or_numeric") {
        return;
      }
      if (expectedDtype == null) {
        throw new Error("Expected dtype cannot be null.");
      }
      if (expectedDtype !== "numeric" && expectedDtype !== actualDType || expectedDtype === "numeric" && actualDType === "string") {
        throw new Error("Argument '".concat(argName, "' passed to '").concat(functionName, "' must ") + "be ".concat(expectedDtype, " tensor, but got ").concat(actualDType, " tensor"));
      }
    }
    function convertToTensor(x, argName, functionName, parseAsDtype) {
      if (parseAsDtype === void 0) {
        parseAsDtype = "numeric";
      }
      if (x instanceof getGlobalTensorClass()) {
        assertDtype(parseAsDtype, x.dtype, argName, functionName);
        return x;
      }
      var inferredDtype = inferDtype(x);
      if (inferredDtype !== "string" && ["bool", "int32", "float32"].indexOf(parseAsDtype) >= 0) {
        inferredDtype = parseAsDtype;
      }
      assertDtype(parseAsDtype, inferredDtype, argName, functionName);
      if (x == null || !isTypedArray(x) && !Array.isArray(x) && typeof x !== "number" && typeof x !== "boolean" && typeof x !== "string") {
        var type = x == null ? "null" : x.constructor.name;
        throw new Error("Argument '".concat(argName, "' passed to '").concat(functionName, "' must be a ") + "Tensor or TensorLike, but got '".concat(type, "'"));
      }
      var inferredShape = inferShape(x, inferredDtype);
      if (!isTypedArray(x) && !Array.isArray(x)) {
        x = [x];
      }
      var skipTypedArray = true;
      var values = inferredDtype !== "string" ? toTypedArray(x, inferredDtype) : flatten(x, [], skipTypedArray);
      return ENGINE.makeTensor(values, inferredShape, inferredDtype);
    }
    function convertToTensorArray(arg, argName, functionName, parseAsDtype) {
      if (parseAsDtype === void 0) {
        parseAsDtype = "numeric";
      }
      if (!Array.isArray(arg)) {
        throw new Error("Argument ".concat(argName, " passed to ").concat(functionName, " must be a ") + "`Tensor[]` or `TensorLike[]`");
      }
      var tensors = arg;
      return tensors.map(function(t, i) {
        return convertToTensor(t, "".concat(argName, "[").concat(i, "]"), functionName, parseAsDtype);
      });
    }
    var OP_SCOPE_SUFFIX = "__op";
    function op(f) {
      var keys = Object.keys(f);
      if (keys.length !== 1) {
        throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with " + "".concat(keys.length, " keys."));
      }
      var opName = keys[0];
      var fn = f[opName];
      if (opName.endsWith("_")) {
        opName = opName.substring(0, opName.length - 1);
      }
      opName = opName + OP_SCOPE_SUFFIX;
      var f2 = function() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        ENGINE.startScope(opName);
        try {
          var result = fn.apply(void 0, __spreadArray([], __read(args), false));
          if (isPromise(result)) {
            console.error("Cannot return a Promise inside of tidy.");
          }
          ENGINE.endScope(result);
          return result;
        } catch (ex) {
          ENGINE.endScope(null);
          throw ex;
        }
      };
      Object.defineProperty(f2, "name", { value: opName, configurable: true });
      return f2;
    }
    function abs_(x) {
      var $x = convertToTensor(x, "x", "abs");
      if ($x.dtype === "complex64") {
        var inputs = { x: $x };
        return ENGINE.runKernel(ComplexAbs, inputs);
      } else {
        var inputs = { x: $x };
        return ENGINE.runKernel(Abs, inputs);
      }
    }
    var abs = /* @__PURE__ */ op({ abs_ });
    function acos_(x) {
      var $x = convertToTensor(x, "x", "acos");
      var inputs = { x: $x };
      return ENGINE.runKernel(Acos, inputs);
    }
    var acos = /* @__PURE__ */ op({ acos_ });
    function acosh_(x) {
      var $x = convertToTensor(x, "x", "acosh");
      var inputs = { x: $x };
      return ENGINE.runKernel(Acosh, inputs);
    }
    var acosh = /* @__PURE__ */ op({ acosh_ });
    function add_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "add");
      var $b = convertToTensor(b, "b", "add");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Add, inputs);
    }
    var add = /* @__PURE__ */ op({ add_ });
    function addN_(tensors) {
      assert(Array.isArray(tensors), function() {
        return "The argument passed to tf.addN() must be a list of tensors";
      });
      assert(tensors.length >= 1, function() {
        return "Must pass at least one tensor to tf.addN(), but got " + "".concat(tensors.length);
      });
      var $tensors = tensors.map(function(t, i) {
        return convertToTensor(t, "tensors".concat(i), "addN");
      });
      var firstTensor = $tensors[0];
      $tensors.forEach(function(t) {
        if (t.dtype !== firstTensor.dtype) {
          throw new Error("All tensors passed to tf.addN() must have the same dtype");
        }
      });
      $tensors.forEach(function(t) {
        if (!arraysEqual(t.shape, firstTensor.shape)) {
          throw new Error("All tensors passed to tf.addN() must have the same shape");
        }
      });
      var inputs = $tensors;
      return ENGINE.runKernel(AddN, inputs);
    }
    var addN = /* @__PURE__ */ op({ addN_ });
    function all_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "all", "bool");
      var inputs = { x: $x };
      var attrs = { axis, keepDims };
      return ENGINE.runKernel(All, inputs, attrs);
    }
    var all = /* @__PURE__ */ op({ all_ });
    function any_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "any", "bool");
      var inputs = { x: $x };
      var attrs = { axis, keepDims };
      return ENGINE.runKernel(Any, inputs, attrs);
    }
    var any = /* @__PURE__ */ op({ any_ });
    function argMax_(x, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $x = convertToTensor(x, "x", "argMax");
      var inputs = { x: $x };
      var attrs = { axis };
      return ENGINE.runKernel(ArgMax, inputs, attrs);
    }
    var argMax = /* @__PURE__ */ op({ argMax_ });
    function argMin_(x, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $x = convertToTensor(x, "x", "argMin");
      var inputs = { x: $x };
      var attrs = { axis };
      return ENGINE.runKernel(ArgMin, inputs, attrs);
    }
    var argMin = /* @__PURE__ */ op({ argMin_ });
    function asin_(x) {
      var $x = convertToTensor(x, "x", "asin");
      var inputs = { x: $x };
      return ENGINE.runKernel(Asin, inputs);
    }
    var asin = /* @__PURE__ */ op({ asin_ });
    function asinh_(x) {
      var $x = convertToTensor(x, "x", "asinh");
      var inputs = { x: $x };
      return ENGINE.runKernel(Asinh, inputs);
    }
    var asinh = /* @__PURE__ */ op({ asinh_ });
    function atan_(x) {
      var $x = convertToTensor(x, "x", "atan");
      var inputs = { x: $x };
      return ENGINE.runKernel(Atan, inputs);
    }
    var atan = /* @__PURE__ */ op({ atan_ });
    function atan2_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "atan2");
      var $b = convertToTensor(b, "b", "atan2");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Atan2, inputs);
    }
    var atan2 = /* @__PURE__ */ op({ atan2_ });
    function atanh_(x) {
      var $x = convertToTensor(x, "x", "atanh");
      var inputs = { x: $x };
      return ENGINE.runKernel(Atanh, inputs);
    }
    var atanh = /* @__PURE__ */ op({ atanh_ });
    function cast_(x, dtype) {
      var $x = convertToTensor(x, "x", "cast");
      if (!isValidDtype(dtype)) {
        throw new Error("Failed to cast to unknown dtype ".concat(dtype));
      }
      if (dtype === "string" && $x.dtype !== "string" || dtype !== "string" && $x.dtype === "string") {
        throw new Error("Only strings can be casted to strings");
      }
      var inputs = { x: $x };
      var attrs = { dtype };
      return ENGINE.runKernel(Cast, inputs, attrs);
    }
    var cast = /* @__PURE__ */ op({ cast_ });
    function computePool2DInfo(inShape, filterSize, strides, dilations, pad2, roundingMode, dataFormat) {
      if (dataFormat === void 0) {
        dataFormat = "channelsLast";
      }
      var _a = __read(parseTupleParam(filterSize), 2), filterHeight = _a[0], filterWidth = _a[1];
      var filterShape;
      if (dataFormat === "channelsLast") {
        filterShape = [filterHeight, filterWidth, inShape[3], inShape[3]];
      } else if (dataFormat === "channelsFirst") {
        filterShape = [filterHeight, filterWidth, inShape[1], inShape[1]];
      } else {
        throw new Error("Unknown dataFormat ".concat(dataFormat));
      }
      return computeConv2DInfo(inShape, filterShape, strides, dilations, pad2, roundingMode, false, dataFormat);
    }
    function computeConv2DInfo(inShape, filterShape, strides, dilations, pad2, roundingMode, depthwise, dataFormat) {
      var _a, _b;
      if (depthwise === void 0) {
        depthwise = false;
      }
      if (dataFormat === void 0) {
        dataFormat = "channelsLast";
      }
      var _c = __read([-1, -1, -1, -1], 4), batchSize = _c[0], inHeight = _c[1], inWidth = _c[2], inChannels = _c[3];
      if (dataFormat === "channelsLast") {
        _a = __read(inShape, 4), batchSize = _a[0], inHeight = _a[1], inWidth = _a[2], inChannels = _a[3];
      } else if (dataFormat === "channelsFirst") {
        _b = __read(inShape, 4), batchSize = _b[0], inChannels = _b[1], inHeight = _b[2], inWidth = _b[3];
      } else {
        throw new Error("Unknown dataFormat ".concat(dataFormat));
      }
      var _d = __read(filterShape, 4), filterHeight = _d[0], filterWidth = _d[1], filterChannels = _d[3];
      var _e = __read(parseTupleParam(strides), 2), strideHeight = _e[0], strideWidth = _e[1];
      var _f = __read(parseTupleParam(dilations), 2), dilationHeight = _f[0], dilationWidth = _f[1];
      var effectiveFilterHeight = getEffectiveFilterSize(filterHeight, dilationHeight);
      var effectiveFilterWidth = getEffectiveFilterSize(filterWidth, dilationWidth);
      var _g = getPadAndOutInfo(pad2, inHeight, inWidth, strideHeight, strideWidth, effectiveFilterHeight, effectiveFilterWidth, roundingMode, dataFormat), padInfo = _g.padInfo, outHeight = _g.outHeight, outWidth = _g.outWidth;
      var outChannels = depthwise ? filterChannels * inChannels : filterChannels;
      var outShape;
      if (dataFormat === "channelsFirst") {
        outShape = [batchSize, outChannels, outHeight, outWidth];
      } else if (dataFormat === "channelsLast") {
        outShape = [batchSize, outHeight, outWidth, outChannels];
      }
      return {
        batchSize,
        dataFormat,
        inHeight,
        inWidth,
        inChannels,
        outHeight,
        outWidth,
        outChannels,
        padInfo,
        strideHeight,
        strideWidth,
        filterHeight,
        filterWidth,
        effectiveFilterHeight,
        effectiveFilterWidth,
        dilationHeight,
        dilationWidth,
        inShape,
        outShape,
        filterShape
      };
    }
    function computeOutputShape2D(inShape, fieldSize, stride, zeroPad, roundingMode) {
      if (zeroPad == null) {
        zeroPad = computeDefaultPad(inShape, fieldSize, stride);
      }
      var inputRows = inShape[0];
      var inputCols = inShape[1];
      var outputRows = round$1((inputRows - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
      var outputCols = round$1((inputCols - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
      return [outputRows, outputCols];
    }
    function computeDefaultPad(inputShape, fieldSize, stride, dilation) {
      if (dilation === void 0) {
        dilation = 1;
      }
      var effectiveFieldSize = getEffectiveFilterSize(fieldSize, dilation);
      return Math.floor((inputShape[0] * (stride - 1) - stride + effectiveFieldSize) / 2);
    }
    function parseTupleParam(param) {
      if (typeof param === "number") {
        return [param, param, param];
      }
      if (param.length === 2) {
        return [param[0], param[1], 1];
      }
      return param;
    }
    function getEffectiveFilterSize(filterSize, dilation) {
      if (dilation <= 1) {
        return filterSize;
      }
      return filterSize + (filterSize - 1) * (dilation - 1);
    }
    function getPadAndOutInfo(pad2, inHeight, inWidth, strideHeight, strideWidth, filterHeight, filterWidth, roundingMode, dataFormat) {
      var padInfo;
      var outHeight;
      var outWidth;
      if (typeof pad2 === "number") {
        var padType = pad2 === 0 ? "VALID" : "NUMBER";
        padInfo = { top: pad2, bottom: pad2, left: pad2, right: pad2, type: padType };
        var outShape = computeOutputShape2D([inHeight, inWidth], filterHeight, strideHeight, pad2, roundingMode);
        outHeight = outShape[0];
        outWidth = outShape[1];
      } else if (pad2 === "same") {
        outHeight = Math.ceil(inHeight / strideHeight);
        outWidth = Math.ceil(inWidth / strideWidth);
        var padAlongHeight = Math.max(0, (outHeight - 1) * strideHeight + filterHeight - inHeight);
        var padAlongWidth = Math.max(0, (outWidth - 1) * strideWidth + filterWidth - inWidth);
        var top = Math.floor(padAlongHeight / 2);
        var bottom = padAlongHeight - top;
        var left = Math.floor(padAlongWidth / 2);
        var right = padAlongWidth - left;
        padInfo = { top, bottom, left, right, type: "SAME" };
      } else if (pad2 === "valid") {
        padInfo = { top: 0, bottom: 0, left: 0, right: 0, type: "VALID" };
        outHeight = Math.ceil((inHeight - filterHeight + 1) / strideHeight);
        outWidth = Math.ceil((inWidth - filterWidth + 1) / strideWidth);
      } else if (typeof pad2 === "object") {
        var top = dataFormat === "channelsLast" ? pad2[1][0] : pad2[2][0];
        var bottom = dataFormat === "channelsLast" ? pad2[1][1] : pad2[2][1];
        var left = dataFormat === "channelsLast" ? pad2[2][0] : pad2[3][0];
        var right = dataFormat === "channelsLast" ? pad2[2][1] : pad2[3][1];
        var padType = top === 0 && bottom === 0 && left === 0 && right === 0 ? "VALID" : "EXPLICIT";
        padInfo = { top, bottom, left, right, type: padType };
        outHeight = round$1((inHeight - filterHeight + top + bottom) / strideHeight + 1, roundingMode);
        outWidth = round$1((inWidth - filterWidth + left + right) / strideWidth + 1, roundingMode);
      } else {
        throw Error("Unknown padding parameter: ".concat(pad2));
      }
      return { padInfo, outHeight, outWidth };
    }
    function round$1(value, roundingMode) {
      if (!roundingMode) {
        return Math.trunc(value);
      }
      switch (roundingMode) {
        case "round":
          return Math.round(value);
        case "ceil":
          return Math.ceil(value);
        case "floor":
          return Math.floor(value);
        default:
          throw new Error("Unknown roundingMode ".concat(roundingMode));
      }
    }
    function tupleValuesAreOne(param) {
      var _a = __read(parseTupleParam(param), 3), dimA = _a[0], dimB = _a[1], dimC = _a[2];
      return dimA === 1 && dimB === 1 && dimC === 1;
    }
    function eitherStridesOrDilationsAreOne(strides, dilations) {
      return tupleValuesAreOne(strides) || tupleValuesAreOne(dilations);
    }
    function stridesOrDilationsArePositive(values) {
      return parseTupleParam(values).every(function(value) {
        return value > 0;
      });
    }
    function checkPadOnDimRoundingMode(opDesc, pad2, dimRoundingMode) {
      if (dimRoundingMode != null) {
        if (typeof pad2 === "string") {
          throw Error("Error in ".concat(opDesc, ": pad must be an integer when using ") + "dimRoundingMode ".concat(dimRoundingMode, " but got pad ").concat(pad2, "."));
        } else if (typeof pad2 === "number") {
          assert(isInt(pad2), function() {
            return "Error in ".concat(opDesc, ": pad must be an integer when using ") + "dimRoundingMode ".concat(dimRoundingMode, " but got pad ").concat(pad2, ".");
          });
        } else if (typeof pad2 === "object") {
          pad2.forEach(function(p) {
            p.forEach(function(v) {
              assert(isInt(v), function() {
                return "Error in ".concat(opDesc, ": pad must be an integer when using ") + "dimRoundingMode ".concat(dimRoundingMode, " but got pad ").concat(v, ".");
              });
            });
          });
        } else {
          throw Error("Error in ".concat(opDesc, ": Unknown padding parameter: ").concat(pad2));
        }
      }
    }
    function reshape_(x, shape) {
      var $x = convertToTensor(x, "x", "reshape", "string_or_numeric");
      var inputs = { x: $x };
      var attrs = { shape };
      return ENGINE.runKernel(Reshape, inputs, attrs);
    }
    var reshape = /* @__PURE__ */ op({ reshape_ });
    function avgPool_(x, filterSize, strides, pad2, dimRoundingMode) {
      var $x = convertToTensor(x, "x", "avgPool", "float32");
      var dilations = 1;
      assert(eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in avgPool: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, function() {
        return "Error in avgPool: x must be rank 4 but got rank ".concat(x4D.rank, ".");
      });
      checkPadOnDimRoundingMode("avgPool", pad2, dimRoundingMode);
      var inputs = { x: x4D };
      var attrs = { filterSize, strides, pad: pad2, dimRoundingMode };
      var res = ENGINE.runKernel(AvgPool, inputs, attrs);
      res = cast(res, $x.dtype);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var avgPool = /* @__PURE__ */ op({ avgPool_ });
    function avgPool3d_(x, filterSize, strides, pad2, dimRoundingMode, dataFormat) {
      if (dataFormat === void 0) {
        dataFormat = "NDHWC";
      }
      var $x = convertToTensor(x, "x", "avgPool3d", "float32");
      var x5D = $x;
      var reshapedTo5D = false;
      if ($x.rank === 4) {
        reshapedTo5D = true;
        x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
      }
      assert(x5D.rank === 5, function() {
        return "Error in avgPool3d: x must be rank 5 but got rank ".concat(x5D.rank, ".");
      });
      assert(dataFormat === "NDHWC", function() {
        return "Error in avgPool3d: Only NDHWC is currently supported, " + "but got dataFormat of ".concat(dataFormat);
      });
      assert(typeof strides === "number" && strides > 0 || Array.isArray(strides) && strides[0] > 0 && strides[1] > 0 && strides[2] > 0, function() {
        return "Error in avgPool3d: Stride must be > 0, but got '".concat(strides, "'");
      });
      checkPadOnDimRoundingMode("avgPool3d", pad2, dimRoundingMode);
      var inputs = { x: x5D };
      var attrs = { filterSize, strides, pad: pad2, dimRoundingMode, dataFormat };
      var res = ENGINE.runKernel(AvgPool3D, inputs, attrs);
      res = cast(res, x5D.dtype);
      if (reshapedTo5D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
      }
      return res;
    }
    var avgPool3d = /* @__PURE__ */ op({ avgPool3d_ });
    function clone_(x) {
      var $x = convertToTensor(x, "x", "clone", "string_or_numeric");
      var inputs = { x: $x };
      return ENGINE.runKernel(Identity, inputs);
    }
    var clone = /* @__PURE__ */ op({ clone_ });
    function concat_(tensors, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      assert(tensors.length >= 1, function() {
        return "Pass at least one tensor to concat";
      });
      var $tensors = convertToTensorArray(tensors, "tensors", "concat", "string_or_numeric");
      if ($tensors[0].dtype === "complex64") {
        $tensors.forEach(function(tensor2) {
          if (tensor2.dtype !== "complex64") {
            throw new Error("Cannot concatenate complex64 tensors with a tensor\n          with dtype ".concat(tensor2.dtype, ". "));
          }
        });
      }
      if ($tensors.length === 1) {
        return clone($tensors[0]);
      }
      var inputs = $tensors;
      var attr = { axis };
      return ENGINE.runKernel(Concat, inputs, attr);
    }
    var concat = /* @__PURE__ */ op({ concat_ });
    function matMul_(a, b, transposeA, transposeB) {
      var _a;
      if (transposeA === void 0) {
        transposeA = false;
      }
      if (transposeB === void 0) {
        transposeB = false;
      }
      var $a = convertToTensor(a, "a", "matMul");
      var $b = convertToTensor(b, "b", "matMul");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      var inputs = { a: $a, b: $b };
      var attrs = { transposeA, transposeB };
      return ENGINE.runKernel(BatchMatMul, inputs, attrs);
    }
    var matMul$1 = /* @__PURE__ */ op({ matMul_ });
    function mul_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "mul");
      var $b = convertToTensor(b, "b", "mul");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Multiply, inputs);
    }
    var mul = /* @__PURE__ */ op({ mul_ });
    function sigmoid_(x) {
      var $x = convertToTensor(x, "x", "sigmoid", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Sigmoid, inputs);
    }
    var sigmoid = /* @__PURE__ */ op({ sigmoid_ });
    function slice_(x, begin, size) {
      var $x = convertToTensor(x, "x", "slice", "string_or_numeric");
      if ($x.rank === 0) {
        throw new Error("Slicing scalar is not possible");
      }
      var inputs = { x: $x };
      var attrs = { begin, size };
      return ENGINE.runKernel(Slice, inputs, attrs);
    }
    var slice = /* @__PURE__ */ op({ slice_ });
    function tanh_(x) {
      var $x = convertToTensor(x, "x", "tanh", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Tanh, inputs);
    }
    var tanh = /* @__PURE__ */ op({ tanh_ });
    function basicLSTMCell_(forgetBias, lstmKernel, lstmBias, data, c, h) {
      var $forgetBias = convertToTensor(forgetBias, "forgetBias", "basicLSTMCell");
      var $lstmKernel = convertToTensor(lstmKernel, "lstmKernel", "basicLSTMCell");
      var $lstmBias = convertToTensor(lstmBias, "lstmBias", "basicLSTMCell");
      var $data = convertToTensor(data, "data", "basicLSTMCell");
      var $c = convertToTensor(c, "c", "basicLSTMCell");
      var $h = convertToTensor(h, "h", "basicLSTMCell");
      var combined = concat([$data, $h], 1);
      var weighted = matMul$1(combined, $lstmKernel);
      var res = add(weighted, $lstmBias);
      var batchSize = res.shape[0];
      var sliceCols = res.shape[1] / 4;
      var sliceSize = [batchSize, sliceCols];
      var i = slice(res, [0, 0], sliceSize);
      var j = slice(res, [0, sliceCols], sliceSize);
      var f = slice(res, [0, sliceCols * 2], sliceSize);
      var o = slice(res, [0, sliceCols * 3], sliceSize);
      var newC = add(mul(sigmoid(i), tanh(j)), mul($c, sigmoid(add($forgetBias, f))));
      var newH = mul(tanh(newC), sigmoid(o));
      return [newC, newH];
    }
    var basicLSTMCell = /* @__PURE__ */ op({ basicLSTMCell_ });
    function batchToSpaceND_(x, blockShape, crops) {
      var $x = convertToTensor(x, "x", "batchToSpaceND");
      var prod2 = blockShape.reduce(function(a, b) {
        return a * b;
      });
      assert($x.rank >= 1 + blockShape.length, function() {
        return "input rank is ".concat($x.rank, " but should be > than blockShape.length ").concat(blockShape.length);
      });
      assert(crops.length === blockShape.length, function() {
        return "crops.length is ".concat(crops.length, " but should be equal to blockShape.length  ").concat(blockShape.length);
      });
      assert($x.shape[0] % prod2 === 0, function() {
        return "input tensor batch is ".concat($x.shape[0], " but is not divisible by the product of ") + "the elements of blockShape ".concat(blockShape.join(" * "), " === ").concat(prod2);
      });
      var inputs = { x: $x };
      var attrs = { blockShape, crops };
      return ENGINE.runKernel(BatchToSpaceND, inputs, attrs);
    }
    var batchToSpaceND = /* @__PURE__ */ op({ batchToSpaceND_ });
    function xAs4D(x) {
      var x4D;
      if (x.rank === 0 || x.rank === 1) {
        x4D = reshape(x, [1, 1, 1, x.size]);
      } else if (x.rank === 2) {
        x4D = reshape(x, [1, 1, x.shape[0], x.shape[1]]);
      } else if (x.rank === 3) {
        x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
      } else {
        x4D = x;
      }
      return x4D;
    }
    function batchNorm_(x, mean2, variance, offset, scale, varianceEpsilon) {
      if (varianceEpsilon == null) {
        varianceEpsilon = 1e-3;
      }
      var $x = convertToTensor(x, "x", "batchNorm");
      var $mean = convertToTensor(mean2, "mean", "batchNorm");
      var $variance = convertToTensor(variance, "variance", "batchNorm");
      var $scale;
      if (scale != null) {
        $scale = convertToTensor(scale, "scale", "batchNorm");
      }
      var $offset;
      if (offset != null) {
        $offset = convertToTensor(offset, "offset", "batchNorm");
      }
      assert($mean.rank === $variance.rank, function() {
        return "Batch normalization gradient requires mean and variance to have equal ranks.";
      });
      assert($offset == null || $mean.rank === $offset.rank, function() {
        return "Batch normalization gradient requires mean and offset to have equal ranks.";
      });
      assert($scale == null || $mean.rank === $scale.rank, function() {
        return "Batch normalization gradient requires mean and scale to have equal ranks.";
      });
      var x4D = xAs4D($x);
      var inputs = {
        x: x4D,
        scale: $scale,
        offset: $offset,
        mean: $mean,
        variance: $variance
      };
      var attrs = { varianceEpsilon };
      var res = ENGINE.runKernel(FusedBatchNorm, inputs, attrs);
      return reshape(res, $x.shape);
    }
    var batchNorm = /* @__PURE__ */ op({ batchNorm_ });
    function batchNorm2d_(x, mean2, variance, offset, scale, varianceEpsilon) {
      var $x = convertToTensor(x, "x", "batchNorm");
      var $mean = convertToTensor(mean2, "mean", "batchNorm");
      var $variance = convertToTensor(variance, "variance", "batchNorm");
      var $scale;
      if (scale != null) {
        $scale = convertToTensor(scale, "scale", "batchNorm");
      }
      var $offset;
      if (offset != null) {
        $offset = convertToTensor(offset, "offset", "batchNorm");
      }
      assert($x.rank === 2, function() {
        return "Error in batchNorm2D: x must be rank 2 but got rank " + "".concat($x.rank, ".");
      });
      assert($mean.rank === 2 || $mean.rank === 1, function() {
        return "Error in batchNorm2D: mean must be rank 2 or rank 1 but " + "got rank ".concat($mean.rank, ".");
      });
      assert($variance.rank === 2 || $variance.rank === 1, function() {
        return "Error in batchNorm2D: variance must be rank 2 or rank 1 " + "but got rank ".concat($variance.rank, ".");
      });
      if ($scale != null) {
        assert($scale.rank === 2 || $scale.rank === 1, function() {
          return "Error in batchNorm2D: scale must be rank 2 or rank 1 " + "but got rank ".concat($scale.rank, ".");
        });
      }
      if ($offset != null) {
        assert($offset.rank === 2 || $offset.rank === 1, function() {
          return "Error in batchNorm2D: offset must be rank 2 or rank 1 " + "but got rank ".concat($offset.rank, ".");
        });
      }
      return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);
    }
    var batchNorm2d = /* @__PURE__ */ op({ batchNorm2d_ });
    function batchNorm3d_(x, mean2, variance, offset, scale, varianceEpsilon) {
      var $x = convertToTensor(x, "x", "batchNorm");
      var $mean = convertToTensor(mean2, "mean", "batchNorm");
      var $variance = convertToTensor(variance, "variance", "batchNorm");
      var $scale;
      if (scale != null) {
        $scale = convertToTensor(scale, "scale", "batchNorm");
      }
      var $offset;
      if (offset != null) {
        $offset = convertToTensor(offset, "offset", "batchNorm");
      }
      assert($x.rank === 3, function() {
        return "Error in batchNorm3D: x must be rank 3 but got rank " + "".concat($x.rank, ".");
      });
      assert($mean.rank === 3 || $mean.rank === 1, function() {
        return "Error in batchNorm3D: mean must be rank 3 or rank 1 but " + "got rank ".concat($mean.rank, ".");
      });
      assert($variance.rank === 3 || $variance.rank === 1, function() {
        return "Error in batchNorm3D: variance must be rank 3 or rank 1 " + "but got rank ".concat($variance.rank, ".");
      });
      if ($scale != null) {
        assert($scale.rank === 3 || $scale.rank === 1, function() {
          return "Error in batchNorm3D: scale must be rank 3 or rank 1 " + "but got rank ".concat($scale.rank, ".");
        });
      }
      if ($offset != null) {
        assert($offset.rank === 3 || $offset.rank === 1, function() {
          return "Error in batchNorm3D: offset must be rank 3 or rank 1 " + "but got rank ".concat($offset.rank, ".");
        });
      }
      return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);
    }
    var batchNorm3d = /* @__PURE__ */ op({ batchNorm3d_ });
    function batchNorm4d_(x, mean2, variance, offset, scale, varianceEpsilon) {
      var $x = convertToTensor(x, "x", "batchNorm");
      var $mean = convertToTensor(mean2, "mean", "batchNorm");
      var $variance = convertToTensor(variance, "variance", "batchNorm");
      var $scale;
      if (scale != null) {
        $scale = convertToTensor(scale, "scale", "batchNorm");
      }
      var $offset;
      if (offset != null) {
        $offset = convertToTensor(offset, "offset", "batchNorm");
      }
      assert($x.rank === 4, function() {
        return "Error in batchNorm4D: x must be rank 4 but got rank " + "".concat($x.rank, ".");
      });
      assert($mean.rank === 4 || $mean.rank === 1, function() {
        return "Error in batchNorm4D: mean must be rank 4 or rank 1 but " + "got rank ".concat($mean.rank, ".");
      });
      assert($variance.rank === 4 || $variance.rank === 1, function() {
        return "Error in batchNorm4D: variance must be rank 4 or rank 1 " + "but got rank ".concat($variance.rank, ".");
      });
      if ($scale != null) {
        assert($scale.rank === 4 || $scale.rank === 1, function() {
          return "Error in batchNorm4D: scale must be rank 4 or rank 1 " + "but got rank ".concat($scale.rank, ".");
        });
      }
      if ($offset != null) {
        assert($offset.rank === 4 || $offset.rank === 1, function() {
          return "Error in batchNorm4D: offset must be rank 4 or rank 1 " + "but got rank ".concat($offset.rank, ".");
        });
      }
      return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);
    }
    var batchNorm4d = /* @__PURE__ */ op({ batchNorm4d_ });
    function bincount_(x, weights, size) {
      var $x = convertToTensor(x, "x", "bincount");
      var $weights = convertToTensor(weights, "weights", "bincount");
      assert($x.dtype === "int32", function() {
        return "Error in bincount: input " + "dtype must be int32, but got ".concat($x.dtype);
      });
      assert(size >= 0, function() {
        return "size must be non-negative, but got ".concat(size, ".");
      });
      assert($weights.size === $x.size || $weights.size === 0, function() {
        return "Error in bincount: weights must have the same size as input or" + "0-length, but got input shape: ".concat($x.shape, ", weights shape: ") + "".concat($weights.shape, ".");
      });
      var inputs = { x: $x, weights: $weights };
      var attrs = { size };
      return ENGINE.runKernel(Bincount, inputs, attrs);
    }
    var bincount = /* @__PURE__ */ op({ bincount_ });
    function bitwiseAnd_(x, y) {
      var $x = convertToTensor(x, "x", "bitwiseAnd");
      var $y = convertToTensor(y, "y", "bitwiseAnd");
      if (!arraysEqual($x.shape, $y.shape)) {
        throw new Error("BitwiseAnd: Tensors must have the same shape. x: ".concat($x.shape, ", y: ").concat($y.shape));
      }
      if ($x.dtype !== "int32" || $y.dtype !== "int32") {
        throw new Error("BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ".concat($x.dtype, " and type of y: ").concat($y.dtype));
      }
      var inputs = { a: $x, b: $y };
      return ENGINE.runKernel(BitwiseAnd, inputs);
    }
    var bitwiseAnd = /* @__PURE__ */ op({ bitwiseAnd_ });
    function broadcastArgs_(s0, s1) {
      var shape1Input = convertToTensor(s0, "s0", "broadcastArgs", "int32");
      var shape2Input = convertToTensor(s1, "s1", "broadcastArgs", "int32");
      if (shape1Input.rank !== 1) {
        throw new Error("broadcastArgs(): first input must be a vector (rank=1). " + "Has rank ".concat(shape1Input.rank));
      }
      if (shape2Input.rank !== 1) {
        throw new Error("broadcastArgs(): second input must be a vector (rank=1). " + "Has rank ".concat(shape2Input.rank));
      }
      var inputs = { s0: shape1Input, s1: shape2Input };
      return ENGINE.runKernel(BroadcastArgs, inputs);
    }
    var broadcastArgs = /* @__PURE__ */ op({ broadcastArgs_ });
    function broadcastTo_(x, shape) {
      var input = convertToTensor(x, "broadcastTo", "x");
      var xShape = input.shape;
      assertNonNegativeIntegerDimensions(shape);
      if (shape.length < input.rank) {
        throw new Error("broadcastTo(): shape.length=".concat(shape.length, " < input.rank=").concat(input.rank, "."));
      }
      if (shape.length > input.rank) {
        var newShape = input.shape.slice();
        while (newShape.length < shape.length) {
          newShape.unshift(1);
        }
        input = reshape(input, newShape);
      }
      var inputShape = input.shape;
      var reps = Array.from(shape);
      for (var i = shape.length - 1; i >= 0; i--) {
        if (inputShape[i] === shape[i]) {
          reps[i] = 1;
        } else if (input.shape[i] !== 1) {
          throw new Error("broadcastTo(): [".concat(xShape, "] cannot be broadcast to [").concat(shape, "]."));
        }
      }
      var axes = reps.map(function(n, i2) {
        return n > 1 ? i2 : -1;
      }).filter(function(i2) {
        return i2 >= 0;
      });
      if (axes.length === 0) {
        return clone(input);
      }
      var inputs = { x: input };
      var attrs = { reps };
      return ENGINE.runKernel(Tile, inputs, attrs);
    }
    var broadcastTo = /* @__PURE__ */ op({ broadcastTo_ });
    function buffer(shape, dtype, values) {
      if (dtype === void 0) {
        dtype = "float32";
      }
      dtype = dtype || "float32";
      assertNonNegativeIntegerDimensions(shape);
      return new TensorBuffer(shape, dtype, values);
    }
    function ceil_(x) {
      var $x = convertToTensor(x, "x", "ceil", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Ceil, inputs);
    }
    var ceil = /* @__PURE__ */ op({ ceil_ });
    function fill(shape, value, dtype) {
      assertNonNegativeIntegerDimensions(shape);
      dtype = dtype || inferDtype(value);
      var attrs = { shape, value, dtype };
      return ENGINE.runKernel(Fill, {}, attrs);
    }
    function clipByValue_(x, clipValueMin, clipValueMax) {
      var $x = convertToTensor(x, "x", "clipByValue");
      assert(clipValueMin <= clipValueMax, function() {
        return "Error in clip: min (".concat(clipValueMin, ") must be ") + "less than or equal to max (".concat(clipValueMax, ").");
      });
      if (clipValueMin === clipValueMax) {
        return fill($x.shape, clipValueMin, $x.dtype);
      }
      var inputs = { x: $x };
      var attrs = { clipValueMin, clipValueMax };
      return ENGINE.runKernel(ClipByValue, inputs, attrs);
    }
    var clipByValue = /* @__PURE__ */ op({ clipByValue_ });
    function complex_(real2, imag2) {
      var $real = convertToTensor(real2, "real", "complex");
      var $imag = convertToTensor(imag2, "imag", "complex");
      assertShapesMatch($real.shape, $imag.shape, "real and imag shapes, ".concat($real.shape, " and ").concat($imag.shape, ", ") + "must match in call to tf.complex().");
      var inputs = { real: $real, imag: $imag };
      return ENGINE.runKernel(Complex, inputs);
    }
    var complex = /* @__PURE__ */ op({ complex_ });
    function concat1d_(tensors) {
      return concat(
        tensors,
        0
        /* axis */
      );
    }
    var concat1d = /* @__PURE__ */ op({ concat1d_ });
    function concat2d_(tensors, axis) {
      return concat(tensors, axis);
    }
    var concat2d = /* @__PURE__ */ op({ concat2d_ });
    function concat3d_(tensors, axis) {
      return concat(tensors, axis);
    }
    var concat3d = /* @__PURE__ */ op({ concat3d_ });
    function concat4d_(tensors, axis) {
      return concat(tensors, axis);
    }
    var concat4d = /* @__PURE__ */ op({ concat4d_ });
    function conv2d_(x, filter, strides, pad2, dataFormat, dilations, dimRoundingMode) {
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      if (dilations === void 0) {
        dilations = [1, 1];
      }
      var $x = convertToTensor(x, "x", "conv2d", "float32");
      var $filter = convertToTensor(filter, "filter", "conv2d", "float32");
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, function() {
        return "Error in conv2d: input must be rank 4, but got rank ".concat(x4D.rank, ".");
      });
      assert($filter.rank === 4, function() {
        return "Error in conv2d: filter must be rank 4, but got rank " + "".concat($filter.rank, ".");
      });
      checkPadOnDimRoundingMode("conv2d", pad2, dimRoundingMode);
      var inDepth = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
      assert(inDepth === $filter.shape[2], function() {
        return "Error in conv2d: depth of input (".concat(inDepth, ") must match ") + "input depth for filter ".concat($filter.shape[2], ".");
      });
      assert(eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in conv2D: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      assert(stridesOrDilationsArePositive(dilations), function() {
        return "Error in conv2D: Dilated rates should be larger than 0.";
      });
      assert(stridesOrDilationsArePositive(strides), function() {
        return "Error in conv2D: Strides should be larger than 0.";
      });
      var inputs = { x: x4D, filter: $filter };
      var attrs = { strides, pad: pad2, dataFormat, dilations, dimRoundingMode };
      var res = ENGINE.runKernel(Conv2D, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var conv2d$1 = /* @__PURE__ */ op({ conv2d_ });
    function conv1d_(x, filter, stride, pad2, dataFormat, dilation, dimRoundingMode) {
      if (dataFormat === void 0) {
        dataFormat = "NWC";
      }
      if (dilation === void 0) {
        dilation = 1;
      }
      var $x = convertToTensor(x, "x", "conv1d");
      var $filter = convertToTensor(filter, "filter", "conv1d");
      var x3D = $x;
      var reshapedTo3D = false;
      if ($x.rank === 2) {
        reshapedTo3D = true;
        x3D = reshape($x, [1, $x.shape[0], $x.shape[1]]);
      }
      assert(x3D.rank === 3, function() {
        return "Error in conv1d: input must be rank 3, but got rank ".concat(x3D.rank, ".");
      });
      assert($filter.rank === 3, function() {
        return "Error in conv1d: filter must be rank 3, but got rank " + "".concat($filter.rank, ".");
      });
      checkPadOnDimRoundingMode("conv1d", pad2, dimRoundingMode);
      assert(x3D.shape[2] === $filter.shape[1], function() {
        return "Error in conv1d: depth of input (".concat(x3D.shape[2], ") must match ") + "input depth for filter ".concat($filter.shape[1], ".");
      });
      assert(eitherStridesOrDilationsAreOne(stride, dilation), function() {
        return "Error in conv1D: Either stride or dilation must be 1. " + "Got stride ".concat(stride, " and dilation '").concat(dilation, "'");
      });
      assert(stridesOrDilationsArePositive(dilation), function() {
        return "Error in conv1D: Dilated rates should be larger than 0.";
      });
      assert(stridesOrDilationsArePositive(stride), function() {
        return "Error in conv1D: Stride should be larger than 0.";
      });
      assert(dataFormat === "NWC", function() {
        return "Error in conv1d: got dataFormat of ".concat(dataFormat, " but only NWC is currently supported.");
      });
      var filter4D = reshape($filter, [1, $filter.shape[0], $filter.shape[1], $filter.shape[2]]);
      var input4D = reshape(x3D, [x3D.shape[0], 1, x3D.shape[1], x3D.shape[2]]);
      var strides = [1, stride];
      var dilations = [1, dilation];
      var conv2dDataFormat = "NHWC";
      var res = conv2d$1(input4D, filter4D, strides, pad2, conv2dDataFormat, dilations, dimRoundingMode);
      if (reshapedTo3D) {
        return reshape(res, [res.shape[2], res.shape[3]]);
      }
      return reshape(res, [res.shape[0], res.shape[2], res.shape[3]]);
    }
    var conv1d = /* @__PURE__ */ op({ conv1d_ });
    function conv2DBackpropInput_(xShape, dy, filter, strides, pad2, dataFormat, dimRoundingMode) {
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      assert(xShape.length === dy.rank, function() {
        return "Length of inShape " + "(".concat(xShape.length, ") and rank of dy (").concat(dy.rank, ") must match");
      });
      var xShape4D = xShape;
      var dy4D = dy;
      var reshapedTo4D = false;
      if (dy.rank === 3) {
        reshapedTo4D = true;
        dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
        xShape4D = [1, xShape[0], xShape[1], xShape[2]];
      }
      assert(xShape4D.length === 4, function() {
        return "Error in conv2dDerInput: inShape must be length 4, but got length " + "".concat(xShape4D.length, ".");
      });
      assert(dy4D.rank === 4, function() {
        return "Error in conv2dDerInput: dy must be rank 4, but got " + "rank ".concat(dy4D.rank);
      });
      assert(filter.rank === 4, function() {
        return "Error in conv2dDerInput: filter must be rank 4, but got " + "rank ".concat(filter.rank);
      });
      var inDepth = dataFormat === "NHWC" ? xShape4D[3] : xShape4D[1];
      var outDepth = dataFormat === "NHWC" ? dy4D.shape[3] : dy4D.shape[1];
      assert(inDepth === filter.shape[2], function() {
        return "Error in conv2dDerInput: depth of input (".concat(inDepth, ") must ") + "match input depth for filter ".concat(filter.shape[2], ".");
      });
      assert(outDepth === filter.shape[3], function() {
        return "Error in conv2dDerInput: depth of output (".concat(outDepth, ") must ") + "match output depth for filter ".concat(filter.shape[3], ".");
      });
      checkPadOnDimRoundingMode("conv2dDerInput", pad2, dimRoundingMode);
      var inputs = { dy: dy4D, filter };
      var attrs = { strides, pad: pad2, dataFormat, dimRoundingMode, inputShape: xShape4D };
      var res = ENGINE.runKernel(Conv2DBackpropInput, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var conv2DBackpropInput = /* @__PURE__ */ op({ conv2DBackpropInput_ });
    function conv2dTranspose_(x, filter, outputShape, strides, pad2, dimRoundingMode) {
      var $x = convertToTensor(x, "x", "conv2dTranspose");
      var $filter = convertToTensor(filter, "filter", "conv2dTranspose");
      return conv2DBackpropInput(outputShape, $x, $filter, strides, pad2, "NHWC", dimRoundingMode);
    }
    var conv2dTranspose = /* @__PURE__ */ op({ conv2dTranspose_ });
    function conv3d_(x, filter, strides, pad2, dataFormat, dilations) {
      if (dataFormat === void 0) {
        dataFormat = "NDHWC";
      }
      if (dilations === void 0) {
        dilations = [1, 1, 1];
      }
      var $x = convertToTensor(x, "x", "conv3d");
      var $filter = convertToTensor(filter, "filter", "conv3d");
      var x5D = $x;
      var reshapedTo5D = false;
      if ($x.rank === 4) {
        reshapedTo5D = true;
        x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
      }
      assert(x5D.rank === 5, function() {
        return "Error in conv3d: input must be rank 5, but got rank ".concat(x5D.rank, ".");
      });
      assert($filter.rank === 5, function() {
        return "Error in conv3d: filter must be rank 5, but got rank " + "".concat($filter.rank, ".");
      });
      assert(x5D.shape[4] === $filter.shape[3], function() {
        return "Error in conv3d: depth of input (".concat(x5D.shape[4], ") must match ") + "input depth for filter ".concat($filter.shape[3], ".");
      });
      assert(eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in conv3D: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      assert(dataFormat === "NDHWC", function() {
        return "Error in conv3d: got dataFormat of ".concat(dataFormat, " but only NDHWC is currently supported.");
      });
      assert(stridesOrDilationsArePositive(dilations), function() {
        return "Error in conv3D: Dilated rates should be larger than 0.";
      });
      assert(stridesOrDilationsArePositive(strides), function() {
        return "Error in conv3D: Strides should be larger than 0.";
      });
      var inputs = { x: x5D, filter: $filter };
      var attrs = { strides, pad: pad2, dataFormat, dilations };
      var res = ENGINE.runKernel(Conv3D, inputs, attrs);
      if (reshapedTo5D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
      }
      return res;
    }
    var conv3d = /* @__PURE__ */ op({ conv3d_ });
    function conv3DBackpropInput_(xShape, dy, filter, strides, pad2) {
      assert(xShape.length === dy.rank, function() {
        return "Length of inShape " + "(".concat(xShape.length, ") and rank of dy (").concat(dy.rank, ") must match");
      });
      var xShape5D = xShape;
      var dy5D = dy;
      var reshapedTo5D = false;
      if (dy.rank === 4) {
        reshapedTo5D = true;
        dy5D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);
        xShape5D = [1, xShape[0], xShape[1], xShape[2], xShape[3]];
      }
      var inDepth = xShape5D[4];
      var outDepth = dy5D.shape[4];
      assert(xShape5D.length === 5, function() {
        return "Error in conv3dDerInput: inShape must be length 5, but got length " + "".concat(xShape5D.length, ".");
      });
      assert(dy5D.rank === 5, function() {
        return "Error in conv3dDerInput: dy must be rank 5, but got " + "rank ".concat(dy5D.rank);
      });
      assert(filter.rank === 5, function() {
        return "Error in conv3dDerInput: filter must be rank 5, but got " + "rank ".concat(filter.rank);
      });
      assert(inDepth === filter.shape[3], function() {
        return "Error in conv3dDerInput: depth of input (".concat(inDepth, ") must ") + "match input depth for filter ".concat(filter.shape[3], ".");
      });
      assert(outDepth === filter.shape[4], function() {
        return "Error in conv3dDerInput: depth of output (".concat(outDepth, ") must ") + "match output depth for filter ".concat(filter.shape[4], ".");
      });
      var inputs = { dy: dy5D, filter };
      var attrs = { pad: pad2, strides, inputShape: xShape5D };
      var res = ENGINE.runKernel(Conv3DBackpropInputV2, inputs, attrs);
      if (reshapedTo5D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
      }
      return res;
    }
    var conv3DBackpropInput = /* @__PURE__ */ op({ conv3DBackpropInput_ });
    function conv3dTranspose_(x, filter, outputShape, strides, pad2) {
      var $x = convertToTensor(x, "x", "conv3dTranspose");
      var $filter = convertToTensor(filter, "filter", "conv3dTranspose");
      return conv3DBackpropInput(outputShape, $x, $filter, strides, pad2);
    }
    var conv3dTranspose = /* @__PURE__ */ op({ conv3dTranspose_ });
    function cos_(x) {
      var $x = convertToTensor(x, "x", "cos", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Cos, inputs);
    }
    var cos = /* @__PURE__ */ op({ cos_ });
    function cosh_(x) {
      var $x = convertToTensor(x, "x", "cosh", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Cosh, inputs);
    }
    var cosh = /* @__PURE__ */ op({ cosh_ });
    function cumprod_(x, axis, exclusive, reverse2) {
      if (axis === void 0) {
        axis = 0;
      }
      if (exclusive === void 0) {
        exclusive = false;
      }
      if (reverse2 === void 0) {
        reverse2 = false;
      }
      var $x = convertToTensor(x, "x", "cumprod");
      var inputs = { x: $x };
      var attrs = { axis, exclusive, reverse: reverse2 };
      return ENGINE.runKernel(Cumprod, inputs, attrs);
    }
    var cumprod = /* @__PURE__ */ op({ cumprod_ });
    function cumsum_(x, axis, exclusive, reverse2) {
      if (axis === void 0) {
        axis = 0;
      }
      if (exclusive === void 0) {
        exclusive = false;
      }
      if (reverse2 === void 0) {
        reverse2 = false;
      }
      var $x = convertToTensor(x, "x", "cumsum");
      var inputs = { x: $x };
      var attrs = { axis, exclusive, reverse: reverse2 };
      return ENGINE.runKernel(Cumsum, inputs, attrs);
    }
    var cumsum = /* @__PURE__ */ op({ cumsum_ });
    function denseBincount_(x, weights, size, binaryOutput) {
      if (binaryOutput === void 0) {
        binaryOutput = false;
      }
      var $x = convertToTensor(x, "x", "denseBincount");
      var $weights = convertToTensor(weights, "weights", "denseBincount");
      assert($x.dtype === "int32", function() {
        return "Error in denseBincount: input " + "dtype must be int32, but got ".concat($x.dtype);
      });
      assert($x.rank <= 2, function() {
        return "Error in denseBincount: input must be at most rank 2, but got " + "rank ".concat($x.rank, ".");
      });
      assert(size >= 0, function() {
        return "size must be non-negative, but got ".concat(size, ".");
      });
      assert($weights.size === $x.size || $weights.size === 0, function() {
        return "Error in denseBincount: weights must have the same shape as x or " + "0-length, but got x shape: ".concat($x.shape, ", weights shape: ") + "".concat($weights.shape, ".");
      });
      var inputs = { x: $x, weights: $weights };
      var attrs = { size, binaryOutput };
      return ENGINE.runKernel(DenseBincount, inputs, attrs);
    }
    var denseBincount = /* @__PURE__ */ op({ denseBincount_ });
    function depthToSpace_(x, blockSize, dataFormat) {
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      var $x = convertToTensor(x, "x", "depthToSpace", "float32");
      var inputHeight = dataFormat === "NHWC" ? $x.shape[1] : $x.shape[2];
      var inputWidth = dataFormat === "NHWC" ? $x.shape[2] : $x.shape[3];
      var inputDepth = dataFormat === "NHWC" ? $x.shape[3] : $x.shape[1];
      assert(blockSize > 1, function() {
        return "blockSize should be > 1 for depthToSpace, but was: ".concat(blockSize);
      });
      assert(inputHeight * blockSize >= 0, function() {
        return "Negative dimension size caused by overflow when multiplying\n    ".concat(inputHeight, " and ").concat(blockSize, "  for depthToSpace with input shape\n    ").concat($x.shape);
      });
      assert(inputWidth * blockSize >= 0, function() {
        return "Negative dimension size caused by overflow when multiplying\n    ".concat(inputWidth, " and ").concat(blockSize, " for depthToSpace with input shape\n        ").concat($x.shape);
      });
      assert(inputDepth % (blockSize * blockSize) === 0, function() {
        return "Dimension size must be evenly divisible by ".concat(blockSize * blockSize, " but is ").concat(inputDepth, " for depthToSpace with input shape ").concat($x.shape);
      });
      var inputs = { x: $x };
      var attrs = { blockSize, dataFormat };
      return ENGINE.runKernel(DepthToSpace, inputs, attrs);
    }
    var depthToSpace = /* @__PURE__ */ op({ depthToSpace_ });
    function depthwiseConv2d_(x, filter, strides, pad2, dataFormat, dilations, dimRoundingMode) {
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      if (dilations === void 0) {
        dilations = [1, 1];
      }
      var $x = convertToTensor(x, "x", "depthwiseConv2d", "float32");
      var $filter = convertToTensor(filter, "filter", "depthwiseConv2d", "float32");
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, function() {
        return "Error in depthwiseConv2d: input must be rank 4, but got " + "rank ".concat(x4D.rank, ".");
      });
      assert($filter.rank === 4, function() {
        return "Error in depthwiseConv2d: filter must be rank 4, but got rank " + "".concat($filter.rank, ".");
      });
      var inChannels = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
      assert(inChannels === $filter.shape[2], function() {
        return "Error in depthwiseConv2d: number of input channels " + "(".concat(inChannels, ") must match the inChannels dimension in ") + "filter ".concat($filter.shape[2], ".");
      });
      checkPadOnDimRoundingMode("depthwiseConv2d", pad2, dimRoundingMode);
      var inputs = { x: x4D, filter: $filter };
      var attrs = { strides, pad: pad2, dataFormat, dilations, dimRoundingMode };
      var res = ENGINE.runKernel(DepthwiseConv2dNative, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var depthwiseConv2d$1 = /* @__PURE__ */ op({ depthwiseConv2d_ });
    function diag_(x) {
      var $x = convertToTensor(x, "x", "diag");
      var inputs = { x: $x };
      return ENGINE.runKernel(Diag, inputs);
    }
    var diag = /* @__PURE__ */ op({ diag_ });
    function dilation2d_(x, filter, strides, pad2, dilations, dataFormat) {
      if (dilations === void 0) {
        dilations = [1, 1];
      }
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      var $x = convertToTensor(x, "x", "dilation2d");
      var $filter = convertToTensor(filter, "filter", "dilation2d");
      assert($x.rank === 3 || $x.rank === 4, function() {
        return "Error in dilation2d: input must be rank 3 or 4, but got rank " + "".concat($x.rank, ".");
      });
      assert($filter.rank === 3, function() {
        return "Error in dilation2d: filter must be rank 3, but got rank " + "".concat($filter.rank, ".");
      });
      assert(dataFormat === "NHWC", function() {
        return "Error in dilation2d: Only NHWC is currently supported, " + "but got dataFormat of ".concat(dataFormat);
      });
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
        reshapedTo4D = true;
      }
      assert(x4D.shape[3] === $filter.shape[2], function() {
        return "Error in dilation2d:  input and filter must have the same depth: ".concat(x4D.shape[3], " vs ").concat($filter.shape[2]);
      });
      var inputs = { x: x4D, filter: $filter };
      var attrs = { strides, pad: pad2, dilations };
      var res = ENGINE.runKernel(Dilation2D, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var dilation2d = /* @__PURE__ */ op({ dilation2d_ });
    function floorDiv_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "floorDiv");
      var $b = convertToTensor(b, "b", "floorDiv");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(FloorDiv, inputs);
    }
    var floorDiv = /* @__PURE__ */ op({ floorDiv_ });
    function div_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "div");
      var $b = convertToTensor(b, "b", "div");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      if ($a.dtype === "int32" && $b.dtype === "int32") {
        return floorDiv($a, $b);
      }
      var inputs = { a: $a, b: $b };
      var attrs = {};
      return ENGINE.runKernel(RealDiv, inputs, attrs);
    }
    var div = /* @__PURE__ */ op({ div_ });
    function getReductionAxes(inShape, outShape) {
      var result = [];
      for (var i = 0; i < outShape.length; i++) {
        var inDim = inShape[inShape.length - i - 1];
        var outAxis = outShape.length - i - 1;
        var outDim = outShape[outAxis];
        if (inDim == null || inDim === 1 && outDim > 1) {
          result.unshift(outAxis);
        }
      }
      return result;
    }
    function assertAndGetBroadcastShape(shapeA, shapeB) {
      var l = Math.max(shapeA.length, shapeB.length);
      var result = new Array(l);
      for (var i = 0; i < l; i++) {
        var a = shapeA[shapeA.length - i - 1];
        if (a == null) {
          a = 1;
        }
        var b = shapeB[shapeB.length - i - 1];
        if (b == null) {
          b = 1;
        }
        if (a === 1) {
          result[l - i - 1] = b;
        } else if (b === 1) {
          result[l - i - 1] = a;
        } else if (a !== b) {
          var errMsg = "Operands could not be broadcast together with shapes " + "".concat(shapeA, " and ").concat(shapeB, ".");
          throw Error(errMsg);
        } else {
          result[l - i - 1] = a;
        }
      }
      return result;
    }
    function equal_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "equal", "string_or_numeric");
      var $b = convertToTensor(b, "b", "equal", "string_or_numeric");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Equal, inputs);
    }
    var equal = /* @__PURE__ */ op({ equal_ });
    function where_(condition, a, b) {
      var $a = convertToTensor(a, "a", "where");
      var $b = convertToTensor(b, "b", "where");
      var $condition = convertToTensor(condition, "condition", "where", "bool");
      var broadcastShape = assertAndGetBroadcastShape(assertAndGetBroadcastShape($condition.shape, $a.shape), $b.shape);
      var $broadcastedCondition = broadcastTo($condition, broadcastShape);
      var $broadcastedA = broadcastTo($a, broadcastShape);
      var $broadcastedB = broadcastTo($b, broadcastShape);
      var inputs = {
        condition: $broadcastedCondition,
        t: $broadcastedA,
        e: $broadcastedB
      };
      return ENGINE.runKernel(Select, inputs);
    }
    var where = /* @__PURE__ */ op({ where_ });
    function zerosLike_(x) {
      var $x = convertToTensor(x, "x", "zerosLike");
      var inputs = { x: $x };
      return ENGINE.runKernel(ZerosLike, inputs);
    }
    var zerosLike = /* @__PURE__ */ op({ zerosLike_ });
    function divNoNan_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "div");
      var $b = convertToTensor(b, "b", "div");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      var divResult = div($a, $b);
      var zeros2 = zerosLike(divResult);
      var bEqualsZero = equal($b, zeros2);
      return where(bEqualsZero, zeros2, divResult);
    }
    var divNoNan = /* @__PURE__ */ op({ divNoNan_ });
    function dot_(t1, t2) {
      var $t1 = convertToTensor(t1, "t1", "dot");
      var $t2 = convertToTensor(t2, "t2", "dot");
      assert(($t1.rank === 1 || $t1.rank === 2) && ($t2.rank === 1 || $t2.rank === 2), function() {
        return "Error in dot: inputs must all be rank 1 or 2, but got ranks " + "".concat($t1.rank, " and ").concat($t2.rank, ".");
      });
      var t1Inner = $t1.rank === 1 ? $t1.size : $t1.shape[1];
      var t2Inner = $t2.rank === 1 ? $t2.size : $t2.shape[0];
      assert(t1Inner === t2Inner, function() {
        return "Error in dot: inner dimensions of inputs must match, but got " + "".concat(t1Inner, " and ").concat(t2Inner, ".");
      });
      if ($t1.rank === 1 && $t2.rank === 1) {
        var t12D = reshape($t1, [1, -1]);
        var t22D = reshape($t2, [-1, 1]);
        var t1t2 = matMul$1(t12D, t22D);
        return reshape(t1t2, []);
      } else if ($t1.rank === 1 && $t2.rank === 2) {
        var t12D = reshape($t1, [1, -1]);
        var t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);
        var t1t2 = matMul$1(t12D, t22D);
        return reshape(t1t2, [t1t2.size]);
      } else if ($t1.rank === 2 && $t2.rank === 1) {
        var t22D = reshape($t2, [-1, 1]);
        var t1t2 = matMul$1($t1, t22D);
        return reshape(t1t2, [t1t2.size]);
      } else {
        var t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);
        var t1t2 = matMul$1($t1, t22D);
        return t1t2;
      }
    }
    var dot = /* @__PURE__ */ op({ dot_ });
    function einsum_(equation) {
      var tensors = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        tensors[_i - 1] = arguments[_i];
      }
      var $tensors = tensors.map(function(t, i) {
        return convertToTensor(t, "tensors".concat(i), "einsum");
      });
      var attrs = { equation };
      return ENGINE.runKernel(Einsum, $tensors, attrs);
    }
    var einsum = /* @__PURE__ */ op({ einsum_ });
    function elu_(x) {
      var $x = convertToTensor(x, "x", "elu", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Elu, inputs);
    }
    var elu = /* @__PURE__ */ op({ elu_ });
    function ensureShape_(x, shape) {
      var $x = convertToTensor(x, "x", "ensureShape", "string_or_numeric");
      if (!arraysEqualWithNull($x.shape, shape)) {
        throw new Error("EnsureShape: Shape of tensor ".concat($x.shape, " is not compatible with expected shape ").concat(shape));
      }
      return x;
    }
    var ensureShape = /* @__PURE__ */ op({ ensureShape_ });
    function erf_(x) {
      var $x = convertToTensor(x, "x", "erf");
      assert($x.dtype === "int32" || $x.dtype === "float32", function() {
        return "Input dtype must be `int32` or `float32`.";
      });
      if ($x.dtype === "int32") {
        $x = cast($x, "float32");
      }
      var inputs = { x: $x };
      return ENGINE.runKernel(Erf, inputs);
    }
    var erf = /* @__PURE__ */ op({ erf_ });
    function combineLocations(outputLoc, reduceLoc, axes) {
      var rank = outputLoc.length + reduceLoc.length;
      var loc = [];
      var outIdx = 0;
      var reduceIdx = 0;
      for (var dim = 0; dim < rank; dim++) {
        if (axes.indexOf(dim) === -1) {
          loc.push(outputLoc[outIdx++]);
        } else {
          loc.push(reduceLoc[reduceIdx++]);
        }
      }
      return loc;
    }
    function expandShapeToKeepDim(shape, axes) {
      var reduceSubShape = axes.map(function(x) {
        return 1;
      });
      return combineLocations(shape, reduceSubShape, axes);
    }
    function max_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "max");
      var inputs = { x: $x };
      var attrs = { reductionIndices: axis, keepDims };
      return ENGINE.runKernel(Max, inputs, attrs);
    }
    var max = /* @__PURE__ */ op({ max_ });
    function min_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "min");
      var inputs = { x: $x };
      var attrs = { axis, keepDims };
      return ENGINE.runKernel(Min, inputs, attrs);
    }
    var min = /* @__PURE__ */ op({ min_ });
    function pow_(base, exp2) {
      var _a;
      var $base = convertToTensor(base, "base", "pow");
      var $exp = convertToTensor(exp2, "exp", "pow");
      _a = __read(makeTypesMatch($base, $exp), 2), $base = _a[0], $exp = _a[1];
      var inputs = { a: $base, b: $exp };
      return ENGINE.runKernel(Pow, inputs);
    }
    var pow = /* @__PURE__ */ op({ pow_ });
    function makeTensor(values, shape, inferredShape, dtype) {
      if (dtype == null) {
        dtype = inferDtype(values);
      } else if (dtype === "complex64") {
        throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");
      }
      if (isWebGPUData(values) || isWebGLData(values)) {
        if (dtype !== "float32" && dtype !== "int32") {
          throw new Error("Creating tensor from GPU data only supports " + "'float32'|'int32' dtype, while the dtype is ".concat(dtype, "."));
        }
        return ENGINE.backend.createTensorFromGPUData(values, shape || inferredShape, dtype);
      }
      if (!isTypedArray(values) && !Array.isArray(values) && typeof values !== "number" && typeof values !== "boolean" && typeof values !== "string") {
        throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");
      }
      if (shape != null) {
        assertNonNegativeIntegerDimensions(shape);
        var providedSize_1 = sizeFromShape(shape);
        var inferredSize_1 = sizeFromShape(inferredShape);
        assert(providedSize_1 === inferredSize_1, function() {
          return "Based on the provided shape, [".concat(shape, "], the tensor should have ") + "".concat(providedSize_1, " values but has ").concat(inferredSize_1);
        });
        for (var i = 0; i < inferredShape.length; ++i) {
          var inferred = inferredShape[i];
          var flatDimsDontMatch = i === inferredShape.length - 1 ? inferred !== sizeFromShape(shape.slice(i)) : true;
          assert(inferredShape[i] === shape[i] || !flatDimsDontMatch, function() {
            return "Error creating a new Tensor. Inferred shape " + "(".concat(inferredShape, ") does not match the provided ") + "shape (".concat(shape, "). ");
          });
        }
      }
      if (!isTypedArray(values) && !Array.isArray(values)) {
        values = [values];
      }
      shape = shape || inferredShape;
      values = dtype !== "string" ? toTypedArray(values, dtype) : flatten(values, [], true);
      return ENGINE.makeTensor(values, shape, dtype);
    }
    function scalar(value, dtype) {
      if ((isTypedArray(value) && dtype !== "string" || Array.isArray(value)) && dtype !== "complex64") {
        throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");
      }
      if (dtype === "string" && isTypedArray(value) && !(value instanceof Uint8Array)) {
        throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");
      }
      var shape = [];
      var inferredShape = [];
      return makeTensor(value, shape, inferredShape, dtype);
    }
    function sqrt_(x) {
      var $x = convertToTensor(x, "x", "sqrt", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Sqrt, inputs);
    }
    var sqrt = /* @__PURE__ */ op({ sqrt_ });
    function square_(x) {
      var $x = convertToTensor(x, "x", "square");
      var attrs = {};
      return ENGINE.runKernel("Square", { x: $x }, attrs);
    }
    var square = /* @__PURE__ */ op({ square_ });
    function sum_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "sum");
      if ($x.dtype === "bool") {
        $x = cast($x, "int32");
      }
      var inputs = { x: $x };
      var attrs = { axis, keepDims };
      return ENGINE.runKernel(Sum, inputs, attrs);
    }
    var sum = /* @__PURE__ */ op({ sum_ });
    function norm_(x, ord, axis, keepDims) {
      if (ord === void 0) {
        ord = "euclidean";
      }
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      x = convertToTensor(x, "x", "norm");
      var norm2 = normImpl(x, ord, axis);
      var keepDimsShape = norm2.shape;
      if (keepDims) {
        var axes = parseAxisParam(axis, x.shape);
        keepDimsShape = expandShapeToKeepDim(norm2.shape, axes);
      }
      return reshape(norm2, keepDimsShape);
    }
    function normImpl(x, p, axis) {
      if (axis === void 0) {
        axis = null;
      }
      if (x.rank === 0) {
        return abs(x);
      }
      if (x.rank !== 1 && axis === null) {
        return normImpl(reshape(x, [-1]), p, axis);
      }
      if (x.rank === 1 || typeof axis === "number" || Array.isArray(axis) && axis.length === 1) {
        if (p === 1) {
          return sum(abs(x), axis);
        }
        if (p === Infinity) {
          return max(abs(x), axis);
        }
        if (p === -Infinity) {
          return min(abs(x), axis);
        }
        if (p === "euclidean" || p === 2) {
          return sqrt(sum(pow(abs(x), scalar(2, "int32")), axis));
        }
        throw new Error("Error in norm: invalid ord value: ".concat(p));
      }
      if (Array.isArray(axis) && axis.length === 2) {
        if (p === 1) {
          return max(sum(abs(x), axis[0]), axis[1] - 1);
        }
        if (p === Infinity) {
          return max(sum(abs(x), axis[1]), axis[0]);
        }
        if (p === -Infinity) {
          return min(sum(abs(x), axis[1]), axis[0]);
        }
        if (p === "fro" || p === "euclidean") {
          return sqrt(sum(square(x), axis));
        }
        throw new Error("Error in norm: invalid ord value: ".concat(p));
      }
      throw new Error("Error in norm: invalid axis: ".concat(axis));
    }
    var norm = /* @__PURE__ */ op({ norm_ });
    function euclideanNorm_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      return norm(x, "euclidean", axis, keepDims);
    }
    var euclideanNorm = /* @__PURE__ */ op({ euclideanNorm_ });
    function exp_(x) {
      var $x = convertToTensor(x, "x", "exp");
      var inputs = { x: $x };
      return ENGINE.runKernel(Exp, inputs);
    }
    var exp = /* @__PURE__ */ op({ exp_ });
    function expandDims_(x, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $x = convertToTensor(x, "x", "expandDims", "string_or_numeric");
      assert(axis <= $x.rank, function() {
        return "Axis must be <= rank of the tensor";
      });
      var inputs = { input: $x };
      var attrs = { dim: axis };
      return ENGINE.runKernel(ExpandDims, inputs, attrs);
    }
    var expandDims = /* @__PURE__ */ op({ expandDims_ });
    function expm1_(x) {
      var $x = convertToTensor(x, "x", "expm1");
      var inputs = { x: $x };
      return ENGINE.runKernel(Expm1, inputs);
    }
    var expm1 = /* @__PURE__ */ op({ expm1_ });
    function tile_(x, reps) {
      var $x = convertToTensor(x, "x", "tile", "string_or_numeric");
      assert($x.rank === reps.length, function() {
        return "Error in transpose: rank of input ".concat($x.rank, " ") + "must match length of reps ".concat(reps, ".");
      });
      var inputs = { x: $x };
      var attrs = { reps };
      return ENGINE.runKernel(Tile, inputs, attrs);
    }
    var tile = /* @__PURE__ */ op({ tile_ });
    function eye_(numRows, numColumns, batchShape, dtype) {
      if (dtype === void 0) {
        dtype = "float32";
      }
      if (numColumns == null) {
        numColumns = numRows;
      }
      var buff = buffer([numRows, numColumns], dtype);
      var n = numRows <= numColumns ? numRows : numColumns;
      for (var i = 0; i < n; ++i) {
        buff.set(1, i, i);
      }
      var out = reshape(buff.toTensor(), [numRows, numColumns]);
      if (batchShape == null) {
        return out;
      } else {
        if (batchShape.length === 1) {
          return tile(expandDims(out, 0), [batchShape[0], 1, 1]);
        } else if (batchShape.length === 2) {
          return tile(expandDims(expandDims(out, 0), 0), [batchShape[0], batchShape[1], 1, 1]);
        } else if (batchShape.length === 3) {
          return tile(expandDims(expandDims(expandDims(out, 0), 0), 0), [
            batchShape[0],
            batchShape[1],
            batchShape[2],
            1,
            1
          ]);
        } else {
          throw new Error("eye() currently supports only 1D and 2D " + // tslint:disable-next-line:no-any
          "batchShapes, but received ".concat(batchShape.length, "D."));
        }
      }
    }
    var eye = /* @__PURE__ */ op({ eye_ });
    function floor_(x) {
      var $x = convertToTensor(x, "x", "floor", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Floor, inputs);
    }
    var floor = /* @__PURE__ */ op({ floor_ });
    function gather_(x, indices, axis, batchDims) {
      if (axis === void 0) {
        axis = 0;
      }
      if (batchDims === void 0) {
        batchDims = 0;
      }
      var $x = convertToTensor(x, "x", "gather");
      var $indices = convertToTensor(indices, "indices", "gather", "int32");
      var inputs = { x: $x, indices: $indices };
      var attrs = { axis, batchDims };
      return ENGINE.runKernel(GatherV2, inputs, attrs);
    }
    var gather = /* @__PURE__ */ op({ gather_ });
    function greater_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "greater", "string_or_numeric");
      var $b = convertToTensor(b, "b", "greater", "string_or_numeric");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Greater, inputs);
    }
    var greater = /* @__PURE__ */ op({ greater_ });
    function greaterEqual_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "greaterEqual", "string_or_numeric");
      var $b = convertToTensor(b, "b", "greaterEqual", "string_or_numeric");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(GreaterEqual, inputs);
    }
    var greaterEqual = /* @__PURE__ */ op({ greaterEqual_ });
    function imag_(input) {
      var $input = convertToTensor(input, "input", "imag");
      var inputs = { input: $input };
      return ENGINE.runKernel(Imag, inputs);
    }
    var imag = /* @__PURE__ */ op({ imag_ });
    function isFinite_(x) {
      var $x = convertToTensor(x, "x", "isFinite");
      var inputs = { x: $x };
      return ENGINE.runKernel(IsFinite, inputs);
    }
    var isFinite$1 = /* @__PURE__ */ op({ isFinite_ });
    function isInf_(x) {
      var $x = convertToTensor(x, "x", "isInf");
      var inputs = { x: $x };
      return ENGINE.runKernel(IsInf, inputs);
    }
    var isInf = /* @__PURE__ */ op({ isInf_ });
    function isNaN_(x) {
      var $x = convertToTensor(x, "x", "isNaN");
      var inputs = { x: $x };
      return ENGINE.runKernel(IsNan, inputs);
    }
    var isNaN$1 = /* @__PURE__ */ op({ isNaN_ });
    function leakyRelu_(x, alpha) {
      if (alpha === void 0) {
        alpha = 0.2;
      }
      var $x = convertToTensor(x, "x", "leakyRelu");
      var inputs = { x: $x };
      var attrs = { alpha };
      return ENGINE.runKernel(LeakyRelu, inputs, attrs);
    }
    var leakyRelu = /* @__PURE__ */ op({ leakyRelu_ });
    function less_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "less", "string_or_numeric");
      var $b = convertToTensor(b, "b", "less", "string_or_numeric");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Less, inputs);
    }
    var less = /* @__PURE__ */ op({ less_ });
    function lessEqual_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "lessEqual", "string_or_numeric");
      var $b = convertToTensor(b, "b", "lessEqual", "string_or_numeric");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(LessEqual, inputs);
    }
    var lessEqual = /* @__PURE__ */ op({ lessEqual_ });
    function linspace(start, stop, num) {
      if (num <= 0) {
        throw new Error("The number of values should be positive.");
      }
      var attrs = { start, stop, num };
      return ENGINE.runKernel(LinSpace, {}, attrs);
    }
    function localResponseNormalization_(x, depthRadius, bias, alpha, beta) {
      if (depthRadius === void 0) {
        depthRadius = 5;
      }
      if (bias === void 0) {
        bias = 1;
      }
      if (alpha === void 0) {
        alpha = 1;
      }
      if (beta === void 0) {
        beta = 0.5;
      }
      var $x = convertToTensor(x, "x", "localResponseNormalization");
      assert($x.rank === 4 || $x.rank === 3, function() {
        return "Error in localResponseNormalization: x must be rank 3 or 4 but got\n               rank ".concat($x.rank, ".");
      });
      assert(isInt(depthRadius), function() {
        return "Error in localResponseNormalization: depthRadius must be an " + "integer but got depthRadius ".concat(depthRadius, ".");
      });
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      var inputs = { x: x4D };
      var attrs = { depthRadius, bias, alpha, beta };
      var res = ENGINE.runKernel(LRN, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      } else {
        return res;
      }
    }
    var localResponseNormalization = /* @__PURE__ */ op({ localResponseNormalization_ });
    function log_(x) {
      var $x = convertToTensor(x, "x", "log", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Log, inputs);
    }
    var log = /* @__PURE__ */ op({ log_ });
    function log1p_(x) {
      var $x = convertToTensor(x, "x", "log1p");
      var inputs = { x: $x };
      return ENGINE.runKernel(Log1p, inputs);
    }
    var log1p = /* @__PURE__ */ op({ log1p_ });
    function customGrad(f) {
      return ENGINE.customGrad(f);
    }
    function neg_(x) {
      var $x = convertToTensor(x, "x", "neg");
      var inputs = { x: $x };
      return ENGINE.runKernel(Neg, inputs);
    }
    var neg = /* @__PURE__ */ op({ neg_ });
    function softplus_(x) {
      var $x = convertToTensor(x, "x", "softplus");
      var inputs = { x: $x };
      return ENGINE.runKernel(Softplus, inputs);
    }
    var softplus = /* @__PURE__ */ op({ softplus_ });
    function logSigmoid_(x) {
      var $x = convertToTensor(x, "x", "logSigmoid");
      var customOp = customGrad(function(x2) {
        var value = neg(softplus(neg(x2)));
        var gradFunc = function(dy) {
          var derX = mul(dy, sigmoid(neg(x2)));
          return derX;
        };
        return { value, gradFunc };
      });
      return customOp($x);
    }
    var logSigmoid = /* @__PURE__ */ op({ logSigmoid_ });
    function sub_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "sub");
      var $b = convertToTensor(b, "b", "sub");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Sub, inputs);
    }
    var sub = /* @__PURE__ */ op({ sub_ });
    function logSoftmax_(logits, axis) {
      if (axis === void 0) {
        axis = -1;
      }
      var $logits = convertToTensor(logits, "logits", "logSoftmax");
      if (axis === -1) {
        axis = $logits.rank - 1;
      }
      if (axis !== $logits.rank - 1) {
        throw Error("Log Softmax along a non-last dimension is not yet supported. " + "Logits was rank ".concat($logits.rank, " and axis was ").concat(axis));
      }
      var customOp = customGrad(function(logits2, save) {
        var keepDims = true;
        var xMax = max(logits2, axis, true);
        var shifted = sub(logits2, xMax);
        var value = sub(cast(shifted, "float32"), log(sum(exp(shifted), axis, keepDims)));
        save([value]);
        var gradFunc = function(dy, saved) {
          var _a = __read(saved, 1), value2 = _a[0];
          var keepDims2 = true;
          var softmax2 = exp(value2);
          return sub(dy, mul(sum(dy, axis, keepDims2), softmax2));
        };
        return { value, gradFunc };
      });
      return customOp($logits);
    }
    var logSoftmax = /* @__PURE__ */ op({ logSoftmax_ });
    function logSumExp_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "logSumExp");
      var axes = parseAxisParam(axis, $x.shape);
      var xMax = max(
        $x,
        axes,
        true
        /* keepDims */
      );
      var a = sub($x, xMax);
      var b = exp(a);
      var c = sum(b, axes);
      var d = log(c);
      var res = add(reshape(xMax, d.shape), d);
      if (keepDims) {
        var newShape = expandShapeToKeepDim(res.shape, axes);
        return reshape(res, newShape);
      }
      return res;
    }
    var logSumExp = /* @__PURE__ */ op({ logSumExp_ });
    function logicalAnd_(a, b) {
      var $a = convertToTensor(a, "a", "logicalAnd", "bool");
      var $b = convertToTensor(b, "b", "logicalAnd", "bool");
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(LogicalAnd, inputs);
    }
    var logicalAnd = /* @__PURE__ */ op({ logicalAnd_ });
    function logicalNot_(x) {
      var $x = convertToTensor(x, "x", "logicalNot", "bool");
      var inputs = { x: $x };
      return ENGINE.runKernel(LogicalNot, inputs);
    }
    var logicalNot = /* @__PURE__ */ op({ logicalNot_ });
    function logicalOr_(a, b) {
      var $a = convertToTensor(a, "a", "logicalOr", "bool");
      var $b = convertToTensor(b, "b", "logicalOr", "bool");
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(LogicalOr, inputs);
    }
    var logicalOr = /* @__PURE__ */ op({ logicalOr_ });
    function logicalXor_(a, b) {
      var $a = convertToTensor(a, "a", "logicalXor", "bool");
      var $b = convertToTensor(b, "b", "logicalXor", "bool");
      assertAndGetBroadcastShape($a.shape, $b.shape);
      return logicalAnd(logicalOr(a, b), logicalNot(logicalAnd(a, b)));
    }
    var logicalXor = /* @__PURE__ */ op({ logicalXor_ });
    var INT32_MAX = 2147483648;
    function searchSorted_(sortedSequence, values, side) {
      if (side === void 0) {
        side = "left";
      }
      var $sortedSequence = convertToTensor(sortedSequence, "sortedSequence", "searchSorted");
      var $values = convertToTensor(values, "values", "searchSorted");
      var sequenceSize = $sortedSequence.shape[$sortedSequence.shape.length - 1];
      var valuesSize = $values.shape[$values.shape.length - 1];
      var $sortedSequence2D = reshape($sortedSequence, [-1, sequenceSize]);
      var $values2D = reshape($values, [-1, valuesSize]);
      if ($sortedSequence2D.rank < 2) {
        throw new Error("Sorted input argument must be at least 2-dimensional");
      }
      if ($sortedSequence2D.shape[0] !== $values2D.shape[0]) {
        throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");
      }
      if (sizeFromShape($values2D.shape) >= INT32_MAX) {
        throw new Error("values tensor size must less than ".concat(INT32_MAX));
      }
      if ($sortedSequence2D.shape[1] >= INT32_MAX) {
        throw new Error("trailing dim_size must less than ".concat(INT32_MAX, " for int32 output type, was ").concat($sortedSequence2D.shape[1]));
      }
      var inputs = {
        sortedSequence: $sortedSequence2D,
        values: $values2D
      };
      var attrs = { side };
      return ENGINE.runKernel(SearchSorted, inputs, attrs);
    }
    var searchSorted = /* @__PURE__ */ op({ searchSorted_ });
    function lowerBound(sortedSequence, values) {
      return searchSorted(sortedSequence, values, "left");
    }
    function maxPool_(x, filterSize, strides, pad2, dimRoundingMode) {
      var $x = convertToTensor(x, "x", "maxPool");
      var dilations = 1;
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, function() {
        return "Error in maxPool: input must be rank 4 but got rank ".concat(x4D.rank, ".");
      });
      assert(eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in maxPool: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      checkPadOnDimRoundingMode("maxPool", pad2, dimRoundingMode);
      var inputs = { x: x4D };
      var attrs = { filterSize, strides, pad: pad2, dimRoundingMode };
      var res = ENGINE.runKernel(MaxPool, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var maxPool = /* @__PURE__ */ op({ maxPool_ });
    function maxPool3d_(x, filterSize, strides, pad2, dimRoundingMode, dataFormat) {
      if (filterSize === void 0) {
        filterSize = [1, 1, 1];
      }
      if (dataFormat === void 0) {
        dataFormat = "NDHWC";
      }
      var $x = convertToTensor(x, "x", "maxPool3d");
      var x5D = $x;
      var reshapedTo5D = false;
      if ($x.rank === 4) {
        reshapedTo5D = true;
        x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
      }
      assert(x5D.rank === 5, function() {
        return "Error in maxPool3d: x must be rank 5 but got rank ".concat(x5D.rank, ".");
      });
      assert(dataFormat === "NDHWC", function() {
        return "Error in maxPool3d: Only NDHWC is currently supported, " + "but got dataFormat of ".concat(dataFormat);
      });
      checkPadOnDimRoundingMode("maxPool3d", pad2, dimRoundingMode);
      var inputs = { x: x5D };
      var attrs = { filterSize, strides, pad: pad2, dimRoundingMode, dataFormat };
      var res = ENGINE.runKernel(MaxPool3D, inputs, attrs);
      if (reshapedTo5D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
      }
      return res;
    }
    var maxPool3d = /* @__PURE__ */ op({ maxPool3d_ });
    function maxPoolWithArgmax_(x, filterSize, strides, pad2, includeBatchInIndex) {
      if (includeBatchInIndex === void 0) {
        includeBatchInIndex = false;
      }
      var $x = convertToTensor(x, "x", "maxPoolWithArgmax");
      var inputs = { x: $x };
      var attrs = { filterSize, strides, pad: pad2, includeBatchInIndex };
      var result = ENGINE.runKernel(MaxPoolWithArgmax, inputs, attrs);
      return { result: result[0], indexes: result[1] };
    }
    var maxPoolWithArgmax = /* @__PURE__ */ op({ maxPoolWithArgmax_ });
    function maximum_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "maximum");
      var $b = convertToTensor(b, "b", "maximum");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      if ($a.dtype === "bool") {
        $a = cast($a, "int32");
        $b = cast($b, "int32");
      }
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Maximum, inputs);
    }
    var maximum = /* @__PURE__ */ op({ maximum_ });
    function mean_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "mean");
      var inputs = { x: $x };
      var attrs = { axis, keepDims };
      return ENGINE.runKernel(Mean, inputs, attrs);
    }
    var mean = /* @__PURE__ */ op({ mean_ });
    function zeros(shape, dtype) {
      if (dtype === void 0) {
        dtype = "float32";
      }
      assertNonNegativeIntegerDimensions(shape);
      if (dtype === "complex64") {
        var real2 = zeros(shape, "float32");
        var imag2 = zeros(shape, "float32");
        return complex(real2, imag2);
      }
      var values = makeZerosTypedArray(sizeFromShape(shape), dtype);
      return ENGINE.makeTensor(values, shape, dtype);
    }
    function ones(shape, dtype) {
      if (dtype === void 0) {
        dtype = "float32";
      }
      assertNonNegativeIntegerDimensions(shape);
      if (dtype === "complex64") {
        var real2 = ones(shape, "float32");
        var imag2 = zeros(shape, "float32");
        return complex(real2, imag2);
      }
      var values = makeOnesTypedArray(sizeFromShape(shape), dtype);
      return ENGINE.makeTensor(values, shape, dtype);
    }
    function meshgrid(x, y, _a) {
      var _b = _a === void 0 ? {} : _a, _c = _b.indexing, indexing = _c === void 0 ? "xy" : _c;
      if (indexing !== "xy" && indexing !== "ij") {
        throw new TypeError("".concat(indexing, " is not a valid third argument to meshgrid"));
      }
      if (x === void 0) {
        return [];
      }
      var $x = convertToTensor(x, "x", "meshgrid", x instanceof Tensor ? x.dtype : "float32");
      if (y === void 0) {
        return [$x];
      }
      var $y = convertToTensor(y, "y", "meshgrid", y instanceof Tensor ? y.dtype : "float32");
      var w = sizeFromShape($x.shape);
      var h = sizeFromShape($y.shape);
      if (indexing === "xy") {
        $x = reshape($x, [1, -1]);
        $y = reshape($y, [-1, 1]);
        return [
          matMul$1(ones([h, 1], $x.dtype), $x),
          matMul$1($y, ones([1, w], $y.dtype))
        ];
      }
      $x = reshape($x, [-1, 1]);
      $y = reshape($y, [1, -1]);
      return [
        matMul$1($x, ones([1, h], $x.dtype)),
        matMul$1(ones([w, 1], $y.dtype), $y)
      ];
    }
    function minimum_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "minimum");
      var $b = convertToTensor(b, "b", "minimum");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      if ($a.dtype === "bool") {
        $a = cast($a, "int32");
        $b = cast($b, "int32");
      }
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Minimum, inputs);
    }
    var minimum = /* @__PURE__ */ op({ minimum_ });
    function mirrorPad_(x, paddings, mode) {
      assert(mode === "reflect" || mode === "symmetric", function() {
        return "Invalid mode. Mode must be either reflect or symmetric. " + "Got ".concat(mode, ".");
      });
      var $x = convertToTensor(x, "x", "mirrorPad");
      if ($x.rank === 0) {
        throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");
      }
      assert(paddings.length === $x.rank, function() {
        return "Padding doesn't match input. Must be ".concat($x.rank, ". ") + "Got ".concat(paddings.length, ".");
      });
      var shapeOffset = mode === "reflect" ? 1 : 0;
      var _loop_1 = function(i2) {
        assert(paddings[i2].length === 2, function() {
          return "Invalid number of paddings. Must be length of 2 each.";
        });
        assert(paddings[i2][0] >= 0 && paddings[i2][0] <= $x.shape[i2] - shapeOffset && paddings[i2][1] >= 0 && paddings[i2][1] <= $x.shape[i2] - shapeOffset, function() {
          return "Padding in dimension ".concat(i2, " cannot be greater than or equal ") + "to ".concat($x.shape[i2] - shapeOffset, " or less than 0 for input of ") + "shape ".concat($x.shape);
        });
      };
      for (var i = 0; i < $x.rank; i++) {
        _loop_1(i);
      }
      var attrs = { paddings, mode };
      var inputs = { x: $x };
      return ENGINE.runKernel(MirrorPad, inputs, attrs);
    }
    var mirrorPad = /* @__PURE__ */ op({ mirrorPad_ });
    function mod_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "mod");
      var $b = convertToTensor(b, "b", "mod");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Mod, inputs);
    }
    var mod = /* @__PURE__ */ op({ mod_ });
    function moments_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      x = convertToTensor(x, "x", "moments");
      var axes = parseAxisParam(axis, x.shape);
      var xMean = mean(x, axes, keepDims);
      var keepDimsShape = xMean.shape;
      if (!keepDims) {
        keepDimsShape = expandShapeToKeepDim(xMean.shape, axes);
      }
      var devSquared = square(sub(cast(x, "float32"), reshape(xMean, keepDimsShape)));
      var variance = mean(devSquared, axes, keepDims);
      return { mean: xMean, variance };
    }
    var moments = /* @__PURE__ */ op({ moments_ });
    function multiRNNCell_(lstmCells, data, c, h) {
      var $data = convertToTensor(data, "data", "multiRNNCell");
      var $c = convertToTensorArray(c, "c", "multiRNNCell");
      var $h = convertToTensorArray(h, "h", "multiRNNCell");
      var input = $data;
      var newStates = [];
      for (var i = 0; i < lstmCells.length; i++) {
        var output = lstmCells[i](input, $c[i], $h[i]);
        newStates.push(output[0]);
        newStates.push(output[1]);
        input = output[1];
      }
      var newC = [];
      var newH = [];
      for (var i = 0; i < newStates.length; i += 2) {
        newC.push(newStates[i]);
        newH.push(newStates[i + 1]);
      }
      return [newC, newH];
    }
    var multiRNNCell = /* @__PURE__ */ op({ multiRNNCell_ });
    function multinomial_(logits, numSamples, seed, normalized) {
      if (normalized === void 0) {
        normalized = false;
      }
      var $logits = convertToTensor(logits, "logits", "multinomial");
      var numOutcomes = $logits.size;
      var origRank = $logits.rank;
      if (numOutcomes < 2) {
        throw new Error("Error in multinomial: you need at least 2 outcomes, but got " + "".concat(numOutcomes, "."));
      }
      if (origRank > 2) {
        throw new Error("Rank of probabilities must be 1 or 2, but is ".concat(origRank));
      }
      seed = seed || Math.random();
      var logits2D = origRank === 1 ? reshape($logits, [1, -1]) : $logits;
      var inputs = { logits: logits2D };
      var attrs = { numSamples, seed, normalized };
      var res = ENGINE.runKernel(Multinomial, inputs, attrs);
      return origRank === 1 ? reshape(res, [res.size]) : res;
    }
    var multinomial = /* @__PURE__ */ op({ multinomial_ });
    function notEqual_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "notEqual", "string_or_numeric");
      var $b = convertToTensor(b, "b", "notEqual", "string_or_numeric");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      return ENGINE.runKernel(NotEqual, inputs);
    }
    var notEqual = /* @__PURE__ */ op({ notEqual_ });
    function oneHot_(indices, depth, onValue, offValue, dtype) {
      if (onValue === void 0) {
        onValue = 1;
      }
      if (offValue === void 0) {
        offValue = 0;
      }
      if (dtype === void 0) {
        dtype = "int32";
      }
      if (depth < 2) {
        throw new Error("Error in oneHot: depth must be >=2, but it is ".concat(depth));
      }
      var $indices = convertToTensor(indices, "indices", "oneHot", "int32");
      var inputs = { indices: $indices };
      var attrs = { dtype, depth, onValue, offValue };
      return ENGINE.runKernel(OneHot, inputs, attrs);
    }
    var oneHot = /* @__PURE__ */ op({ oneHot_ });
    function onesLike_(x) {
      var $x = convertToTensor(x, "x", "onesLike");
      var inputs = { x: $x };
      return ENGINE.runKernel(OnesLike, inputs);
    }
    var onesLike = /* @__PURE__ */ op({ onesLike_ });
    function outerProduct_(v1, v2) {
      var $v1 = convertToTensor(v1, "v1", "outerProduct");
      var $v2 = convertToTensor(v2, "v2", "outerProduct");
      assert($v1.rank === 1 && $v2.rank === 1, function() {
        return "Error in outerProduct: inputs must be rank 1, but got ranks " + "".concat($v1.rank, " and ").concat($v2.rank, ".");
      });
      var v12D = reshape($v1, [-1, 1]);
      var v22D = reshape($v2, [1, -1]);
      return matMul$1(v12D, v22D);
    }
    var outerProduct = /* @__PURE__ */ op({ outerProduct_ });
    function pad_(x, paddings, constantValue) {
      if (constantValue === void 0) {
        constantValue = 0;
      }
      var $x = convertToTensor(x, "x", "pad");
      if ($x.rank === 0) {
        throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");
      }
      var attrs = { paddings, constantValue };
      var inputs = { x: $x };
      return ENGINE.runKernel(PadV2, inputs, attrs);
    }
    var pad = /* @__PURE__ */ op({ pad_ });
    function pad1d_(x, paddings, constantValue) {
      if (constantValue === void 0) {
        constantValue = 0;
      }
      assert(paddings.length === 2, function() {
        return "Invalid number of paddings. Must be length of 2.";
      });
      return pad(x, [paddings], constantValue);
    }
    var pad1d = /* @__PURE__ */ op({ pad1d_ });
    function pad2d_(x, paddings, constantValue) {
      if (constantValue === void 0) {
        constantValue = 0;
      }
      assert(paddings.length === 2 && paddings[0].length === 2 && paddings[1].length === 2, function() {
        return "Invalid number of paddings. Must be length of 2 each.";
      });
      return pad(x, paddings, constantValue);
    }
    var pad2d = /* @__PURE__ */ op({ pad2d_ });
    function pad3d_(x, paddings, constantValue) {
      if (constantValue === void 0) {
        constantValue = 0;
      }
      assert(paddings.length === 3 && paddings[0].length === 2 && paddings[1].length === 2 && paddings[2].length === 2, function() {
        return "Invalid number of paddings. Must be length of 2 each.";
      });
      return pad(x, paddings, constantValue);
    }
    var pad3d = /* @__PURE__ */ op({ pad3d_ });
    function pad4d_(x, paddings, constantValue) {
      if (constantValue === void 0) {
        constantValue = 0;
      }
      assert(paddings.length === 4 && paddings[0].length === 2 && paddings[1].length === 2 && paddings[2].length === 2 && paddings[3].length === 2, function() {
        return "Invalid number of paddings. Must be length of 2 each.";
      });
      return pad(x, paddings, constantValue);
    }
    var pad4d = /* @__PURE__ */ op({ pad4d_ });
    function spaceToBatchND_(x, blockShape, paddings) {
      var $x = convertToTensor(x, "x", "spaceToBatchND");
      assert($x.rank >= 1 + blockShape.length, function() {
        return "input rank ".concat($x.rank, " should be > than [blockShape] ").concat(blockShape.length);
      });
      assert(paddings.length === blockShape.length, function() {
        return "paddings.shape[0] ".concat(paddings.length, " must be equal to [blockShape] ").concat(blockShape.length);
      });
      assert($x.shape.reduce(function(a, b, i) {
        if (i > 0 && i <= blockShape.length) {
          return a && (b + paddings[i - 1][0] + paddings[i - 1][1]) % blockShape[i - 1] === 0;
        }
        return a;
      }, true), function() {
        return "input spatial dimensions ".concat($x.shape.slice(1), " with paddings ").concat(paddings.toString(), " must be divisible by blockShapes ").concat(blockShape.toString());
      });
      var inputs = { x: $x };
      var attrs = { blockShape, paddings };
      return ENGINE.runKernel(SpaceToBatchND, inputs, attrs);
    }
    var spaceToBatchND = /* @__PURE__ */ op({ spaceToBatchND_ });
    function pool_(input, windowShape, poolingType, pad2, dilations, strides, dimRoundingMode) {
      if (dilations == null) {
        dilations = [1, 1];
      }
      if (strides == null) {
        strides = 1;
      }
      if (pad2 === 0) {
        pad2 = "valid";
      }
      var $x = convertToTensor(input, "x", "maxPool");
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in pool: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      var convInfo = computePool2DInfo(x4D.shape, windowShape, strides, dilations, pad2);
      var dilation = [convInfo.dilationHeight, convInfo.dilationWidth];
      var basePadding;
      if (pad2 === "same") {
        basePadding = withSpaceToBatchBasePaddings([convInfo.filterHeight, convInfo.filterWidth], dilation);
      } else {
        basePadding = [[0, 0], [0, 0]];
      }
      var isDilationOne = dilation[0] === 1 && dilation[1] === 1;
      var _a = __read(requiredSpaceToBatchPaddings([convInfo.inHeight, convInfo.inWidth], dilation, basePadding), 2), adjustedPadding = _a[0], adjustedCrops = _a[1];
      var convertedPad = isDilationOne ? pad2 : "valid";
      var convertedX = isDilationOne ? x4D : spaceToBatchND(x4D, dilation, adjustedPadding);
      var forwardOp = poolingType === "avg" ? function() {
        return avgPool(convertedX, windowShape, strides, convertedPad, dimRoundingMode);
      } : function() {
        return maxPool(convertedX, windowShape, strides, convertedPad, dimRoundingMode);
      };
      var y = forwardOp();
      var res = isDilationOne ? y : batchToSpaceND(y, dilation, adjustedCrops);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    function requiredSpaceToBatchPaddings(inputShape, blockShape, basePadding) {
      var padStart = basePadding.map(function(b) {
        return b[0];
      });
      var origPadEnd = basePadding.map(function(b) {
        return b[1];
      });
      var fullInputShape = inputShape.concat(padStart, origPadEnd);
      var padEndExtra = blockShape.map(function(b, i) {
        return (b - fullInputShape[i] % b) % b;
      });
      var padEnd = origPadEnd.map(function(s, i) {
        return s + padEndExtra[i];
      });
      var paddings = blockShape.map(function(_, i) {
        return [padStart[i], padEnd[i]];
      });
      var crops = blockShape.map(function(_, i) {
        return [0, padEndExtra[i]];
      });
      return [paddings, crops];
    }
    function withSpaceToBatchBasePaddings(filterShape, dilation) {
      var dilatedFilterShape = filterShape.map(function(s, i) {
        return s + (s - 1) * (dilation[i] - 1);
      });
      var padExtraShape = dilatedFilterShape.map(function(s) {
        return s - 1;
      });
      var padExtraStart = padExtraShape.map(function(s) {
        return Math.floor(s / 2);
      });
      var padExtraEnd = padExtraShape.map(function(s, i) {
        return s - padExtraStart[i];
      });
      return padExtraShape.map(function(_, i) {
        return [padExtraStart[i], padExtraEnd[i]];
      });
    }
    var pool = /* @__PURE__ */ op({ pool_ });
    function prelu_(x, alpha) {
      var $x = convertToTensor(x, "x", "prelu");
      var $alpha = convertToTensor(alpha, "alpha", "prelu");
      var inputs = { x: $x, alpha: $alpha };
      return ENGINE.runKernel(Prelu, inputs);
    }
    var prelu = /* @__PURE__ */ op({ prelu_ });
    function print(x, verbose) {
      if (verbose === void 0) {
        verbose = false;
      }
      console.log(x.toString(verbose));
    }
    function prod_(x, axis, keepDims) {
      if (axis === void 0) {
        axis = null;
      }
      if (keepDims === void 0) {
        keepDims = false;
      }
      var $x = convertToTensor(x, "x", "prod");
      if ($x.dtype === "bool") {
        $x = cast($x, "int32");
      }
      var inputs = { x: $x };
      var attrs = { axis, keepDims };
      return ENGINE.runKernel(Prod, inputs, attrs);
    }
    var prod = /* @__PURE__ */ op({ prod_ });
    function raggedGather_(paramsNestedSplits, paramsDenseValues, indices, outputRaggedRank) {
      var $paramsNestedSplits = paramsNestedSplits.map(function(t, i) {
        return convertToTensor(t, "tensors".concat(i), "raggedGather", "int32");
      });
      var $paramsDenseValues = convertToTensor(paramsDenseValues, "paramsDenseValues", "raggedGather");
      var $indices = convertToTensor(indices, "indices", "raggedGather", "int32");
      var inputs = {
        paramsNestedSplits: $paramsNestedSplits,
        paramsDenseValues: $paramsDenseValues,
        indices: $indices
      };
      var attrs = { outputRaggedRank };
      var result = ENGINE.runKernel(RaggedGather, inputs, attrs);
      return {
        outputNestedSplits: result.slice(0, result.length - 1),
        outputDenseValues: result[result.length - 1]
      };
    }
    var raggedGather = /* @__PURE__ */ op({ raggedGather_ });
    function raggedRange_(starts, limits, deltas) {
      var $starts = convertToTensor(starts, "starts", "raggedRange");
      var $limits = convertToTensor(limits, "limits", "raggedRange", $starts.dtype);
      var $deltas = convertToTensor(deltas, "deltas", "raggedRange", $starts.dtype);
      var inputs = {
        starts: $starts,
        limits: $limits,
        deltas: $deltas
      };
      var result = ENGINE.runKernel(RaggedRange, inputs);
      return {
        rtNestedSplits: result[0],
        rtDenseValues: result[1]
      };
    }
    var raggedRange = /* @__PURE__ */ op({ raggedRange_ });
    function raggedTensorToTensor_(shape, values, defaultValue, rowPartitionTensors, rowPartitionTypes) {
      var $shape = convertToTensor(shape, "shape", "raggedTensorToTensor", "int32");
      var $values = convertToTensor(values, "values", "raggedTensorToTensor");
      var $defaultValue = convertToTensor(defaultValue, "defaultValue", "raggedTensorToTensor", $values.dtype);
      var $rowPartitionTensors = rowPartitionTensors.map(function(t, i) {
        return convertToTensor(t, "tensors".concat(i), "raggedTensorToTensor", "int32");
      });
      var inputs = {
        shape: $shape,
        values: $values,
        defaultValue: $defaultValue,
        rowPartitionTensors: $rowPartitionTensors
      };
      var attrs = { rowPartitionTypes };
      return ENGINE.runKernel(RaggedTensorToTensor, inputs, attrs);
    }
    var raggedTensorToTensor = /* @__PURE__ */ op({ raggedTensorToTensor_ });
    function rand_(shape, randFunction, dtype) {
      assertNonNegativeIntegerDimensions(shape);
      var size = sizeFromShape(shape);
      var values = null;
      if (dtype == null || dtype === "float32") {
        values = new Float32Array(size);
      } else if (dtype === "int32") {
        values = new Int32Array(size);
      } else if (dtype === "bool") {
        values = new Uint8Array(size);
      } else {
        throw new Error("Unknown data type ".concat(dtype));
      }
      for (var i = 0; i < size; i++) {
        values[i] = randFunction();
      }
      return ENGINE.makeTensor(values, shape, dtype);
    }
    var rand = /* @__PURE__ */ op({ rand_ });
    var alea$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function Alea(seed) {
          var me = this, mash = Mash();
          me.next = function() {
            var t = 2091639 * me.s0 + me.c * 23283064365386963e-26;
            me.s0 = me.s1;
            me.s1 = me.s2;
            return me.s2 = t - (me.c = t | 0);
          };
          me.c = 1;
          me.s0 = mash(" ");
          me.s1 = mash(" ");
          me.s2 = mash(" ");
          me.s0 -= mash(seed);
          if (me.s0 < 0) {
            me.s0 += 1;
          }
          me.s1 -= mash(seed);
          if (me.s1 < 0) {
            me.s1 += 1;
          }
          me.s2 -= mash(seed);
          if (me.s2 < 0) {
            me.s2 += 1;
          }
          mash = null;
        }
        function copy(f, t) {
          t.c = f.c;
          t.s0 = f.s0;
          t.s1 = f.s1;
          t.s2 = f.s2;
          return t;
        }
        function impl(seed, opts) {
          var xg = new Alea(seed), state = opts && opts.state, prng = xg.next;
          prng.int32 = function() {
            return xg.next() * 4294967296 | 0;
          };
          prng.double = function() {
            return prng() + (prng() * 2097152 | 0) * 11102230246251565e-32;
          };
          prng.quick = prng;
          if (state) {
            if (typeof state == "object")
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        function Mash() {
          var n = 4022871197;
          var mash = function(data) {
            data = String(data);
            for (var i = 0; i < data.length; i++) {
              n += data.charCodeAt(i);
              var h = 0.02519603282416938 * n;
              n = h >>> 0;
              h -= n;
              h *= n;
              n = h >>> 0;
              h -= n;
              n += h * 4294967296;
            }
            return (n >>> 0) * 23283064365386963e-26;
          };
          return mash;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.alea = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(alea$1);
    var aleaExports = alea$1.exports;
    var xor128$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this, strseed = "";
          me.x = 0;
          me.y = 0;
          me.z = 0;
          me.w = 0;
          me.next = function() {
            var t = me.x ^ me.x << 11;
            me.x = me.y;
            me.y = me.z;
            me.z = me.w;
            return me.w ^= me.w >>> 19 ^ t ^ t >>> 8;
          };
          if (seed === (seed | 0)) {
            me.x = seed;
          } else {
            strseed += seed;
          }
          for (var k = 0; k < strseed.length + 64; k++) {
            me.x ^= strseed.charCodeAt(k) | 0;
            me.next();
          }
        }
        function copy(f, t) {
          t.x = f.x;
          t.y = f.y;
          t.z = f.z;
          t.w = f.w;
          return t;
        }
        function impl(seed, opts) {
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (typeof state == "object")
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xor128 = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xor128$1);
    var xor128Exports = xor128$1.exports;
    var xorwow$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this, strseed = "";
          me.next = function() {
            var t = me.x ^ me.x >>> 2;
            me.x = me.y;
            me.y = me.z;
            me.z = me.w;
            me.w = me.v;
            return (me.d = me.d + 362437 | 0) + (me.v = me.v ^ me.v << 4 ^ (t ^ t << 1)) | 0;
          };
          me.x = 0;
          me.y = 0;
          me.z = 0;
          me.w = 0;
          me.v = 0;
          if (seed === (seed | 0)) {
            me.x = seed;
          } else {
            strseed += seed;
          }
          for (var k = 0; k < strseed.length + 64; k++) {
            me.x ^= strseed.charCodeAt(k) | 0;
            if (k == strseed.length) {
              me.d = me.x << 10 ^ me.x >>> 4;
            }
            me.next();
          }
        }
        function copy(f, t) {
          t.x = f.x;
          t.y = f.y;
          t.z = f.z;
          t.w = f.w;
          t.v = f.v;
          t.d = f.d;
          return t;
        }
        function impl(seed, opts) {
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (typeof state == "object")
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xorwow = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xorwow$1);
    var xorwowExports = xorwow$1.exports;
    var xorshift7$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this;
          me.next = function() {
            var X = me.x, i = me.i, t, v;
            t = X[i];
            t ^= t >>> 7;
            v = t ^ t << 24;
            t = X[i + 1 & 7];
            v ^= t ^ t >>> 10;
            t = X[i + 3 & 7];
            v ^= t ^ t >>> 3;
            t = X[i + 4 & 7];
            v ^= t ^ t << 7;
            t = X[i + 7 & 7];
            t = t ^ t << 13;
            v ^= t ^ t << 9;
            X[i] = v;
            me.i = i + 1 & 7;
            return v;
          };
          function init(me2, seed2) {
            var j, X = [];
            if (seed2 === (seed2 | 0)) {
              X[0] = seed2;
            } else {
              seed2 = "" + seed2;
              for (j = 0; j < seed2.length; ++j) {
                X[j & 7] = X[j & 7] << 15 ^ seed2.charCodeAt(j) + X[j + 1 & 7] << 13;
              }
            }
            while (X.length < 8)
              X.push(0);
            for (j = 0; j < 8 && X[j] === 0; ++j)
              ;
            if (j == 8)
              X[7] = -1;
            else
              X[j];
            me2.x = X;
            me2.i = 0;
            for (j = 256; j > 0; --j) {
              me2.next();
            }
          }
          init(me, seed);
        }
        function copy(f, t) {
          t.x = f.x.slice();
          t.i = f.i;
          return t;
        }
        function impl(seed, opts) {
          if (seed == null)
            seed = +/* @__PURE__ */ new Date();
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (state.x)
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xorshift7 = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xorshift7$1);
    var xorshift7Exports = xorshift7$1.exports;
    var xor4096$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this;
          me.next = function() {
            var w = me.w, X = me.X, i = me.i, t, v;
            me.w = w = w + 1640531527 | 0;
            v = X[i + 34 & 127];
            t = X[i = i + 1 & 127];
            v ^= v << 13;
            t ^= t << 17;
            v ^= v >>> 15;
            t ^= t >>> 12;
            v = X[i] = v ^ t;
            me.i = i;
            return v + (w ^ w >>> 16) | 0;
          };
          function init(me2, seed2) {
            var t, v, i, j, w, X = [], limit = 128;
            if (seed2 === (seed2 | 0)) {
              v = seed2;
              seed2 = null;
            } else {
              seed2 = seed2 + "\0";
              v = 0;
              limit = Math.max(limit, seed2.length);
            }
            for (i = 0, j = -32; j < limit; ++j) {
              if (seed2)
                v ^= seed2.charCodeAt((j + 32) % seed2.length);
              if (j === 0)
                w = v;
              v ^= v << 10;
              v ^= v >>> 15;
              v ^= v << 4;
              v ^= v >>> 13;
              if (j >= 0) {
                w = w + 1640531527 | 0;
                t = X[j & 127] ^= v + w;
                i = 0 == t ? i + 1 : 0;
              }
            }
            if (i >= 128) {
              X[(seed2 && seed2.length || 0) & 127] = -1;
            }
            i = 127;
            for (j = 4 * 128; j > 0; --j) {
              v = X[i + 34 & 127];
              t = X[i = i + 1 & 127];
              v ^= v << 13;
              t ^= t << 17;
              v ^= v >>> 15;
              t ^= t >>> 12;
              X[i] = v ^ t;
            }
            me2.w = w;
            me2.X = X;
            me2.i = i;
          }
          init(me, seed);
        }
        function copy(f, t) {
          t.i = f.i;
          t.w = f.w;
          t.X = f.X.slice();
          return t;
        }
        function impl(seed, opts) {
          if (seed == null)
            seed = +/* @__PURE__ */ new Date();
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (state.X)
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xor4096 = impl;
        }
      })(
        commonjsGlobal,
        // window object or global
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xor4096$1);
    var xor4096Exports = xor4096$1.exports;
    var tychei$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this, strseed = "";
          me.next = function() {
            var b = me.b, c = me.c, d = me.d, a = me.a;
            b = b << 25 ^ b >>> 7 ^ c;
            c = c - d | 0;
            d = d << 24 ^ d >>> 8 ^ a;
            a = a - b | 0;
            me.b = b = b << 20 ^ b >>> 12 ^ c;
            me.c = c = c - d | 0;
            me.d = d << 16 ^ c >>> 16 ^ a;
            return me.a = a - b | 0;
          };
          me.a = 0;
          me.b = 0;
          me.c = 2654435769 | 0;
          me.d = 1367130551;
          if (seed === Math.floor(seed)) {
            me.a = seed / 4294967296 | 0;
            me.b = seed | 0;
          } else {
            strseed += seed;
          }
          for (var k = 0; k < strseed.length + 20; k++) {
            me.b ^= strseed.charCodeAt(k) | 0;
            me.next();
          }
        }
        function copy(f, t) {
          t.a = f.a;
          t.b = f.b;
          t.c = f.c;
          t.d = f.d;
          return t;
        }
        function impl(seed, opts) {
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (typeof state == "object")
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.tychei = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(tychei$1);
    var tycheiExports = tychei$1.exports;
    var seedrandom$1 = { exports: {} };
    var _nodeResolve_empty = {};
    var _nodeResolve_empty$1 = {
      __proto__: null,
      default: _nodeResolve_empty
    };
    var require$$0 = /* @__PURE__ */ getAugmentedNamespace(_nodeResolve_empty$1);
    (function(module3) {
      (function(global2, pool2, math) {
        var width = 256, chunks = 6, digits = 52, rngname = "random", startdenom = math.pow(width, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask = width - 1, nodecrypto;
        function seedrandom2(seed, options, callback) {
          var key = [];
          options = options == true ? { entropy: true } : options || {};
          var shortseed = mixkey(flatten2(options.entropy ? [seed, tostring(pool2)] : seed == null ? autoseed() : seed, 3), key);
          var arc4 = new ARC4(key);
          var prng = function() {
            var n = arc4.g(chunks), d = startdenom, x = 0;
            while (n < significance) {
              n = (n + x) * width;
              d *= width;
              x = arc4.g(1);
            }
            while (n >= overflow) {
              n /= 2;
              d /= 2;
              x >>>= 1;
            }
            return (n + x) / d;
          };
          prng.int32 = function() {
            return arc4.g(4) | 0;
          };
          prng.quick = function() {
            return arc4.g(4) / 4294967296;
          };
          prng.double = prng;
          mixkey(tostring(arc4.S), pool2);
          return (options.pass || callback || function(prng2, seed2, is_math_call, state) {
            if (state) {
              if (state.S) {
                copy(state, arc4);
              }
              prng2.state = function() {
                return copy(arc4, {});
              };
            }
            if (is_math_call) {
              math[rngname] = prng2;
              return seed2;
            } else
              return prng2;
          })(prng, shortseed, "global" in options ? options.global : this == math, options.state);
        }
        function ARC4(key) {
          var t, keylen = key.length, me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
          if (!keylen) {
            key = [keylen++];
          }
          while (i < width) {
            s[i] = i++;
          }
          for (i = 0; i < width; i++) {
            s[i] = s[j = mask & j + key[i % keylen] + (t = s[i])];
            s[j] = t;
          }
          (me.g = function(count) {
            var t2, r = 0, i2 = me.i, j2 = me.j, s2 = me.S;
            while (count--) {
              t2 = s2[i2 = mask & i2 + 1];
              r = r * width + s2[mask & (s2[i2] = s2[j2 = mask & j2 + t2]) + (s2[j2] = t2)];
            }
            me.i = i2;
            me.j = j2;
            return r;
          })(width);
        }
        function copy(f, t) {
          t.i = f.i;
          t.j = f.j;
          t.S = f.S.slice();
          return t;
        }
        function flatten2(obj, depth) {
          var result = [], typ = typeof obj, prop;
          if (depth && typ == "object") {
            for (prop in obj) {
              try {
                result.push(flatten2(obj[prop], depth - 1));
              } catch (e) {
              }
            }
          }
          return result.length ? result : typ == "string" ? obj : obj + "\0";
        }
        function mixkey(seed, key) {
          var stringseed = seed + "", smear, j = 0;
          while (j < stringseed.length) {
            key[mask & j] = mask & (smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++);
          }
          return tostring(key);
        }
        function autoseed() {
          try {
            var out;
            if (nodecrypto && (out = nodecrypto.randomBytes)) {
              out = out(width);
            } else {
              out = new Uint8Array(width);
              (global2.crypto || global2.msCrypto).getRandomValues(out);
            }
            return tostring(out);
          } catch (e) {
            var browser = global2.navigator, plugins = browser && browser.plugins;
            return [+/* @__PURE__ */ new Date(), global2, plugins, global2.screen, tostring(pool2)];
          }
        }
        function tostring(a) {
          return String.fromCharCode.apply(0, a);
        }
        mixkey(math.random(), pool2);
        if (module3.exports) {
          module3.exports = seedrandom2;
          try {
            nodecrypto = require$$0;
          } catch (ex) {
          }
        } else {
          math["seed" + rngname] = seedrandom2;
        }
      })(
        // global: `self` in browsers (including strict mode and web workers),
        // otherwise `this` in Node and other environments
        typeof self !== "undefined" ? self : commonjsGlobal,
        [],
        // pool: entropy pool starts empty
        Math
        // math: package containing random, pow, and seedrandom
      );
    })(seedrandom$1);
    var seedrandomExports = seedrandom$1.exports;
    var alea = aleaExports;
    var xor128 = xor128Exports;
    var xorwow = xorwowExports;
    var xorshift7 = xorshift7Exports;
    var xor4096 = xor4096Exports;
    var tychei = tycheiExports;
    var sr = seedrandomExports;
    sr.alea = alea;
    sr.xor128 = xor128;
    sr.xorwow = xorwow;
    sr.xorshift7 = xorshift7;
    sr.xor4096 = xor4096;
    sr.tychei = tychei;
    var seedrandom = sr;
    var MPRandGauss = (
      /** @class */
      function() {
        function MPRandGauss2(mean2, stdDeviation, dtype, truncated, seed) {
          this.mean = mean2;
          this.stdDev = stdDeviation;
          this.dtype = dtype;
          this.nextVal = NaN;
          this.truncated = truncated;
          if (this.truncated) {
            this.upper = this.mean + this.stdDev * 2;
            this.lower = this.mean - this.stdDev * 2;
          }
          var seedValue = seed ? seed : Math.random();
          this.random = seedrandom.alea(seedValue.toString());
        }
        MPRandGauss2.prototype.nextValue = function() {
          if (!isNaN(this.nextVal)) {
            var value = this.nextVal;
            this.nextVal = NaN;
            return value;
          }
          var resultX, resultY;
          var isValid = false;
          while (!isValid) {
            var v1 = void 0, v2 = void 0, s = void 0;
            do {
              v1 = 2 * this.random() - 1;
              v2 = 2 * this.random() - 1;
              s = v1 * v1 + v2 * v2;
            } while (s >= 1 || s === 0);
            var mul2 = Math.sqrt(-2 * Math.log(s) / s);
            resultX = this.mean + this.stdDev * v1 * mul2;
            resultY = this.mean + this.stdDev * v2 * mul2;
            if (!this.truncated || this.isValidTruncated(resultX)) {
              isValid = true;
            }
          }
          if (!this.truncated || this.isValidTruncated(resultY)) {
            this.nextVal = this.convertValue(resultY);
          }
          return this.convertValue(resultX);
        };
        MPRandGauss2.prototype.convertValue = function(value) {
          if (this.dtype == null || this.dtype === "float32") {
            return value;
          }
          return Math.round(value);
        };
        MPRandGauss2.prototype.isValidTruncated = function(value) {
          return value <= this.upper && value >= this.lower;
        };
        return MPRandGauss2;
      }()
    );
    var RandGamma = (
      /** @class */
      function() {
        function RandGamma2(alpha, beta, dtype, seed) {
          this.alpha = alpha;
          this.beta = 1 / beta;
          this.dtype = dtype;
          var seedValue = seed ? seed : Math.random();
          this.randu = seedrandom.alea(seedValue.toString());
          this.randn = new MPRandGauss(0, 1, dtype, false, this.randu());
          if (alpha < 1) {
            this.d = alpha + 2 / 3;
          } else {
            this.d = alpha - 1 / 3;
          }
          this.c = 1 / Math.sqrt(9 * this.d);
        }
        RandGamma2.prototype.nextValue = function() {
          var x2, v0, v1, x, u, v;
          while (true) {
            do {
              x = this.randn.nextValue();
              v = 1 + this.c * x;
            } while (v <= 0);
            v *= v * v;
            x2 = x * x;
            v0 = 1 - 0.331 * x2 * x2;
            v1 = 0.5 * x2 + this.d * (1 - v + Math.log(v));
            u = this.randu();
            if (u < v0 || Math.log(u) < v1) {
              break;
            }
          }
          v = 1 / this.beta * this.d * v;
          if (this.alpha < 1) {
            v *= Math.pow(this.randu(), 1 / this.alpha);
          }
          return this.convertValue(v);
        };
        RandGamma2.prototype.convertValue = function(value) {
          if (this.dtype === "float32") {
            return value;
          }
          return Math.round(value);
        };
        return RandGamma2;
      }()
    );
    var UniformRandom = (
      /** @class */
      function() {
        function UniformRandom2(min2, max2, dtype, seed) {
          if (min2 === void 0) {
            min2 = 0;
          }
          if (max2 === void 0) {
            max2 = 1;
          }
          var _this = this;
          this.canReturnFloat = function() {
            return _this.dtype == null || _this.dtype === "float32";
          };
          this.min = min2;
          this.range = max2 - min2;
          this.dtype = dtype;
          if (seed == null) {
            seed = Math.random();
          }
          if (typeof seed === "number") {
            seed = seed.toString();
          }
          if (!this.canReturnFloat() && this.range <= 1) {
            throw new Error("The difference between ".concat(min2, " - ").concat(max2, " <= 1 and dtype is not float"));
          }
          this.random = seedrandom.alea(seed);
        }
        UniformRandom2.prototype.convertValue = function(value) {
          if (this.canReturnFloat()) {
            return value;
          }
          return Math.round(value);
        };
        UniformRandom2.prototype.nextValue = function() {
          return this.convertValue(this.min + this.range * this.random());
        };
        return UniformRandom2;
      }()
    );
    function randomGamma_(shape, alpha, beta, dtype, seed) {
      if (beta === void 0) {
        beta = 1;
      }
      if (dtype === void 0) {
        dtype = "float32";
      }
      assertNonNegativeIntegerDimensions(shape);
      if (beta == null) {
        beta = 1;
      }
      if (dtype == null) {
        dtype = "float32";
      }
      if (dtype !== "float32" && dtype !== "int32") {
        throw new Error("Unsupported data type ".concat(dtype));
      }
      var rgamma = new RandGamma(alpha, beta, dtype, seed);
      var res = buffer(shape, dtype);
      for (var i = 0; i < res.values.length; i++) {
        res.values[i] = rgamma.nextValue();
      }
      return res.toTensor();
    }
    var randomGamma = /* @__PURE__ */ op({ randomGamma_ });
    function randomNormal_(shape, mean2, stdDev, dtype, seed) {
      if (mean2 === void 0) {
        mean2 = 0;
      }
      if (stdDev === void 0) {
        stdDev = 1;
      }
      assertNonNegativeIntegerDimensions(shape);
      if (dtype != null && dtype === "bool") {
        throw new Error("Unsupported data type ".concat(dtype));
      }
      var randGauss = new MPRandGauss(mean2, stdDev, dtype, false, seed);
      var res = buffer(shape, dtype);
      for (var i = 0; i < res.values.length; i++) {
        res.values[i] = randGauss.nextValue();
      }
      return res.toTensor();
    }
    var randomNormal = /* @__PURE__ */ op({ randomNormal_ });
    function randomStandardNormal_(shape, dtype, seed) {
      if (dtype != null && dtype === "bool") {
        throw new Error("Unsupported data type ".concat(dtype));
      }
      return randomNormal(shape, 0, 1, dtype, seed);
    }
    var randomStandardNormal = /* @__PURE__ */ op({ randomStandardNormal_ });
    function randomUniform_(shape, minval, maxval, dtype, seed) {
      if (minval === void 0) {
        minval = 0;
      }
      if (maxval === void 0) {
        maxval = 1;
      }
      if (dtype === void 0) {
        dtype = "float32";
      }
      assertNonNegativeIntegerDimensions(shape);
      var res = buffer(shape, dtype);
      var random = new UniformRandom(minval, maxval, null, seed);
      for (var i = 0; i < res.values.length; i++) {
        res.values[i] = random.nextValue();
      }
      return res.toTensor();
    }
    var randomUniform = /* @__PURE__ */ op({ randomUniform_ });
    function randomUniformInt_(shape, minval, maxval, seed) {
      return randomUniform(shape, minval, maxval, "int32", seed);
    }
    var randomUniformInt = /* @__PURE__ */ op({ randomUniformInt_ });
    function range(start, stop, step2, dtype) {
      if (step2 === void 0) {
        step2 = 1;
      }
      if (dtype === void 0) {
        dtype = "float32";
      }
      if (step2 === 0) {
        throw new Error("Cannot have a step of zero");
      }
      var attrs = { start, stop, step: step2, dtype };
      return ENGINE.runKernel(Range, {}, attrs);
    }
    function real_(input) {
      var $input = convertToTensor(input, "input", "real");
      var inputs = { input: $input };
      return ENGINE.runKernel(Real, inputs);
    }
    var real = /* @__PURE__ */ op({ real_ });
    function reciprocal_(x) {
      var $x = convertToTensor(x, "x", "reciprocal");
      var inputs = { x: $x };
      return ENGINE.runKernel(Reciprocal, inputs);
    }
    var reciprocal = /* @__PURE__ */ op({ reciprocal_ });
    function relu_(x) {
      var $x = convertToTensor(x, "x", "relu");
      var inputs = { x: $x };
      return ENGINE.runKernel(Relu, inputs);
    }
    var relu = /* @__PURE__ */ op({ relu_ });
    function relu6_(x) {
      var $x = convertToTensor(x, "x", "relu6");
      var inputs = { x: $x };
      return ENGINE.runKernel(Relu6, inputs);
    }
    var relu6 = /* @__PURE__ */ op({ relu6_ });
    function reverse_(x, axis) {
      var $x = convertToTensor(x, "x", "reverse");
      var inputs = { x: $x };
      var attrs = { dims: axis };
      return ENGINE.runKernel(Reverse, inputs, attrs);
    }
    var reverse = /* @__PURE__ */ op({ reverse_ });
    function reverse1d_(x) {
      var $x = convertToTensor(x, "x", "reverse");
      assert($x.rank === 1, function() {
        return "Error in reverse1D: x must be rank 1 but got rank ".concat($x.rank, ".");
      });
      return reverse($x, 0);
    }
    var reverse1d = /* @__PURE__ */ op({ reverse1d_ });
    function reverse2d_(x, axis) {
      var $x = convertToTensor(x, "x", "reverse");
      assert($x.rank === 2, function() {
        return "Error in reverse2D: x must be rank 2 but got rank ".concat($x.rank, ".");
      });
      return reverse($x, axis);
    }
    var reverse2d = /* @__PURE__ */ op({ reverse2d_ });
    function reverse3d_(x, axis) {
      var $x = convertToTensor(x, "x", "reverse");
      assert($x.rank === 3, function() {
        return "Error in reverse3D: x must be rank 3 but got rank ".concat($x.rank, ".");
      });
      return reverse($x, axis);
    }
    var reverse3d = /* @__PURE__ */ op({ reverse3d_ });
    function reverse4d_(x, axis) {
      var $x = convertToTensor(x, "x", "reverse");
      assert($x.rank === 4, function() {
        return "Error in reverse4D: x must be rank 4 but got rank ".concat($x.rank, ".");
      });
      return reverse($x, axis);
    }
    var reverse4d = /* @__PURE__ */ op({ reverse4d_ });
    function round_(x) {
      var $x = convertToTensor(x, "x", "round");
      var inputs = { x: $x };
      return ENGINE.runKernel(Round, inputs);
    }
    var round = /* @__PURE__ */ op({ round_ });
    function rsqrt_(x) {
      var $x = convertToTensor(x, "x", "rsqrt", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Rsqrt, inputs);
    }
    var rsqrt = /* @__PURE__ */ op({ rsqrt_ });
    function selu_(x) {
      var $x = convertToTensor(x, "x", "selu");
      var inputs = { x: $x };
      return ENGINE.runKernel(Selu, inputs);
    }
    var selu = /* @__PURE__ */ op({ selu_ });
    function separableConv2d_(x, depthwiseFilter, pointwiseFilter, strides, pad2, dilation, dataFormat) {
      if (dilation === void 0) {
        dilation = [1, 1];
      }
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      var $x = convertToTensor(x, "x", "separableConv2d");
      var $depthwiseFilter = convertToTensor(depthwiseFilter, "depthwiseFilter", "separableConv2d");
      var $pointwiseFilter = convertToTensor(pointwiseFilter, "pointwiseFilter", "separableConv2d");
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      if (dataFormat === "NCHW") {
        throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");
      }
      assert(x4D.rank === 4, function() {
        return "Error in separableConv2d: input must be rank 4, but got " + "rank ".concat(x4D.rank, ".");
      });
      assert($depthwiseFilter.rank === 4, function() {
        return "Error in separableConv2d: depthwise filter must be rank 4, but " + "got rank ".concat($depthwiseFilter.rank, ".");
      });
      assert($pointwiseFilter.rank === 4, function() {
        return "Error in separableConv2d: pointwise filter must be rank 4, but " + "got rank ".concat($depthwiseFilter.rank, ".");
      });
      assert($pointwiseFilter.shape[0] === 1, function() {
        return "Error in separableConv2d: the first dimension of pointwise filter " + " must be 1, but got ".concat($pointwiseFilter.shape[0], ".");
      });
      assert($pointwiseFilter.shape[1] === 1, function() {
        return "Error in separableConv2d: the second dimension of pointwise " + "filter must be 1, but got ".concat($pointwiseFilter.shape[1], ".");
      });
      var inChannels = $depthwiseFilter.shape[2];
      var channelMultiplier = $depthwiseFilter.shape[3];
      assert($pointwiseFilter.shape[2] === inChannels * channelMultiplier, function() {
        return "Error in separableConv2d: the third dimension of pointwise filter " + "must be ".concat(inChannels * channelMultiplier, ", ") + "but got ".concat($pointwiseFilter.shape[2], ".");
      });
      var depthwise = depthwiseConv2d$1(x4D, $depthwiseFilter, strides, pad2, dataFormat, dilation);
      var pointwiseStride = 1;
      var res = conv2d$1(depthwise, $pointwiseFilter, pointwiseStride, "valid", dataFormat);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var separableConv2d = /* @__PURE__ */ op({ separableConv2d_ });
    function setdiff1dAsync_(x, y) {
      return __awaiter(this, void 0, void 0, function() {
        var $x, $y, xVals, yVals, ySet, outputSize, i, buffer2, indices, i, p;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              $x = convertToTensor(x, "x", "setdiff1d");
              $y = convertToTensor(y, "y", "setdiff1d");
              assert($x.dtype === $y.dtype, function() {
                return "x and y should have the same dtype, but got x (".concat($x.dtype, ") and y (").concat($y.dtype, ").");
              });
              assert($x.rank === 1, function() {
                return "x should be 1D tensor, but got x (".concat($x.shape, ").");
              });
              assert($y.rank === 1, function() {
                return "y should be 1D tensor, but got y (".concat($y.shape, ").");
              });
              return [4, $x.data()];
            case 1:
              xVals = _a.sent();
              return [4, $y.data()];
            case 2:
              yVals = _a.sent();
              ySet = new Set(yVals);
              outputSize = 0;
              for (i = 0; i < xVals.length; i++) {
                if (!ySet.has(xVals[i])) {
                  outputSize++;
                }
              }
              buffer2 = new TensorBuffer([outputSize], $x.dtype);
              indices = new TensorBuffer([outputSize], "int32");
              for (i = 0, p = 0; i < xVals.length; i++) {
                if (!ySet.has(xVals[i])) {
                  buffer2.values[p] = xVals[i];
                  indices.values[p] = i;
                  p++;
                }
              }
              return [2, [buffer2.toTensor(), indices.toTensor()]];
          }
        });
      });
    }
    var setdiff1dAsync = setdiff1dAsync_;
    function sign_(x) {
      var $x = convertToTensor(x, "x", "sign");
      var inputs = { x: $x };
      return ENGINE.runKernel(Sign, inputs);
    }
    var sign = /* @__PURE__ */ op({ sign_ });
    function sin_(x) {
      var $x = convertToTensor(x, "x", "sin", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Sin, inputs);
    }
    var sin = /* @__PURE__ */ op({ sin_ });
    function sinh_(x) {
      var $x = convertToTensor(x, "x", "sinh");
      var inputs = { x: $x };
      return ENGINE.runKernel(Sinh, inputs);
    }
    var sinh = /* @__PURE__ */ op({ sinh_ });
    function slice1d_(x, begin, size) {
      var $x = convertToTensor(x, "x", "slice1d");
      assert($x.rank === 1, function() {
        return "slice1d expects a rank-1 tensor, but got a rank-".concat($x.rank, " tensor");
      });
      return slice($x, [begin], [size]);
    }
    var slice1d = /* @__PURE__ */ op({ slice1d_ });
    function slice2d_(x, begin, size) {
      var $x = convertToTensor(x, "x", "slice2d");
      assert($x.rank === 2, function() {
        return "slice2d expects a rank-2 tensor, but got a rank-".concat($x.rank, " tensor");
      });
      return slice($x, begin, size);
    }
    var slice2d = /* @__PURE__ */ op({ slice2d_ });
    function slice3d_(x, begin, size) {
      var $x = convertToTensor(x, "x", "slice3d");
      assert($x.rank === 3, function() {
        return "slice3d expects a rank-3 tensor, but got a rank-".concat($x.rank, " tensor");
      });
      return slice($x, begin, size);
    }
    var slice3d = /* @__PURE__ */ op({ slice3d_ });
    function slice4d_(x, begin, size) {
      var $x = convertToTensor(x, "x", "slice4d");
      assert($x.rank === 4, function() {
        return "slice4d expects a rank-4 tensor, but got a rank-".concat($x.rank, " tensor");
      });
      return slice($x, begin, size);
    }
    var slice4d = /* @__PURE__ */ op({ slice4d_ });
    function softmax_(logits, dim) {
      if (dim === void 0) {
        dim = -1;
      }
      var $logits = convertToTensor(logits, "logits", "softmax", "float32");
      if (dim === -1) {
        dim = $logits.rank - 1;
      }
      if (dim !== $logits.rank - 1) {
        throw Error("Softmax along a non-last dimension is not yet supported. " + "Logits was rank ".concat($logits.rank, " and dim was ").concat(dim));
      }
      var inputs = { logits: $logits };
      var attrs = { dim };
      return ENGINE.runKernel(Softmax, inputs, attrs);
    }
    var softmax = /* @__PURE__ */ op({ softmax_ });
    function fft_(input) {
      assert(input.dtype === "complex64", function() {
        return "The dtype for tf.spectral.fft() must be complex64 " + "but got ".concat(input.dtype, ".");
      });
      var inputs = { input };
      return ENGINE.runKernel(FFT, inputs);
    }
    var fft = /* @__PURE__ */ op({ fft_ });
    function ifft_(input) {
      assert(input.dtype === "complex64", function() {
        return "The dtype for tf.spectral.ifft() must be complex64 " + "but got ".concat(input.dtype, ".");
      });
      var inputs = { input };
      return ENGINE.runKernel(IFFT, inputs);
    }
    var ifft = /* @__PURE__ */ op({ ifft_ });
    function irfft_(input) {
      var innerDimensionSize = input.shape[input.shape.length - 1];
      var batch = input.size / innerDimensionSize;
      var ret;
      if (innerDimensionSize <= 2) {
        var complexInput = reshape(input, [batch, innerDimensionSize]);
        ret = ifft(complexInput);
      } else {
        var outputShape = [batch, 2 * (innerDimensionSize - 1)];
        var realInput = reshape(real(input), [batch, innerDimensionSize]);
        var imagInput = reshape(imag(input), [batch, innerDimensionSize]);
        var realConjugate = reverse(slice(realInput, [0, 1], [batch, innerDimensionSize - 2]), 1);
        var imagConjugate = mul(reverse(slice(imagInput, [0, 1], [batch, innerDimensionSize - 2]), 1), scalar(-1));
        var r = concat([realInput, realConjugate], 1);
        var i = concat([imagInput, imagConjugate], 1);
        var complexInput = reshape(complex(r, i), [outputShape[0], outputShape[1]]);
        ret = ifft(complexInput);
      }
      ret = real(ret);
      if (input.rank === 3 && input.shape[0] !== 0) {
        var temp = ret;
        var batch_1 = input.shape[0];
        ret = reshape(ret, [batch_1, ret.shape[0] / batch_1, ret.shape[1]]);
        temp.dispose();
      }
      return ret;
    }
    var irfft = /* @__PURE__ */ op({ irfft_ });
    function split_(x, numOrSizeSplits, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $x = convertToTensor(x, "x", "split");
      var inputs = { x: $x };
      var attr = { numOrSizeSplits, axis };
      return ENGINE.runKernel(SplitV, inputs, attr);
    }
    var split$1 = /* @__PURE__ */ op({ split_ });
    function rfft_(input, fftLength) {
      assert(input.dtype === "float32", function() {
        return "The dtype for rfft() must be real value but got ".concat(input.dtype);
      });
      var innerDimensionSize = input.shape[input.shape.length - 1];
      var batch = input.size / innerDimensionSize;
      var adjustedInput;
      if (fftLength != null && fftLength < innerDimensionSize) {
        var begin = input.shape.map(function(v) {
          return 0;
        });
        var size = input.shape.map(function(v) {
          return v;
        });
        size[input.shape.length - 1] = fftLength;
        adjustedInput = slice(input, begin, size);
        innerDimensionSize = fftLength;
      } else if (fftLength != null && fftLength > innerDimensionSize) {
        var zerosShape = input.shape.map(function(v) {
          return v;
        });
        zerosShape[input.shape.length - 1] = fftLength - innerDimensionSize;
        adjustedInput = concat([input, zeros(zerosShape)], input.shape.length - 1);
        innerDimensionSize = fftLength;
      } else {
        adjustedInput = input;
      }
      var zerosInput = zerosLike(adjustedInput);
      var complexInput = reshape(complex(adjustedInput, zerosInput), [batch, innerDimensionSize]);
      var ret = fft(complexInput);
      var half = Math.floor(innerDimensionSize / 2) + 1;
      var realValues = real(ret);
      var imagValues = imag(ret);
      var realComplexConjugate = split$1(realValues, [half, innerDimensionSize - half], realValues.shape.length - 1);
      var imagComplexConjugate = split$1(imagValues, [half, innerDimensionSize - half], imagValues.shape.length - 1);
      var outputShape = adjustedInput.shape.slice();
      outputShape[adjustedInput.shape.length - 1] = half;
      return reshape(complex(realComplexConjugate[0], imagComplexConjugate[0]), outputShape);
    }
    var rfft = /* @__PURE__ */ op({ rfft_ });
    function squaredDifference_(a, b) {
      var _a;
      var $a = convertToTensor(a, "a", "squaredDifference");
      var $b = convertToTensor(b, "b", "squaredDifference");
      _a = __read(makeTypesMatch($a, $b), 2), $a = _a[0], $b = _a[1];
      assertAndGetBroadcastShape($a.shape, $b.shape);
      var inputs = { a: $a, b: $b };
      var attrs = {};
      return ENGINE.runKernel(SquaredDifference, inputs, attrs);
    }
    var squaredDifference = /* @__PURE__ */ op({ squaredDifference_ });
    function squeeze_(x, axis) {
      var $x = convertToTensor(x, "x", "squeeze", "string_or_numeric");
      return reshape($x, squeezeShape($x.shape, axis).newShape);
    }
    var squeeze = /* @__PURE__ */ op({ squeeze_ });
    function stack_(tensors, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $tensors = convertToTensorArray(tensors, "tensors", "stack", "string_or_numeric");
      assert($tensors.length >= 1, function() {
        return "Pass at least one tensor to tf.stack";
      });
      if ($tensors.length > 0) {
        assert(axis <= $tensors[0].rank, function() {
          return "Axis must be <= rank of the tensor";
        });
      }
      var inputs = $tensors;
      var attrs = { axis };
      return ENGINE.runKernel(Pack, inputs, attrs);
    }
    var stack = /* @__PURE__ */ op({ stack_ });
    function step_(x, alpha) {
      if (alpha === void 0) {
        alpha = 0;
      }
      var $x = convertToTensor(x, "x", "step");
      var inputs = { x: $x };
      var attrs = { alpha };
      return ENGINE.runKernel(Step, inputs, attrs);
    }
    var step = /* @__PURE__ */ op({ step_ });
    function stridedSlice_(x, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask) {
      if (beginMask === void 0) {
        beginMask = 0;
      }
      if (endMask === void 0) {
        endMask = 0;
      }
      if (ellipsisMask === void 0) {
        ellipsisMask = 0;
      }
      if (newAxisMask === void 0) {
        newAxisMask = 0;
      }
      if (shrinkAxisMask === void 0) {
        shrinkAxisMask = 0;
      }
      var $x = convertToTensor(x, "x", "stridedSlice", "string_or_numeric");
      var inputs = { x: $x };
      var attrs = {
        begin,
        end,
        strides,
        beginMask,
        endMask,
        ellipsisMask,
        newAxisMask,
        shrinkAxisMask
      };
      return ENGINE.runKernel(StridedSlice, inputs, attrs);
    }
    var stridedSlice = /* @__PURE__ */ op({ stridedSlice_ });
    function tan_(x) {
      var $x = convertToTensor(x, "x", "tan", "float32");
      var inputs = { x: $x };
      return ENGINE.runKernel(Tan, inputs);
    }
    var tan = /* @__PURE__ */ op({ tan_ });
    function tensor(values, shape, dtype) {
      var inferredShape = inferShape(values, dtype);
      return makeTensor(values, shape, inferredShape, dtype);
    }
    function tensor1d(values, dtype) {
      assertNonNull(values);
      var inferredShape = inferShape(values, dtype);
      if (inferredShape.length !== 1) {
        throw new Error("tensor1d() requires values to be a flat/TypedArray");
      }
      var shape = null;
      return makeTensor(values, shape, inferredShape, dtype);
    }
    function tensor2d(values, shape, dtype) {
      assertNonNull(values);
      if (shape != null && shape.length !== 2) {
        throw new Error("tensor2d() requires shape to have two numbers");
      }
      var inferredShape = inferShape(values, dtype);
      if (inferredShape.length !== 2 && inferredShape.length !== 1) {
        throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");
      }
      if (inferredShape.length === 1 && shape == null) {
        throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");
      }
      return makeTensor(values, shape, inferredShape, dtype);
    }
    function tensor3d(values, shape, dtype) {
      assertNonNull(values);
      if (shape != null && shape.length !== 3) {
        throw new Error("tensor3d() requires shape to have three numbers");
      }
      var inferredShape = inferShape(values, dtype);
      if (inferredShape.length !== 3 && inferredShape.length !== 1) {
        throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");
      }
      if (inferredShape.length === 1 && shape == null) {
        throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");
      }
      return makeTensor(values, shape, inferredShape, dtype);
    }
    function tensor4d(values, shape, dtype) {
      assertNonNull(values);
      if (shape != null && shape.length !== 4) {
        throw new Error("tensor4d() requires shape to have four numbers");
      }
      var inferredShape = inferShape(values, dtype);
      if (inferredShape.length !== 4 && inferredShape.length !== 1) {
        throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");
      }
      if (inferredShape.length === 1 && shape == null) {
        throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");
      }
      return makeTensor(values, shape, inferredShape, dtype);
    }
    function tensor5d(values, shape, dtype) {
      assertNonNull(values);
      if (shape != null && shape.length !== 5) {
        throw new Error("tensor5d() requires shape to have five numbers");
      }
      var inferredShape = inferShape(values, dtype);
      if (inferredShape.length !== 5 && inferredShape.length !== 1) {
        throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");
      }
      if (inferredShape.length === 1 && shape == null) {
        throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");
      }
      return makeTensor(values, shape, inferredShape, dtype);
    }
    function tensor6d(values, shape, dtype) {
      assertNonNull(values);
      if (shape != null && shape.length !== 6) {
        throw new Error("tensor6d() requires shape to have six numbers");
      }
      var inferredShape = inferShape(values, dtype);
      if (inferredShape.length !== 6 && inferredShape.length !== 1) {
        throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");
      }
      if (inferredShape.length === 1 && shape == null) {
        throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");
      }
      shape = shape || inferredShape;
      return makeTensor(values, shape, inferredShape, dtype);
    }
    function validateUpdateShape(shape, indices, updates) {
      var sliceDim = indices.rank > 1 ? indices.shape[indices.rank - 1] : 1;
      var batchDim = indices.rank > 1 ? indices.rank - 1 : 1;
      var shapeError = "Must have updates.shape = indices.shape[:batchDim] + " + "shape[sliceDim:], got updates.shape: ".concat(updates.shape) + ", indices.shape: ".concat(indices.shape, ", shape: ").concat(shape) + ", sliceDim: ".concat(sliceDim, ", and batchDim: ").concat(batchDim, ".");
      if (updates.rank < batchDim) {
        throw new Error(shapeError + " update.rank < ".concat(batchDim, ". "));
      }
      if (shape.length < sliceDim + (updates.rank - batchDim)) {
        throw new Error(shapeError + " Output shape length < ".concat(sliceDim + (updates.rank - batchDim)));
      }
      if (updates.rank !== batchDim + shape.length - sliceDim) {
        throw new Error(shapeError + " update.rank != ".concat(batchDim + shape.length - sliceDim));
      }
      for (var d = 0; d < batchDim; ++d) {
        if (updates.shape[d] !== indices.shape[d]) {
          throw new Error(shapeError + " updates.shape[".concat(d, "] (").concat(updates.shape[d], ") != indices.shape[").concat(d, "] (").concat(indices.shape[d], ")."));
        }
      }
      for (var d = 0; d < updates.rank - batchDim; ++d) {
        if (updates.shape[d + batchDim] !== shape[d + sliceDim]) {
          throw new Error(shapeError + " updates.shape[".concat(d + batchDim, "] (").concat(updates.shape[d + batchDim], ") != shape[").concat(d + batchDim, "] (").concat(shape[d + batchDim], ")"));
        }
      }
    }
    function validateInput$1(updates, indices, shape) {
      if (indices.rank < 1) {
        throw new Error("tf.scatterND() expects the indices to be rank 1 or higher," + " but the rank was ".concat(indices.rank, "."));
      }
      if (updates.rank < 1) {
        throw new Error("tf.scatterND() expects the updates to be rank 1 or higher," + " but the rank was ".concat(updates.rank, "."));
      }
      if (indices.dtype !== "int32") {
        throw new Error("The dtype of 'indices' should be int32, but got dtype: ".concat(indices.dtype));
      }
      if (shape.length < 1) {
        throw new Error("Output rank must be greater or equal to 1, but got shape: ".concat(shape));
      }
      if (shape.length === 0) {
        if (indices.size === 0) {
          throw new Error("Indices specified for empty output. indices shape: ".concat(indices.shape));
        }
        if (updates.size === 0) {
          throw new Error("Updates specified for empty output. updates shape: ".concat(updates.shape));
        }
      }
      validateUpdateShape(shape, indices, updates);
    }
    function tensorScatterUpdate_(tensor2, indices, updates) {
      var $tensor = convertToTensor(tensor2, "tensor", "tensorScatterupdate");
      var $indices = convertToTensor(indices, "indices", "tensorScatterupdate", "int32");
      var $updates = convertToTensor(updates, "updates", "tensorScatterupdate");
      validateInput$1($updates, $indices, $tensor.shape);
      if ($tensor.dtype !== $updates.dtype) {
        throw new Error("tensor and updates must have the same dtype, instead they are ".concat($tensor.dtype, " and ").concat($updates.dtype, "."));
      }
      var inputs = {
        tensor: $tensor,
        indices: $indices,
        updates: $updates
      };
      var attrs = {};
      return ENGINE.runKernel(TensorScatterUpdate, inputs, attrs);
    }
    var tensorScatterUpdate = op({ tensorScatterUpdate_ });
    function topk_(x, k, sorted) {
      if (k === void 0) {
        k = 1;
      }
      if (sorted === void 0) {
        sorted = true;
      }
      var $x = convertToTensor(x, "x", "topk");
      if ($x.rank === 0) {
        throw new Error("topk() expects the input to be of rank 1 or higher");
      }
      var lastDim = $x.shape[$x.shape.length - 1];
      if (k < 0) {
        throw new Error("'k' passed to topk() must be >= 0 but got ".concat(k));
      }
      if (k > lastDim) {
        throw new Error("'k' passed to topk() must be <= the last dimension (".concat(lastDim, ") ") + "but got ".concat(k));
      }
      var inputs = { x: $x };
      var attrs = { k, sorted };
      var _a = __read(ENGINE.runKernel(TopK, inputs, attrs), 2), values = _a[0], indices = _a[1];
      return { values, indices };
    }
    var topk = /* @__PURE__ */ op({ topk_ });
    function truncatedNormal_(shape, mean2, stdDev, dtype, seed) {
      if (mean2 === void 0) {
        mean2 = 0;
      }
      if (stdDev === void 0) {
        stdDev = 1;
      }
      assertNonNegativeIntegerDimensions(shape);
      if (dtype != null && dtype === "bool") {
        throw new Error("Unsupported data type $ { dtype }");
      }
      var randGauss = new MPRandGauss(mean2, stdDev, dtype, true, seed);
      var res = buffer(shape, dtype);
      for (var i = 0; i < res.values.length; i++) {
        res.values[i] = randGauss.nextValue();
      }
      return res.toTensor();
    }
    var truncatedNormal = /* @__PURE__ */ op({ truncatedNormal_ });
    function unique_(x, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $x = convertToTensor(x, "x", "unique", "string_or_numeric");
      assert($x.rank > 0, function() {
        return "The input tensor must be at least 1D";
      });
      var inputs = { x: $x };
      var attrs = { axis };
      var _a = __read(ENGINE.runKernel(Unique, inputs, attrs), 2), values = _a[0], indices = _a[1];
      return { values, indices };
    }
    var unique = /* @__PURE__ */ op({ unique_ });
    function unsortedSegmentSum_(x, segmentIds, numSegments) {
      var $x = convertToTensor(x, "x", "unsortedSegmentSum");
      var $segmentIds = convertToTensor(segmentIds, "segmentIds", "unsortedSegmentSum", "int32");
      assert(isInt(numSegments), function() {
        return "numSegments must be of dtype int";
      });
      var inputs = { x: $x, segmentIds: $segmentIds };
      var attrs = { numSegments };
      return ENGINE.runKernel(UnsortedSegmentSum, inputs, attrs);
    }
    var unsortedSegmentSum = /* @__PURE__ */ op({ unsortedSegmentSum_ });
    function unstack_(x, axis) {
      if (axis === void 0) {
        axis = 0;
      }
      var $x = convertToTensor(x, "x", "unstack", "string_or_numeric");
      assert(axis >= -$x.shape.length && axis < $x.shape.length, function() {
        return "Axis = ".concat(axis, " is not in [-").concat($x.shape.length, ", ").concat($x.shape.length, ")");
      });
      var inputs = { value: $x };
      var attrs = { axis };
      return ENGINE.runKernel(Unpack, inputs, attrs);
    }
    var unstack = /* @__PURE__ */ op({ unstack_ });
    function upperBound(sortedSequence, values) {
      return searchSorted(sortedSequence, values, "right");
    }
    function variable(initialValue, trainable, name, dtype) {
      if (trainable === void 0) {
        trainable = true;
      }
      return ENGINE.makeVariable(initialValue, trainable, name, dtype);
    }
    function whereImpl(condShape, condVals) {
      var indices = [];
      for (var i = 0; i < condVals.length; i++) {
        if (condVals[i]) {
          indices.push(i);
        }
      }
      var inBuffer = buffer(condShape, "int32");
      var out = buffer([indices.length, condShape.length], "int32");
      for (var i = 0; i < indices.length; i++) {
        var loc = inBuffer.indexToLoc(indices[i]);
        var offset = i * condShape.length;
        out.values.set(loc, offset);
      }
      return out.toTensor();
    }
    function whereAsync_(condition) {
      return __awaiter(this, void 0, void 0, function() {
        var $condition, vals, res;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              $condition = convertToTensor(condition, "condition", "whereAsync", "bool");
              return [4, $condition.data()];
            case 1:
              vals = _a.sent();
              res = whereImpl($condition.shape, vals);
              if (condition !== $condition) {
                $condition.dispose();
              }
              return [2, res];
          }
        });
      });
    }
    var whereAsync = whereAsync_;
    function booleanMaskAsync_(tensor2, mask, axis) {
      return __awaiter(this, void 0, void 0, function() {
        var $tensor, $mask, axisFrom, maskDim, tensorShape, leadingSize, i, targetTensorShape, reshapedTensor, reshapedMask, positivePositions, indices, res;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              $tensor = convertToTensor(tensor2, "tensor", "boolMask");
              $mask = convertToTensor(mask, "mask", "boolMask", "bool");
              axisFrom = axis == null ? 0 : axis;
              maskDim = $mask.rank;
              tensorShape = $tensor.shape;
              assert(maskDim > 0, function() {
                return "mask cannot be scalar";
              });
              assertShapesMatch(tensorShape.slice(axisFrom, axisFrom + maskDim), $mask.shape, "mask's shape must match the first K dimensions of tensor's shape,");
              leadingSize = 1;
              for (i = axisFrom; i < axisFrom + maskDim; i++) {
                leadingSize *= tensorShape[i];
              }
              targetTensorShape = tensorShape.slice(0, axisFrom).concat([leadingSize], tensorShape.slice(axisFrom + maskDim));
              reshapedTensor = reshape($tensor, targetTensorShape);
              reshapedMask = reshape($mask, [-1]);
              return [4, whereAsync(reshapedMask)];
            case 1:
              positivePositions = _a.sent();
              indices = squeeze(positivePositions, [1]);
              res = gather(reshapedTensor, indices, axisFrom);
              if (tensor2 !== $tensor) {
                $tensor.dispose();
              }
              if (mask !== $mask) {
                $mask.dispose();
              }
              indices.dispose();
              reshapedTensor.dispose();
              reshapedMask.dispose();
              positivePositions.dispose();
              return [2, res];
          }
        });
      });
    }
    var booleanMaskAsync = booleanMaskAsync_;
    function tidy(nameOrFn, fn) {
      return ENGINE.tidy(nameOrFn, fn);
    }
    function dispose(container) {
      var tensors = getTensorsInContainer(container);
      tensors.forEach(function(tensor2) {
        return tensor2.dispose();
      });
    }
    function getBackend() {
      return ENGINE.backendName;
    }
    function backend() {
      return ENGINE.backend;
    }
    function transpose_(x, perm, conjugate) {
      var $x = convertToTensor(x, "x", "transpose");
      if (perm == null) {
        perm = $x.shape.map(function(s, i) {
          return i;
        }).reverse();
      }
      assert($x.rank === perm.length, function() {
        return "Error in transpose: rank of input ".concat($x.rank, " ") + "must match length of perm ".concat(perm, ".");
      });
      perm.forEach(function(axis) {
        assert(axis >= 0 && axis < $x.rank, function() {
          return "All entries in 'perm' must be between 0 and ".concat($x.rank - 1) + " but got ".concat(perm);
        });
      });
      if ($x.rank <= 1) {
        return $x.clone();
      }
      var inputs = { x: $x };
      var attrs = { perm };
      if ($x.dtype === "complex64") {
        return tidy(function() {
          var $real = real($x);
          var $imag = imag($x);
          $real = ENGINE.runKernel(Transpose, { x: $real }, attrs);
          $imag = ENGINE.runKernel(Transpose, { x: $imag }, attrs);
          if (conjugate) {
            $imag = neg($imag);
          }
          return complex($real, $imag);
        });
      }
      return ENGINE.runKernel(Transpose, inputs, attrs);
    }
    var transpose = /* @__PURE__ */ op({ transpose_ });
    function movingAverage_(v, x, decay, step2, zeroDebias) {
      if (zeroDebias === void 0) {
        zeroDebias = true;
      }
      var $v = convertToTensor(v, "v", "movingAverage");
      var $x = convertToTensor(x, "x", "movingAverage");
      var $decay = convertToTensor(decay, "decay", "movingAverage");
      assertTypesMatch($v, $x);
      assert(arraysEqual($v.shape, $x.shape), function() {
        return "Shape mismatch in v and x";
      });
      var one = scalar(1);
      var oneMinusDecay = sub(one, $decay);
      var update = mul(sub($x, $v), oneMinusDecay);
      if (zeroDebias) {
        assert(step2 != null, function() {
          return "When using zeroDebias: true, step is required.";
        });
        var $step = convertToTensor(step2, "step", "movingAverage");
        update = div(update, sub(one, pow($decay, $step)));
      }
      return add($v, update);
    }
    var movingAverage = /* @__PURE__ */ op({ movingAverage_ });
    function scatterND_(indices, updates, shape) {
      assertNonNegativeIntegerDimensions(shape);
      var $indices = convertToTensor(indices, "indices", "scatterND", "int32");
      var $updates = convertToTensor(updates, "updates", "scatterND");
      validateInput$1($updates, $indices, shape);
      var inputs = { indices: $indices, updates: $updates };
      var attrs = { shape };
      return ENGINE.runKernel(ScatterNd, inputs, attrs);
    }
    var scatterND = /* @__PURE__ */ op({ scatterND_ });
    function validateInput(sparseIndices, sparseValues, outputShape, defaultValues) {
      if (sparseIndices.dtype !== "int32") {
        throw new Error("tf.sparseToDense() expects the indices to be int32 type," + " but the dtype was ".concat(sparseIndices.dtype, "."));
      }
      if (sparseIndices.rank > 2) {
        throw new Error("sparseIndices should be a scalar, vector, or matrix," + " but got shape ".concat(sparseIndices.shape, "."));
      }
      var numElems = sparseIndices.rank > 0 ? sparseIndices.shape[0] : 1;
      var numDims = sparseIndices.rank > 1 ? sparseIndices.shape[1] : 1;
      if (outputShape.length !== numDims) {
        throw new Error("outputShape has incorrect number of elements:," + " ".concat(outputShape.length, ", should be: ").concat(numDims, "."));
      }
      var numValues = sparseValues.size;
      if (!(sparseValues.rank === 0 || sparseValues.rank === 1 && numValues === numElems)) {
        throw new Error("sparseValues has incorrect shape " + "".concat(sparseValues.shape, ", should be [] or [").concat(numElems, "]"));
      }
      if (sparseValues.dtype !== defaultValues.dtype) {
        throw new Error("sparseValues.dtype must match defaultValues.dtype");
      }
    }
    function sparseToDense_(sparseIndices, sparseValues, outputShape, defaultValue) {
      if (defaultValue === void 0) {
        defaultValue = 0;
      }
      assertNonNegativeIntegerDimensions(outputShape);
      var $sparseIndices = convertToTensor(sparseIndices, "sparseIndices", "sparseToDense", "int32");
      var $sparseValues = convertToTensor(sparseValues, "sparseValues", "sparseToDense", "string_or_numeric");
      var $defaultValue = convertToTensor(defaultValue, "defaultValue", "sparseToDense", $sparseValues.dtype);
      validateInput($sparseIndices, $sparseValues, outputShape, $defaultValue);
      var inputs = {
        sparseIndices: $sparseIndices,
        sparseValues: $sparseValues,
        defaultValue: $defaultValue
      };
      var attrs = { outputShape };
      return ENGINE.runKernel(SparseToDense, inputs, attrs);
    }
    var sparseToDense = /* @__PURE__ */ op({ sparseToDense_ });
    function gatherND_(x, indices) {
      var $indices = convertToTensor(indices, "indices", "gatherND", "int32");
      var $x = convertToTensor(x, "x", "gatherND", "string_or_numeric");
      var inputs = { params: $x, indices: $indices };
      return ENGINE.runKernel(GatherNd, inputs);
    }
    var gatherND = /* @__PURE__ */ op({ gatherND_ });
    function getNoiseShape(x, noiseShape) {
      if (noiseShape == null) {
        return x.shape.slice();
      }
      if (arraysEqual(x.shape, noiseShape)) {
        return noiseShape;
      }
      if (x.shape.length === noiseShape.length) {
        var newDimension = [];
        for (var i = 0; i < x.shape.length; i++) {
          if (noiseShape[i] == null && x.shape[i] != null) {
            newDimension.push(x.shape[i]);
          } else {
            newDimension.push(noiseShape[i]);
          }
        }
        return newDimension;
      }
      return noiseShape;
    }
    function dropout_(x, rate, noiseShape, seed) {
      var $x = convertToTensor(x, "x", "dropout");
      assert($x.dtype === "float32", function() {
        return "x has to be a floating point tensor since it's going to be " + "scaled, but got a ".concat($x.dtype, " tensor instead.");
      });
      assert(rate >= 0 && rate < 1, function() {
        return "rate must be a float in the range [0, 1), but got ".concat(rate, ".");
      });
      if (rate === 0) {
        return x instanceof Tensor ? $x.clone() : $x;
      }
      var $noiseShape = getNoiseShape($x, noiseShape);
      var keepProb = 1 - rate;
      var multiplier = div(floor(add(randomUniform($noiseShape, 0, 1, "float32", seed), keepProb)), keepProb);
      return mul($x, multiplier);
    }
    var dropout = /* @__PURE__ */ op({ dropout_ });
    function enclosingPowerOfTwo(value) {
      return Math.floor(Math.pow(2, Math.ceil(Math.log(value) / Math.log(2))));
    }
    function cosineWindow(windowLength, a, b) {
      var even = 1 - windowLength % 2;
      var newValues = new Float32Array(windowLength);
      for (var i = 0; i < windowLength; ++i) {
        var cosArg = 2 * Math.PI * i / (windowLength + even - 1);
        newValues[i] = a - b * Math.cos(cosArg);
      }
      return tensor1d(newValues, "float32");
    }
    function inTopKAsync_(predictions, targets, k) {
      if (k === void 0) {
        k = 1;
      }
      return __awaiter(this, void 0, void 0, function() {
        var $predictions, $targets, lastDim, predictionsVals, targetsVals, _a, batch, size, precision, b, offset, vals, valAndInd, i, i;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              $predictions = convertToTensor(predictions, "predictions", "inTopK");
              $targets = convertToTensor(targets, "targets", "inTopK");
              assert($predictions.rank > 1, function() {
                return "inTopK() expects the predictions to be of rank 2 or higher, " + "but got ".concat($predictions.rank);
              });
              assert($predictions.rank - 1 === $targets.rank, function() {
                return "predictions rank should be 1 larger than targets rank, but got predictions rank " + "".concat($predictions.rank, " and targets rank ").concat($targets.rank);
              });
              assertShapesMatch($predictions.shape.slice(0, $predictions.shape.length - 1), $targets.shape, "predictions's shape should be align with the targets' shape, except the last dimension.");
              lastDim = $predictions.shape[$predictions.shape.length - 1];
              assert(k > 0 && k <= lastDim, function() {
                return "'k' passed to inTopK() must be > 0 && <= the predictions last " + "dimension (".concat(lastDim, "), but got ").concat(k);
              });
              return [4, $predictions.data()];
            case 1:
              predictionsVals = _b.sent();
              return [4, $targets.data()];
            case 2:
              targetsVals = _b.sent();
              _a = __read([predictionsVals.length / lastDim, lastDim], 2), batch = _a[0], size = _a[1];
              precision = getTypedArrayFromDType("bool", batch);
              for (b = 0; b < batch; b++) {
                offset = b * size;
                vals = predictionsVals.subarray(offset, offset + size);
                valAndInd = [];
                for (i = 0; i < vals.length; i++) {
                  valAndInd.push({ value: vals[i], index: i });
                }
                valAndInd.sort(function(a, b2) {
                  return b2.value - a.value;
                });
                precision[b] = 0;
                for (i = 0; i < k; i++) {
                  if (valAndInd[i].index === targetsVals[b]) {
                    precision[b] = 1;
                    break;
                  }
                }
              }
              if (predictions !== $predictions) {
                $predictions.dispose();
              }
              if (targets !== $targets) {
                $targets.dispose();
              }
              return [2, tensor(precision, $targets.shape, "bool")];
          }
        });
      });
    }
    var inTopKAsync = inTopKAsync_;
    function conv2DBackpropFilter_(x, dy, filterShape, strides, pad2, dataFormat, dimRoundingMode) {
      if (dataFormat === void 0) {
        dataFormat = "NHWC";
      }
      var x4D = x;
      if (x.rank === 3) {
        x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
      }
      var dy4D = dy;
      if (dy4D.rank === 3) {
        dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
      }
      assert(x4D.rank === 4, function() {
        return "Error in conv2dDerFilter: input must be rank 4, but got shape " + "".concat(x4D.shape, ".");
      });
      assert(dy4D.rank === 4, function() {
        return "Error in conv2dDerFilter: dy must be rank 4, but got shape " + "".concat(dy4D.shape, ".");
      });
      assert(filterShape.length === 4, function() {
        return "Error in conv2dDerFilter: filterShape must be length 4, but got " + "".concat(filterShape, ".");
      });
      var inDepth = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
      var outDepth = dataFormat === "NHWC" ? dy4D.shape[3] : dy4D.shape[1];
      assert(inDepth === filterShape[2], function() {
        return "Error in conv2dDerFilter: depth of input ".concat(inDepth, ") must ") + "match input depth in filter (".concat(filterShape[2], ".");
      });
      assert(outDepth === filterShape[3], function() {
        return "Error in conv2dDerFilter: depth of dy (".concat(outDepth, ") must ") + "match output depth for filter (".concat(filterShape[3], ").");
      });
      checkPadOnDimRoundingMode("conv2dDerFilter", pad2, dimRoundingMode);
      var inputs = { x: x4D, dy: dy4D };
      var attrs = { strides, pad: pad2, dataFormat, dimRoundingMode, filterShape };
      return ENGINE.runKernel(Conv2DBackpropFilter, inputs, attrs);
    }
    var conv2DBackpropFilter = /* @__PURE__ */ op({ conv2DBackpropFilter_ });
    function getFusedDyActivation(dy, y, activation) {
      if (activation == null || activation === "linear") {
        return dy;
      }
      if (activation === "relu") {
        return mul(dy, step(y));
      }
      throw new Error("Cannot compute gradient for fused activation ".concat(activation, "."));
    }
    function getFusedBiasGradient(bias, dyActivation) {
      var res = dyActivation;
      var reduceAxes = getReductionAxes(bias.shape, dyActivation.shape);
      if (reduceAxes.length > 0) {
        res = sum(res, reduceAxes);
      }
      return reshape(res, bias.shape);
    }
    function applyActivation(x, activation, preluActivationWeights, leakyreluAlpha) {
      if (activation === "linear") {
        return x;
      } else if (activation === "relu") {
        return relu(x);
      } else if (activation === "elu") {
        return elu(x);
      } else if (activation === "relu6") {
        return relu6(x);
      } else if (activation === "prelu") {
        return prelu(x, preluActivationWeights);
      } else if (activation === "leakyrelu") {
        return leakyRelu(x, leakyreluAlpha);
      } else if (activation === "sigmoid") {
        return sigmoid(x);
      }
      throw new Error("Unknown fused activation ".concat(activation, "."));
    }
    var shouldFuse = function(gradientDepth, activation) {
      var gradientMode = gradientDepth > 0;
      return !gradientMode || activation === "linear";
    };
    function fusedConv2d_(_a) {
      var _b;
      var x = _a.x, filter = _a.filter, strides = _a.strides, pad2 = _a.pad, _c = _a.dataFormat, dataFormat = _c === void 0 ? "NHWC" : _c, _d = _a.dilations, dilations = _d === void 0 ? [1, 1] : _d, dimRoundingMode = _a.dimRoundingMode, bias = _a.bias, _e = _a.activation, activation = _e === void 0 ? "linear" : _e, preluActivationWeights = _a.preluActivationWeights, leakyreluAlpha = _a.leakyreluAlpha;
      activation = activation || "linear";
      if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {
        assert(dataFormat === "NHWC", function() {
          return "Error in fused conv2d: got dataFormat of ".concat(dataFormat, " but ") + "only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.";
        });
        var result = conv2d$1(x, filter, strides, pad2, dataFormat, dilations, dimRoundingMode);
        if (bias != null) {
          result = add(result, bias);
        }
        return applyActivation(result, activation, preluActivationWeights, leakyreluAlpha);
      }
      var $x = convertToTensor(x, "x", "conv2d", "float32");
      var $filter = convertToTensor(filter, "filter", "conv2d", "float32");
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, function() {
        return "Error in fused conv2d: input must be rank 4, but got rank " + "".concat(x4D.rank, ".");
      });
      assert($filter.rank === 4, function() {
        return "Error in fused conv2d: filter must be rank 4, but got rank " + "".concat($filter.rank, ".");
      });
      checkPadOnDimRoundingMode("fused conv2d", pad2, dimRoundingMode);
      var inputChannels = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
      assert($filter.shape[2] === inputChannels, function() {
        return "Error in conv2d: depth of input (".concat(inputChannels, ") must match ") + "input depth for filter ".concat($filter.shape[2], ".");
      });
      assert(eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in conv2D: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      var convInfo = computeConv2DInfo(x4D.shape, $filter.shape, strides, dilations, pad2, dimRoundingMode);
      var $bias;
      if (bias != null) {
        $bias = convertToTensor(bias, "bias", "fused conv2d");
        _b = __read(makeTypesMatch($bias, $x), 1), $bias = _b[0];
        if (dataFormat === "NHWC") {
          assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);
        } else {
          assert($bias.shape.length <= 1, function() {
            return "Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of " + "rank-".concat($bias.shape.length, ".");
          });
          assert($bias.shape.length === 0 || $bias.shape[0] === convInfo.outChannels || $bias.shape[0] === 1, function() {
            return "Error in fused conv2d: bias shape (".concat($bias.shape, ") is not ") + "compatible with the number of output channels " + "(".concat(convInfo.outChannels, ")");
          });
        }
      }
      var $preluActivationWeights;
      if (preluActivationWeights != null) {
        var alphaShape_1 = preluActivationWeights.shape;
        assert(alphaShape_1.length <= 1 || alphaShape_1.length === 3, function() {
          return "Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of " + "rank-".concat(alphaShape_1.length, ".");
        });
        if (alphaShape_1.length === 1) {
          assert(alphaShape_1[0] === 1 || alphaShape_1[0] === convInfo.outChannels, function() {
            return "Error in fused conv2d: PReLU activation weights " + "(".concat(alphaShape_1, ") is not compatible with the number of output ") + "channels (".concat(convInfo.outChannels, ").");
          });
        } else if (alphaShape_1.length === 3) {
          try {
            assertAndGetBroadcastShape(alphaShape_1, convInfo.outShape);
          } catch (e) {
            var errMsg = "Error in fused conv2d: PReLU activation weights (".concat(alphaShape_1, ") ") + "is not compatible with the output shape of the conv2d " + "(".concat(convInfo.outShape, ").");
            throw Error(errMsg);
          }
        }
        $preluActivationWeights = convertToTensor(preluActivationWeights, "prelu weights", "fused conv2d");
      }
      var grad = function(dy, saved) {
        assert(dataFormat === "NHWC", function() {
          return "Error in gradient of fused conv2D: got dataFormat of ".concat(dataFormat, " but only NHWC is currently supported.");
        });
        var _a2 = __read(saved, 4), $filter2 = _a2[0], x4D2 = _a2[1], y = _a2[2], $bias2 = _a2[3];
        var dyActivation = getFusedDyActivation(dy, y, activation);
        assert(tupleValuesAreOne(dilations), function() {
          return "Error in gradient of fused conv2D: dilation rates greater than 1 " + "are not yet supported in gradients. Got dilations '".concat(dilations, "'");
        });
        var xDer = conv2DBackpropInput(x4D2.shape, dyActivation, $filter2, strides, pad2);
        var filterDer = conv2DBackpropFilter(x4D2, dyActivation, $filter2.shape, strides, pad2);
        var der = [xDer, filterDer];
        if ($bias2 != null) {
          var biasDer = getFusedBiasGradient($bias2, dyActivation);
          der.push(biasDer);
        }
        return der;
      };
      var inputs = {
        x: x4D,
        filter: $filter,
        bias: $bias,
        preluActivationWeights: $preluActivationWeights
      };
      var attrs = {
        strides,
        pad: pad2,
        dataFormat,
        dilations,
        dimRoundingMode,
        activation,
        leakyreluAlpha
      };
      if (bias == null) {
        var customOp = customGrad(function(x4D2, filter2, save) {
          var res = (
            // tslint:disable-next-line: no-unnecessary-type-assertion
            ENGINE.runKernel(FusedConv2D, inputs, attrs)
          );
          save([filter2, x4D2, res]);
          if (reshapedTo4D) {
            res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
          }
          return { value: res, gradFunc: grad };
        });
        return customOp(x4D, $filter);
      } else {
        var customOpWithBias = customGrad(function(x4D2, filter2, bias2, save) {
          var res = ENGINE.runKernel(FusedConv2D, inputs, attrs);
          save([filter2, x4D2, res, bias2]);
          if (reshapedTo4D) {
            res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
          }
          return { value: res, gradFunc: grad };
        });
        return customOpWithBias(x4D, $filter, $bias);
      }
    }
    var conv2d = /* @__PURE__ */ op({ fusedConv2d_ });
    function depthwiseConv2dNativeBackpropFilter_(x, dy, filterShape, strides, pad2, dilations, dimRoundingMode) {
      if (dilations === void 0) {
        dilations = [1, 1];
      }
      var x4D = x;
      if (x.rank === 3) {
        x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
      }
      var dy4D = dy;
      if (dy4D.rank === 3) {
        dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
      }
      var inputs = { x: x4D, dy: dy4D };
      var attrs = { strides, pad: pad2, dimRoundingMode, dilations, filterShape };
      return ENGINE.runKernel(DepthwiseConv2dNativeBackpropFilter, inputs, attrs);
    }
    var depthwiseConv2dNativeBackpropFilter = op({ depthwiseConv2dNativeBackpropFilter_ });
    function depthwiseConv2dNativeBackpropInput_(xShape, dy, filter, strides, pad2, dilations, dimRoundingMode) {
      if (dilations === void 0) {
        dilations = [1, 1];
      }
      var dy4D = dy;
      var reshapedTo4D = false;
      if (dy.rank === 3) {
        reshapedTo4D = true;
        dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
      }
      var inputs = { dy: dy4D, filter };
      var attrs = { strides, pad: pad2, dimRoundingMode, dilations, inputShape: xShape };
      var res = (
        // tslint:disable-next-line: no-unnecessary-type-assertion
        ENGINE.runKernel(DepthwiseConv2dNativeBackpropInput, inputs, attrs)
      );
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var depthwiseConv2dNativeBackpropInput = op({ depthwiseConv2dNativeBackpropInput_ });
    function fusedDepthwiseConv2d_(_a) {
      var _b;
      var x = _a.x, filter = _a.filter, strides = _a.strides, pad2 = _a.pad, _c = _a.dataFormat, dataFormat = _c === void 0 ? "NHWC" : _c, _d = _a.dilations, dilations = _d === void 0 ? [1, 1] : _d, dimRoundingMode = _a.dimRoundingMode, bias = _a.bias, _e = _a.activation, activation = _e === void 0 ? "linear" : _e, preluActivationWeights = _a.preluActivationWeights, leakyreluAlpha = _a.leakyreluAlpha;
      if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {
        var result = depthwiseConv2d$1(x, filter, strides, pad2, dataFormat, dilations, dimRoundingMode);
        if (bias != null) {
          result = add(result, bias);
        }
        return applyActivation(result, activation, preluActivationWeights, leakyreluAlpha);
      }
      var $x = convertToTensor(x, "x", "depthwiseConv2d", "float32");
      var $filter = convertToTensor(filter, "filter", "depthwiseConv2d", "float32");
      var x4D = $x;
      var reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, function() {
        return "Error in fused depthwiseConv2d: input must be rank 4, but got " + "rank ".concat(x4D.rank, ".");
      });
      assert($filter.rank === 4, function() {
        return "Error in fused depthwiseConv2d: filter must be rank 4, " + "but got rank ".concat($filter.rank, ".");
      });
      assert(x4D.shape[3] === $filter.shape[2], function() {
        return "Error in fused depthwiseConv2d: number of input channels " + "(".concat(x4D.shape[3], ") must match the inChannels dimension in ") + "filter ".concat($filter.shape[2], ".");
      });
      if (dilations == null) {
        dilations = [1, 1];
      }
      assert(eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in fused depthwiseConv2d: Either strides or dilations must " + "be 1. Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      checkPadOnDimRoundingMode("fused depthwiseConv2d", pad2, dimRoundingMode);
      var convInfo = computeConv2DInfo(
        x4D.shape,
        $filter.shape,
        strides,
        dilations,
        pad2,
        dimRoundingMode,
        true
        /* depthwise */
      );
      var $bias;
      if (bias != null) {
        $bias = convertToTensor(bias, "bias", "fused conv2d");
        _b = __read(makeTypesMatch($bias, $x), 1), $bias = _b[0];
        assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);
      }
      var $preluActivationWeights;
      if (preluActivationWeights != null) {
        $preluActivationWeights = convertToTensor(preluActivationWeights, "prelu weights", "fused depthwiseConv2d");
      }
      var grad = function(dy, saved) {
        assert(tupleValuesAreOne(dilations), function() {
          return "Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations " + "'".concat(dilations, "'");
        });
        var _a2 = __read(saved, 4), $filter2 = _a2[0], x4D2 = _a2[1], y = _a2[2], bias2 = _a2[3];
        var dyActivation = getFusedDyActivation(dy, y, activation);
        var xDer = depthwiseConv2dNativeBackpropInput(x4D2.shape, dyActivation, $filter2, strides, pad2, dilations, dimRoundingMode);
        var filterDer = depthwiseConv2dNativeBackpropFilter(x4D2, dyActivation, $filter2.shape, strides, pad2, dilations, dimRoundingMode);
        if (bias2 != null) {
          var biasDer = getFusedBiasGradient($bias, dyActivation);
          return [xDer, filterDer, biasDer];
        }
        return [xDer, filterDer];
      };
      var inputs = {
        x: x4D,
        filter: $filter,
        bias: $bias,
        preluActivationWeights: $preluActivationWeights
      };
      var attrs = {
        strides,
        pad: pad2,
        dataFormat,
        dilations,
        dimRoundingMode,
        activation,
        leakyreluAlpha
      };
      if (bias == null) {
        var customOp = customGrad(function(x4D2, filter2, save) {
          var res = ENGINE.runKernel(FusedDepthwiseConv2D, inputs, attrs);
          save([filter2, x4D2, res]);
          if (reshapedTo4D) {
            res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
          }
          return { value: res, gradFunc: grad };
        });
        return customOp(x4D, $filter);
      } else {
        var customOpWithBias = customGrad(function(x4D2, filter2, bias2, save) {
          var res = ENGINE.runKernel(FusedDepthwiseConv2D, inputs, attrs);
          save([filter2, x4D2, res, bias2]);
          if (reshapedTo4D) {
            res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
          }
          return { value: res, gradFunc: grad };
        });
        return customOpWithBias(x4D, $filter, $bias);
      }
    }
    var depthwiseConv2d = /* @__PURE__ */ op({ fusedDepthwiseConv2d_ });
    function fusedMatMul_(_a) {
      var _b, _c;
      var a = _a.a, b = _a.b, _d = _a.transposeA, transposeA = _d === void 0 ? false : _d, _e = _a.transposeB, transposeB = _e === void 0 ? false : _e, bias = _a.bias, _f = _a.activation, activation = _f === void 0 ? "linear" : _f, preluActivationWeights = _a.preluActivationWeights, _g = _a.leakyreluAlpha, leakyreluAlpha = _g === void 0 ? 0.2 : _g;
      if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {
        var result = matMul$1(a, b, transposeA, transposeB);
        if (bias != null) {
          result = add(result, bias);
        }
        return applyActivation(result, activation, preluActivationWeights, leakyreluAlpha);
      }
      var $a = convertToTensor(a, "a", "fused matMul");
      var $b = convertToTensor(b, "b", "fused matMul");
      _b = __read(makeTypesMatch($a, $b), 2), $a = _b[0], $b = _b[1];
      var innerShapeA = transposeA ? $a.shape[$a.rank - 2] : $a.shape[$a.rank - 1];
      var innerShapeB = transposeB ? $b.shape[$b.rank - 1] : $b.shape[$b.rank - 2];
      var outerShapeA = transposeA ? $a.shape[$a.rank - 1] : $a.shape[$a.rank - 2];
      var outerShapeB = transposeB ? $b.shape[$b.rank - 2] : $b.shape[$b.rank - 1];
      var outerDimsA = $a.shape.slice(0, -2);
      var outerDimsB = $b.shape.slice(0, -2);
      var batchDimA = sizeFromShape(outerDimsA);
      var batchDimB = sizeFromShape(outerDimsB);
      assert(innerShapeA === innerShapeB, function() {
        return "Error in fused matMul: inner shapes (".concat(innerShapeA, ") and (") + "".concat(innerShapeB, ") of Tensors with shapes ").concat($a.shape, " and ") + "".concat($b.shape, " and transposeA=").concat(transposeA) + " and transposeB=".concat(transposeB, " must match.");
      });
      var outShapeOuterDims = assertAndGetBroadcastShape($a.shape.slice(0, -2), $b.shape.slice(0, -2));
      var outShape = outShapeOuterDims.concat([outerShapeA, outerShapeB]);
      var a3D = transposeA ? reshape($a, [batchDimA, innerShapeA, outerShapeA]) : reshape($a, [batchDimA, outerShapeA, innerShapeA]);
      var b3D = transposeB ? reshape($b, [batchDimB, outerShapeB, innerShapeB]) : reshape($b, [batchDimB, innerShapeB, outerShapeB]);
      var $bias;
      if (bias != null) {
        $bias = convertToTensor(bias, "bias", "fused matMul");
        _c = __read(makeTypesMatch($bias, $a), 1), $bias = _c[0];
        assertAndGetBroadcastShape(outShape, $bias.shape);
      }
      var $preluActivationWeights;
      if (preluActivationWeights != null) {
        $preluActivationWeights = convertToTensor(preluActivationWeights, "prelu weights", "fused matMul");
      }
      var grad = function(dy, saved) {
        var _a2 = __read(saved, 4), a3D2 = _a2[0], b3D2 = _a2[1], y = _a2[2], $bias2 = _a2[3];
        var dyActivation = getFusedDyActivation(reshape(dy, y.shape), y, activation);
        var aDer;
        var bDer;
        if (!transposeA && !transposeB) {
          aDer = matMul$1(dyActivation, b3D2, false, true);
          bDer = matMul$1(a3D2, dyActivation, true, false);
        } else if (!transposeA && transposeB) {
          aDer = matMul$1(dyActivation, b3D2, false, false);
          bDer = matMul$1(dyActivation, a3D2, true, false);
        } else if (transposeA && !transposeB) {
          aDer = matMul$1(b3D2, dyActivation, false, true);
          bDer = matMul$1(a3D2, dyActivation, false, false);
        } else {
          aDer = matMul$1(b3D2, dyActivation, true, true);
          bDer = matMul$1(dyActivation, a3D2, true, true);
        }
        if (bias != null) {
          var biasDer = getFusedBiasGradient($bias2, dyActivation);
          return [aDer, bDer, biasDer];
        } else {
          return [aDer, bDer];
        }
      };
      var inputs = {
        a: a3D,
        b: b3D,
        bias: $bias,
        preluActivationWeights: $preluActivationWeights
      };
      var attrs = { transposeA, transposeB, activation, leakyreluAlpha };
      if (bias == null) {
        var customOp = customGrad(function(a3D2, b3D2, save) {
          var res = (
            // tslint:disable-next-line: no-unnecessary-type-assertion
            ENGINE.runKernel(_FusedMatMul, inputs, attrs)
          );
          save([a3D2, b3D2, res]);
          return { value: reshape(res, outShape), gradFunc: grad };
        });
        return customOp(a3D, b3D);
      } else {
        var customOpWithBias = customGrad(function(a3D2, b3D2, $bias2, save) {
          var res = (
            // tslint:disable-next-line: no-unnecessary-type-assertion
            ENGINE.runKernel(_FusedMatMul, inputs, attrs)
          );
          save([a3D2, b3D2, res, $bias2]);
          return { value: reshape(res, outShape), gradFunc: grad };
        });
        return customOpWithBias(a3D, b3D, $bias);
      }
    }
    var matMul = /* @__PURE__ */ op({ fusedMatMul_ });
    var fused_ops = {
      __proto__: null,
      conv2d,
      depthwiseConv2d,
      matMul
    };
    function hammingWindow_(windowLength) {
      return cosineWindow(windowLength, 0.54, 0.46);
    }
    var hammingWindow = /* @__PURE__ */ op({ hammingWindow_ });
    function hannWindow_(windowLength) {
      return cosineWindow(windowLength, 0.5, 0.5);
    }
    var hannWindow = /* @__PURE__ */ op({ hannWindow_ });
    function frame_(signal2, frameLength, frameStep, padEnd, padValue) {
      if (padEnd === void 0) {
        padEnd = false;
      }
      if (padValue === void 0) {
        padValue = 0;
      }
      var start = 0;
      var output = [];
      while (start + frameLength <= signal2.size) {
        output.push(slice(signal2, start, frameLength));
        start += frameStep;
      }
      if (padEnd) {
        while (start < signal2.size) {
          var padLen = start + frameLength - signal2.size;
          var pad2 = concat([
            slice(signal2, start, frameLength - padLen),
            fill([padLen], padValue)
          ]);
          output.push(pad2);
          start += frameStep;
        }
      }
      if (output.length === 0) {
        return tensor2d([], [0, frameLength]);
      }
      return reshape(concat(output), [output.length, frameLength]);
    }
    var frame = /* @__PURE__ */ op({ frame_ });
    function stft_(signal2, frameLength, frameStep, fftLength, windowFn) {
      if (windowFn === void 0) {
        windowFn = hannWindow;
      }
      if (fftLength == null) {
        fftLength = enclosingPowerOfTwo(frameLength);
      }
      var framedSignal = frame(signal2, frameLength, frameStep);
      var windowedSignal = mul(framedSignal, windowFn(frameLength));
      return rfft(windowedSignal, fftLength);
    }
    var stft = /* @__PURE__ */ op({ stft_ });
    function cropAndResize_(image2, boxes, boxInd, cropSize, method, extrapolationValue) {
      if (method === void 0) {
        method = "bilinear";
      }
      if (extrapolationValue === void 0) {
        extrapolationValue = 0;
      }
      var $image = convertToTensor(image2, "image", "cropAndResize");
      var $boxes = convertToTensor(boxes, "boxes", "cropAndResize", "float32");
      var $boxInd = convertToTensor(boxInd, "boxInd", "cropAndResize", "int32");
      var numBoxes = $boxes.shape[0];
      assert($image.rank === 4, function() {
        return "Error in cropAndResize: image must be rank 4," + "but got rank ".concat($image.rank, ".");
      });
      assert($boxes.rank === 2 && $boxes.shape[1] === 4, function() {
        return "Error in cropAndResize: boxes must be have size [".concat(numBoxes, ",4] ") + "but had shape ".concat($boxes.shape, ".");
      });
      assert($boxInd.rank === 1 && $boxInd.shape[0] === numBoxes, function() {
        return "Error in cropAndResize: boxInd must be have size [".concat(numBoxes, "] ") + "but had shape ".concat($boxes.shape, ".");
      });
      assert(cropSize.length === 2, function() {
        return "Error in cropAndResize: cropSize must be of length 2, but got " + "length ".concat(cropSize.length, ".");
      });
      assert(cropSize[0] >= 1 && cropSize[1] >= 1, function() {
        return "cropSize must be atleast [1,1], but was ".concat(cropSize);
      });
      assert(method === "bilinear" || method === "nearest", function() {
        return "method must be bilinear or nearest, but was ".concat(method);
      });
      var inputs = { image: $image, boxes: $boxes, boxInd: $boxInd };
      var attrs = { method, extrapolationValue, cropSize };
      var res = ENGINE.runKernel(CropAndResize, inputs, attrs);
      return res;
    }
    var cropAndResize = /* @__PURE__ */ op({ cropAndResize_ });
    function flipLeftRight_(image2) {
      var $image = convertToTensor(image2, "image", "flipLeftRight", "float32");
      assert($image.rank === 4, function() {
        return "Error in flipLeftRight: image must be rank 4," + "but got rank ".concat($image.rank, ".");
      });
      var inputs = { image: $image };
      var res = ENGINE.runKernel(FlipLeftRight, inputs, {});
      return res;
    }
    var flipLeftRight = /* @__PURE__ */ op({ flipLeftRight_ });
    function grayscaleToRGB_(image2) {
      var $image = convertToTensor(image2, "image", "grayscaleToRGB");
      var lastDimsIdx = $image.rank - 1;
      var lastDims = $image.shape[lastDimsIdx];
      assert($image.rank >= 2, function() {
        return "Error in grayscaleToRGB: images must be at least rank 2, " + "but got rank ".concat($image.rank, ".");
      });
      assert(lastDims === 1, function() {
        return "Error in grayscaleToRGB: last dimension of a grayscale image " + "should be size 1, but got size ".concat(lastDims, ".");
      });
      var reps = new Array($image.rank);
      reps.fill(1, 0, lastDimsIdx);
      reps[lastDimsIdx] = 3;
      return tile($image, reps);
    }
    var grayscaleToRGB = /* @__PURE__ */ op({ grayscaleToRGB_ });
    function rgbToGrayscale_(image2) {
      var $image = convertToTensor(image2, "image", "RGBToGrayscale");
      var lastDimsIdx = $image.rank - 1;
      var lastDims = $image.shape[lastDimsIdx];
      assert($image.rank >= 2, function() {
        return "Error in RGBToGrayscale: images must be at least rank 2, " + "but got rank ".concat($image.rank, ".");
      });
      assert(lastDims === 3, function() {
        return "Error in RGBToGrayscale: last dimension of an RGB image " + "should be size 3, but got size ".concat(lastDims, ".");
      });
      var origDtype = $image.dtype;
      var fltImage = cast($image, "float32");
      var rgbWeights = tensor1d([0.2989, 0.587, 0.114]);
      var grayFloat;
      switch ($image.rank) {
        case 2:
          grayFloat = einsum("ij,j->i", fltImage, rgbWeights);
          break;
        case 3:
          grayFloat = einsum("ijk,k->ij", fltImage, rgbWeights);
          break;
        case 4:
          grayFloat = einsum("ijkl,l->ijk", fltImage, rgbWeights);
          break;
        case 5:
          grayFloat = einsum("ijklm,m->ijkl", fltImage, rgbWeights);
          break;
        case 6:
          grayFloat = einsum("ijklmn,n->ijklm", fltImage, rgbWeights);
          break;
        default:
          throw new Error("Not a valid tensor rank.");
      }
      grayFloat = expandDims(grayFloat, -1);
      return cast(grayFloat, origDtype);
    }
    var rgbToGrayscale = /* @__PURE__ */ op({ rgbToGrayscale_ });
    function rotateWithOffset_(image2, radians, fillValue, center) {
      if (fillValue === void 0) {
        fillValue = 0;
      }
      if (center === void 0) {
        center = 0.5;
      }
      var $image = convertToTensor(image2, "image", "rotateWithOffset", "float32");
      assert($image.rank === 4, function() {
        return "Error in rotateWithOffset: image must be rank 4," + "but got rank ".concat($image.rank, ".");
      });
      var inputs = { image: $image };
      var attrs = { radians, fillValue, center };
      var res = ENGINE.runKernel(RotateWithOffset, inputs, attrs);
      return res;
    }
    var rotateWithOffset = /* @__PURE__ */ op({ rotateWithOffset_ });
    function nonMaxSuppSanityCheck(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
      if (iouThreshold == null) {
        iouThreshold = 0.5;
      }
      if (scoreThreshold == null) {
        scoreThreshold = Number.NEGATIVE_INFINITY;
      }
      if (softNmsSigma == null) {
        softNmsSigma = 0;
      }
      var numBoxes = boxes.shape[0];
      maxOutputSize = Math.min(maxOutputSize, numBoxes);
      assert(0 <= iouThreshold && iouThreshold <= 1, function() {
        return "iouThreshold must be in [0, 1], but was '".concat(iouThreshold, "'");
      });
      assert(boxes.rank === 2, function() {
        return "boxes must be a 2D tensor, but was of rank '".concat(boxes.rank, "'");
      });
      assert(boxes.shape[1] === 4, function() {
        return "boxes must have 4 columns, but 2nd dimension was ".concat(boxes.shape[1]);
      });
      assert(scores.rank === 1, function() {
        return "scores must be a 1D tensor";
      });
      assert(scores.shape[0] === numBoxes, function() {
        return "scores has incompatible shape with boxes. Expected ".concat(numBoxes, ", ") + "but was ".concat(scores.shape[0]);
      });
      assert(0 <= softNmsSigma && softNmsSigma <= 1, function() {
        return "softNmsSigma must be in [0, 1], but was '".concat(softNmsSigma, "'");
      });
      return { maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma };
    }
    function nonMaxSuppression_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) {
      if (iouThreshold === void 0) {
        iouThreshold = 0.5;
      }
      if (scoreThreshold === void 0) {
        scoreThreshold = Number.NEGATIVE_INFINITY;
      }
      var $boxes = convertToTensor(boxes, "boxes", "nonMaxSuppression", "float32");
      var $scores = convertToTensor(scores, "scores", "nonMaxSuppression", "float32");
      var inputs = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);
      maxOutputSize = inputs.maxOutputSize;
      iouThreshold = inputs.iouThreshold;
      scoreThreshold = inputs.scoreThreshold;
      var attrs = { maxOutputSize, iouThreshold, scoreThreshold };
      return ENGINE.runKernel(NonMaxSuppressionV3, { boxes: $boxes, scores: $scores }, attrs);
    }
    var nonMaxSuppression = /* @__PURE__ */ op({ nonMaxSuppression_ });
    function binaryInsert(arr, element, comparator) {
      var index = binarySearch(arr, element, comparator);
      var insertionPoint = index < 0 ? -(index + 1) : index;
      arr.splice(insertionPoint, 0, element);
    }
    function binarySearch(arr, target, comparator) {
      return binarySearch_(arr, target, comparator || defaultComparator);
    }
    function defaultComparator(a, b) {
      return a > b ? 1 : a < b ? -1 : 0;
    }
    function binarySearch_(arr, target, comparator) {
      var left = 0;
      var right = arr.length;
      var middle = 0;
      var found = false;
      while (left < right) {
        middle = left + (right - left >>> 1);
        var compareResult = comparator(target, arr[middle]);
        if (compareResult > 0) {
          left = middle + 1;
        } else {
          right = middle;
          found = !compareResult;
        }
      }
      return found ? left : -left - 1;
    }
    function nonMaxSuppressionV3Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) {
      return nonMaxSuppressionImpl_(
        boxes,
        scores,
        maxOutputSize,
        iouThreshold,
        scoreThreshold,
        0
        /* softNmsSigma */
      );
    }
    function nonMaxSuppressionV4Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize) {
      return nonMaxSuppressionImpl_(
        boxes,
        scores,
        maxOutputSize,
        iouThreshold,
        scoreThreshold,
        0,
        false,
        padToMaxOutputSize,
        true
        /* returnValidOutputs */
      );
    }
    function nonMaxSuppressionV5Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
      return nonMaxSuppressionImpl_(
        boxes,
        scores,
        maxOutputSize,
        iouThreshold,
        scoreThreshold,
        softNmsSigma,
        true
        /* returnScoresTensor */
      );
    }
    function nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma, returnScoresTensor, padToMaxOutputSize, returnValidOutputs) {
      if (returnScoresTensor === void 0) {
        returnScoresTensor = false;
      }
      if (padToMaxOutputSize === void 0) {
        padToMaxOutputSize = false;
      }
      if (returnValidOutputs === void 0) {
        returnValidOutputs = false;
      }
      var candidates = [];
      for (var i = 0; i < scores.length; i++) {
        if (scores[i] > scoreThreshold) {
          candidates.push({ score: scores[i], boxIndex: i, suppressBeginIndex: 0 });
        }
      }
      candidates.sort(ascendingComparator);
      var scale = softNmsSigma > 0 ? -0.5 / softNmsSigma : 0;
      var selectedIndices = [];
      var selectedScores = [];
      while (selectedIndices.length < maxOutputSize && candidates.length > 0) {
        var candidate = candidates.pop();
        var originalScore = candidate.score, boxIndex = candidate.boxIndex, suppressBeginIndex = candidate.suppressBeginIndex;
        if (originalScore < scoreThreshold) {
          break;
        }
        var ignoreCandidate = false;
        for (var j = selectedIndices.length - 1; j >= suppressBeginIndex; --j) {
          var iou = intersectionOverUnion(boxes, boxIndex, selectedIndices[j]);
          if (iou >= iouThreshold) {
            ignoreCandidate = true;
            break;
          }
          candidate.score = candidate.score * suppressWeight(iouThreshold, scale, iou);
          if (candidate.score <= scoreThreshold) {
            break;
          }
        }
        candidate.suppressBeginIndex = selectedIndices.length;
        if (!ignoreCandidate) {
          if (candidate.score === originalScore) {
            selectedIndices.push(boxIndex);
            selectedScores.push(candidate.score);
          } else if (candidate.score > scoreThreshold) {
            binaryInsert(candidates, candidate, ascendingComparator);
          }
        }
      }
      var validOutputs = selectedIndices.length;
      var elemsToPad = maxOutputSize - validOutputs;
      if (padToMaxOutputSize && elemsToPad > 0) {
        selectedIndices.push.apply(selectedIndices, __spreadArray([], __read(new Array(elemsToPad).fill(0)), false));
        selectedScores.push.apply(selectedScores, __spreadArray([], __read(new Array(elemsToPad).fill(0)), false));
      }
      var result = { selectedIndices };
      if (returnScoresTensor) {
        result["selectedScores"] = selectedScores;
      }
      if (returnValidOutputs) {
        result["validOutputs"] = validOutputs;
      }
      return result;
    }
    function intersectionOverUnion(boxes, i, j) {
      var iCoord = boxes.subarray(i * 4, i * 4 + 4);
      var jCoord = boxes.subarray(j * 4, j * 4 + 4);
      var yminI = Math.min(iCoord[0], iCoord[2]);
      var xminI = Math.min(iCoord[1], iCoord[3]);
      var ymaxI = Math.max(iCoord[0], iCoord[2]);
      var xmaxI = Math.max(iCoord[1], iCoord[3]);
      var yminJ = Math.min(jCoord[0], jCoord[2]);
      var xminJ = Math.min(jCoord[1], jCoord[3]);
      var ymaxJ = Math.max(jCoord[0], jCoord[2]);
      var xmaxJ = Math.max(jCoord[1], jCoord[3]);
      var areaI = (ymaxI - yminI) * (xmaxI - xminI);
      var areaJ = (ymaxJ - yminJ) * (xmaxJ - xminJ);
      if (areaI <= 0 || areaJ <= 0) {
        return 0;
      }
      var intersectionYmin = Math.max(yminI, yminJ);
      var intersectionXmin = Math.max(xminI, xminJ);
      var intersectionYmax = Math.min(ymaxI, ymaxJ);
      var intersectionXmax = Math.min(xmaxI, xmaxJ);
      var intersectionArea = Math.max(intersectionYmax - intersectionYmin, 0) * Math.max(intersectionXmax - intersectionXmin, 0);
      return intersectionArea / (areaI + areaJ - intersectionArea);
    }
    function suppressWeight(iouThreshold, scale, iou) {
      var weight = Math.exp(scale * iou * iou);
      return iou <= iouThreshold ? weight : 0;
    }
    function ascendingComparator(c1, c2) {
      return c1.score - c2.score || c1.score === c2.score && c2.boxIndex - c1.boxIndex;
    }
    function nonMaxSuppressionAsync_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) {
      if (iouThreshold === void 0) {
        iouThreshold = 0.5;
      }
      if (scoreThreshold === void 0) {
        scoreThreshold = Number.NEGATIVE_INFINITY;
      }
      return __awaiter(this, void 0, void 0, function() {
        var $boxes, $scores, inputs, boxesAndScores, boxesVals, scoresVals, selectedIndices;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              $boxes = convertToTensor(boxes, "boxes", "nonMaxSuppressionAsync");
              $scores = convertToTensor(scores, "scores", "nonMaxSuppressionAsync");
              inputs = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);
              maxOutputSize = inputs.maxOutputSize;
              iouThreshold = inputs.iouThreshold;
              scoreThreshold = inputs.scoreThreshold;
              return [4, Promise.all([$boxes.data(), $scores.data()])];
            case 1:
              boxesAndScores = _a.sent();
              boxesVals = boxesAndScores[0];
              scoresVals = boxesAndScores[1];
              selectedIndices = nonMaxSuppressionV3Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold).selectedIndices;
              if ($boxes !== boxes) {
                $boxes.dispose();
              }
              if ($scores !== scores) {
                $scores.dispose();
              }
              return [2, tensor1d(selectedIndices, "int32")];
          }
        });
      });
    }
    var nonMaxSuppressionAsync = nonMaxSuppressionAsync_;
    function nonMaxSuppressionWithScore_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
      if (iouThreshold === void 0) {
        iouThreshold = 0.5;
      }
      if (scoreThreshold === void 0) {
        scoreThreshold = Number.NEGATIVE_INFINITY;
      }
      if (softNmsSigma === void 0) {
        softNmsSigma = 0;
      }
      var $boxes = convertToTensor(boxes, "boxes", "nonMaxSuppression");
      var $scores = convertToTensor(scores, "scores", "nonMaxSuppression");
      var params = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
      maxOutputSize = params.maxOutputSize;
      iouThreshold = params.iouThreshold;
      scoreThreshold = params.scoreThreshold;
      softNmsSigma = params.softNmsSigma;
      var inputs = { boxes: $boxes, scores: $scores };
      var attrs = { maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma };
      var result = ENGINE.runKernel(NonMaxSuppressionV5, inputs, attrs);
      return { selectedIndices: result[0], selectedScores: result[1] };
    }
    var nonMaxSuppressionWithScore = /* @__PURE__ */ op({ nonMaxSuppressionWithScore_ });
    function nonMaxSuppressionWithScoreAsync_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
      if (iouThreshold === void 0) {
        iouThreshold = 0.5;
      }
      if (scoreThreshold === void 0) {
        scoreThreshold = Number.NEGATIVE_INFINITY;
      }
      if (softNmsSigma === void 0) {
        softNmsSigma = 0;
      }
      return __awaiter(this, void 0, void 0, function() {
        var $boxes, $scores, params, boxesAndScores, boxesVals, scoresVals, _a, selectedIndices, selectedScores;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              $boxes = convertToTensor(boxes, "boxes", "nonMaxSuppressionAsync");
              $scores = convertToTensor(scores, "scores", "nonMaxSuppressionAsync");
              params = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
              maxOutputSize = params.maxOutputSize;
              iouThreshold = params.iouThreshold;
              scoreThreshold = params.scoreThreshold;
              softNmsSigma = params.softNmsSigma;
              return [4, Promise.all([$boxes.data(), $scores.data()])];
            case 1:
              boxesAndScores = _b.sent();
              boxesVals = boxesAndScores[0];
              scoresVals = boxesAndScores[1];
              _a = nonMaxSuppressionV5Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma), selectedIndices = _a.selectedIndices, selectedScores = _a.selectedScores;
              if ($boxes !== boxes) {
                $boxes.dispose();
              }
              if ($scores !== scores) {
                $scores.dispose();
              }
              return [2, {
                selectedIndices: tensor1d(selectedIndices, "int32"),
                selectedScores: tensor1d(selectedScores)
              }];
          }
        });
      });
    }
    var nonMaxSuppressionWithScoreAsync = nonMaxSuppressionWithScoreAsync_;
    function nonMaxSuppressionPadded_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize) {
      if (iouThreshold === void 0) {
        iouThreshold = 0.5;
      }
      if (scoreThreshold === void 0) {
        scoreThreshold = Number.NEGATIVE_INFINITY;
      }
      if (padToMaxOutputSize === void 0) {
        padToMaxOutputSize = false;
      }
      var $boxes = convertToTensor(boxes, "boxes", "nonMaxSuppression");
      var $scores = convertToTensor(scores, "scores", "nonMaxSuppression");
      var params = nonMaxSuppSanityCheck(
        $boxes,
        $scores,
        maxOutputSize,
        iouThreshold,
        scoreThreshold,
        null
        /* softNmsSigma */
      );
      var $maxOutputSize = params.maxOutputSize;
      var $iouThreshold = params.iouThreshold;
      var $scoreThreshold = params.scoreThreshold;
      var inputs = { boxes: $boxes, scores: $scores };
      var attrs = {
        maxOutputSize: $maxOutputSize,
        iouThreshold: $iouThreshold,
        scoreThreshold: $scoreThreshold,
        padToMaxOutputSize
      };
      var result = ENGINE.runKernel(NonMaxSuppressionV4, inputs, attrs);
      return { selectedIndices: result[0], validOutputs: result[1] };
    }
    var nonMaxSuppressionPadded = /* @__PURE__ */ op({ nonMaxSuppressionPadded_ });
    function nonMaxSuppressionPaddedAsync_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize) {
      if (iouThreshold === void 0) {
        iouThreshold = 0.5;
      }
      if (scoreThreshold === void 0) {
        scoreThreshold = Number.NEGATIVE_INFINITY;
      }
      if (padToMaxOutputSize === void 0) {
        padToMaxOutputSize = false;
      }
      return __awaiter(this, void 0, void 0, function() {
        var $boxes, $scores, params, $maxOutputSize, $iouThreshold, $scoreThreshold, _a, boxesVals, scoresVals, _b, selectedIndices, validOutputs;
        return __generator(this, function(_c) {
          switch (_c.label) {
            case 0:
              $boxes = convertToTensor(boxes, "boxes", "nonMaxSuppressionAsync");
              $scores = convertToTensor(scores, "scores", "nonMaxSuppressionAsync");
              params = nonMaxSuppSanityCheck(
                $boxes,
                $scores,
                maxOutputSize,
                iouThreshold,
                scoreThreshold,
                null
                /* softNmsSigma */
              );
              $maxOutputSize = params.maxOutputSize;
              $iouThreshold = params.iouThreshold;
              $scoreThreshold = params.scoreThreshold;
              return [4, Promise.all([$boxes.data(), $scores.data()])];
            case 1:
              _a = __read.apply(void 0, [_c.sent(), 2]), boxesVals = _a[0], scoresVals = _a[1];
              _b = nonMaxSuppressionV4Impl(boxesVals, scoresVals, $maxOutputSize, $iouThreshold, $scoreThreshold, padToMaxOutputSize), selectedIndices = _b.selectedIndices, validOutputs = _b.validOutputs;
              if ($boxes !== boxes) {
                $boxes.dispose();
              }
              if ($scores !== scores) {
                $scores.dispose();
              }
              return [2, {
                selectedIndices: tensor1d(selectedIndices, "int32"),
                validOutputs: scalar(validOutputs, "int32")
              }];
          }
        });
      });
    }
    var nonMaxSuppressionPaddedAsync = nonMaxSuppressionPaddedAsync_;
    function resizeBilinear_(images, size, alignCorners, halfPixelCenters) {
      if (alignCorners === void 0) {
        alignCorners = false;
      }
      if (halfPixelCenters === void 0) {
        halfPixelCenters = false;
      }
      var $images = convertToTensor(images, "images", "resizeBilinear");
      assert($images.rank === 3 || $images.rank === 4, function() {
        return "Error in resizeBilinear: x must be rank 3 or 4, but got " + "rank ".concat($images.rank, ".");
      });
      assert(size.length === 2, function() {
        return "Error in resizeBilinear: new shape must 2D, but got shape " + "".concat(size, ".");
      });
      assert(halfPixelCenters === false || alignCorners === false, function() {
        return "Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.";
      });
      var batchImages = $images;
      var reshapedTo4D = false;
      if ($images.rank === 3) {
        reshapedTo4D = true;
        batchImages = reshape($images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);
      }
      __read(size, 0);
      var inputs = { images: batchImages };
      var attrs = { alignCorners, halfPixelCenters, size };
      var res = ENGINE.runKernel(ResizeBilinear, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var resizeBilinear = /* @__PURE__ */ op({ resizeBilinear_ });
    function resizeNearestNeighbor_(images, size, alignCorners, halfPixelCenters) {
      if (alignCorners === void 0) {
        alignCorners = false;
      }
      if (halfPixelCenters === void 0) {
        halfPixelCenters = false;
      }
      var $images = convertToTensor(images, "images", "resizeNearestNeighbor");
      assert($images.rank === 3 || $images.rank === 4, function() {
        return "Error in resizeNearestNeighbor: x must be rank 3 or 4, but got " + "rank ".concat($images.rank, ".");
      });
      assert(size.length === 2, function() {
        return "Error in resizeNearestNeighbor: new shape must 2D, but got shape " + "".concat(size, ".");
      });
      assert($images.dtype === "float32" || $images.dtype === "int32", function() {
        return "`images` must have `int32` or `float32` as dtype";
      });
      assert(halfPixelCenters === false || alignCorners === false, function() {
        return "Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.";
      });
      var batchImages = $images;
      var reshapedTo4D = false;
      if ($images.rank === 3) {
        reshapedTo4D = true;
        batchImages = reshape($images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);
      }
      __read(size, 0);
      var inputs = { images: batchImages };
      var attrs = { alignCorners, halfPixelCenters, size };
      var res = ENGINE.runKernel(ResizeNearestNeighbor, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var resizeNearestNeighbor = /* @__PURE__ */ op({ resizeNearestNeighbor_ });
    function threshold_(image2, method, inverted, threshValue) {
      var _a;
      if (method === void 0) {
        method = "binary";
      }
      if (inverted === void 0) {
        inverted = false;
      }
      if (threshValue === void 0) {
        threshValue = 0.5;
      }
      var $image = convertToTensor(image2, "image", "threshold");
      var RED_INTENCITY_COEF = 0.2989;
      var GREEN_INTENCITY_COEF = 0.587;
      var BLUE_INTENCITY_COEF = 0.114;
      var totalPixelsInImage = $image.shape[0] * $image.shape[1];
      var $threshold = mul(tensor1d([threshValue]), 255);
      var r, g, b, grayscale;
      assert($image.rank === 3, function() {
        return "Error in threshold: image must be rank 3," + "but got rank ".concat($image.rank, ".");
      });
      assert($image.shape[2] === 3 || $image.shape[2] === 1, function() {
        return "Error in threshold: image color channel must be equal to 3 or 1" + "but got ".concat($image.shape[2], ".");
      });
      assert($image.dtype === "int32" || $image.dtype === "float32", function() {
        return "Error in dtype: image dtype must be int32 or float32," + "but got dtype ".concat($image.dtype, ".");
      });
      assert(method === "otsu" || method === "binary", function() {
        return "Method must be binary or otsu, but was ".concat(method);
      });
      if ($image.shape[2] === 3) {
        _a = __read(split$1($image, [1, 1, 1], -1), 3), r = _a[0], g = _a[1], b = _a[2];
        var $r = mul(r, RED_INTENCITY_COEF);
        var $g = mul(g, GREEN_INTENCITY_COEF);
        var $b = mul(b, BLUE_INTENCITY_COEF);
        grayscale = add(add($r, $g), $b);
      } else {
        grayscale = image2;
      }
      if (method === "otsu") {
        var $histogram = bincount(cast(round(grayscale), "int32"), tensor([]), 256);
        $threshold = otsu($histogram, totalPixelsInImage);
      }
      var invCondition = inverted ? lessEqual(grayscale, $threshold) : greater(grayscale, $threshold);
      var result = cast(mul(invCondition, 255), "int32");
      return result;
    }
    function otsu(histogram, total) {
      var bestThresh = tensor1d([-1]);
      var bestInBetVar = tensor1d([0]);
      var cInBetVar = tensor1d([0]);
      var classFirst, classSecond, meanFirst, meanSec, weightForeground, weightBack;
      for (var index = 0; index < histogram.size - 1; index++) {
        classFirst = slice(histogram, 0, index + 1);
        classSecond = slice(histogram, index + 1);
        weightForeground = div(sum(classFirst), total);
        weightBack = div(sum(classSecond), total);
        var meanFirstDivA = sum(mul(classFirst, range(0, classFirst.size)));
        meanFirst = div(meanFirstDivA, sum(classFirst));
        var meanSecFill = fill(classSecond.shape, classFirst.size);
        var meanSecAdd = add(range(0, classSecond.size), meanSecFill);
        var meanSecMul = mul(classSecond, meanSecAdd);
        meanSec = div(sum(meanSecMul), sum(classSecond));
        var cInBetVarSubA = sub(meanFirst, meanSec);
        var cInBetVarSubB = sub(meanFirst, meanSec);
        var cInBetVarMul = mul(weightForeground, weightBack);
        cInBetVar = mul(mul(cInBetVarMul, cInBetVarSubA), cInBetVarSubB);
        var condition = greater(cInBetVar, bestInBetVar);
        bestInBetVar = where(condition, cInBetVar, bestInBetVar);
        bestThresh = where(condition, tensor1d([index]), bestThresh);
      }
      return bestThresh;
    }
    var threshold = /* @__PURE__ */ op({ threshold_ });
    function transform_(image2, transforms, interpolation, fillMode, fillValue, outputShape) {
      if (interpolation === void 0) {
        interpolation = "nearest";
      }
      if (fillMode === void 0) {
        fillMode = "constant";
      }
      if (fillValue === void 0) {
        fillValue = 0;
      }
      var $image = convertToTensor(image2, "image", "transform", "float32");
      var $transforms = convertToTensor(transforms, "transforms", "transform", "float32");
      assert($image.rank === 4, function() {
        return "Error in transform: image must be rank 4," + "but got rank ".concat($image.rank, ".");
      });
      assert($transforms.rank === 2 && ($transforms.shape[0] === $image.shape[0] || $transforms.shape[0] === 1) && $transforms.shape[1] === 8, function() {
        return "Error in transform: Input transform should be batch x 8 or 1 x 8";
      });
      assert(outputShape == null || outputShape.length === 2, function() {
        return "Error in transform: outputShape must be [height, width] or null, " + "but got ".concat(outputShape, ".");
      });
      var inputs = { image: $image, transforms: $transforms };
      var attrs = { interpolation, fillMode, fillValue, outputShape };
      return ENGINE.runKernel(Transform, inputs, attrs);
    }
    var transform = /* @__PURE__ */ op({ transform_ });
    function bandPart_(a, numLower, numUpper) {
      var $a = convertToTensor(a, "a", "bandPart");
      assert($a.rank >= 2, function() {
        return "bandPart(): Rank must be at least 2, got ".concat($a.rank, ".");
      });
      var shape = $a.shape;
      var _a = __read($a.shape.slice(-2), 2), M = _a[0], N = _a[1];
      var $numLower;
      var $numUpper;
      if (typeof numLower === "number") {
        assert(numLower % 1 === 0, function() {
          return "bandPart(): numLower must be an integer, got ".concat(numLower, ".");
        });
        assert(numLower <= M, function() {
          return "bandPart(): numLower (".concat(numLower, ")") + " must not be greater than the number of rows (".concat(M, ").");
        });
        $numLower = convertToTensor(numLower < 0 ? M : numLower, "numLower", "bandPart");
      } else {
        assert(numLower.dtype === "int32", function() {
          return "bandPart(): numLower's dtype must be an int32.";
        });
        $numLower = where(less(numLower, 0), M, minimum(numLower, M));
      }
      if (typeof numUpper === "number") {
        assert(numUpper % 1 === 0, function() {
          return "bandPart(): numUpper must be an integer, got ".concat(numUpper, ".");
        });
        assert(numUpper <= N, function() {
          return "bandPart(): numUpper (".concat(numUpper, ")") + " must not be greater than the number of columns (".concat(N, ").");
        });
        $numUpper = convertToTensor(numUpper < 0 ? N : numUpper, "numUpper", "bandPart");
      } else {
        assert(numUpper.dtype === "int32", function() {
          return "bandPart(): numUpper's dtype must be an int32.";
        });
        $numUpper = where(less(numUpper, 0), N, minimum(numUpper, N));
      }
      var i = reshape(range(0, M, 1, "int32"), [-1, 1]);
      var j = range(0, N, 1, "int32");
      var ij = sub(i, j);
      var inBand = logicalAnd(lessEqual(ij, $numLower), greaterEqual(ij, neg($numUpper)));
      var zero = zeros([M, N], $a.dtype);
      return reshape(stack(unstack(reshape($a, [-1, M, N])).map(function(mat) {
        return where(inBand, mat, zero);
      })), shape);
    }
    var bandPart = /* @__PURE__ */ op({ bandPart_ });
    function gramSchmidt_(xs) {
      var inputIsTensor2D;
      if (Array.isArray(xs)) {
        inputIsTensor2D = false;
        assert(xs != null && xs.length > 0, function() {
          return "Gram-Schmidt process: input must not be null, undefined, or empty";
        });
        var dim_1 = xs[0].shape[0];
        var _loop_1 = function(i2) {
          assert(xs[i2].shape[0] === dim_1, function() {
            return "Gram-Schmidt: Non-unique lengths found in the input vectors: " + "(".concat(xs[i2].shape[0], " vs. ").concat(dim_1, ")");
          });
        };
        for (var i = 1; i < xs.length; ++i) {
          _loop_1(i);
        }
      } else {
        inputIsTensor2D = true;
        xs = split$1(xs, xs.shape[0], 0).map(function(x) {
          return squeeze(x, [0]);
        });
      }
      assert(xs.length <= xs[0].shape[0], function() {
        return "Gram-Schmidt: Number of vectors (".concat(xs.length, ") exceeds ") + "number of dimensions (".concat(xs[0].shape[0], ").");
      });
      var ys = [];
      var xs1d = xs;
      var _loop_2 = function(i2) {
        ys.push(ENGINE.tidy(function() {
          var x = xs1d[i2];
          if (i2 > 0) {
            for (var j = 0; j < i2; ++j) {
              var proj = mul(sum(mul(ys[j], x)), ys[j]);
              x = sub(x, proj);
            }
          }
          return div(x, norm(x, "euclidean"));
        }));
      };
      for (var i = 0; i < xs.length; ++i) {
        _loop_2(i);
      }
      if (inputIsTensor2D) {
        return stack(ys, 0);
      } else {
        return ys;
      }
    }
    var gramSchmidt = /* @__PURE__ */ op({ gramSchmidt_ });
    function qr_(x, fullMatrices) {
      if (fullMatrices === void 0) {
        fullMatrices = false;
      }
      assert(x.rank >= 2, function() {
        return "qr() requires input tensor to have a rank >= 2, but got rank ".concat(x.rank);
      });
      if (x.rank === 2) {
        return qr2d(x, fullMatrices);
      } else {
        var outerDimsProd = x.shape.slice(0, x.shape.length - 2).reduce(function(value, prev) {
          return value * prev;
        });
        var x2ds = unstack(reshape(x, [
          outerDimsProd,
          x.shape[x.shape.length - 2],
          x.shape[x.shape.length - 1]
        ]), 0);
        var q2ds_1 = [];
        var r2ds_1 = [];
        x2ds.forEach(function(x2d) {
          var _a = __read(qr2d(x2d, fullMatrices), 2), q2d = _a[0], r2d = _a[1];
          q2ds_1.push(q2d);
          r2ds_1.push(r2d);
        });
        var q = reshape(stack(q2ds_1, 0), x.shape);
        var r = reshape(stack(r2ds_1, 0), x.shape);
        return [q, r];
      }
    }
    function qr2d(x, fullMatrices) {
      if (fullMatrices === void 0) {
        fullMatrices = false;
      }
      return ENGINE.tidy(function() {
        assert(x.shape.length === 2, function() {
          return "qr2d() requires a 2D Tensor, but got a ".concat(x.shape.length, "D Tensor.");
        });
        var m = x.shape[0];
        var n = x.shape[1];
        var q = eye(m);
        var r = clone(x);
        var one2D = tensor2d([[1]], [1, 1]);
        var w = clone(one2D);
        var iters = m >= n ? n : m;
        var _loop_1 = function(j2) {
          var _a;
          var rTemp = r;
          var wTemp = w;
          var qTemp = q;
          _a = __read(ENGINE.tidy(function() {
            var rjEnd1 = slice(r, [j2, j2], [m - j2, 1]);
            var normX = norm(rjEnd1);
            var rjj = slice(r, [j2, j2], [1, 1]);
            var s = where(greater(rjj, 0), tensor2d([[-1]]), tensor2d([[1]]));
            var u1 = sub(rjj, mul(s, normX));
            var wPre = div(rjEnd1, u1);
            if (wPre.shape[0] === 1) {
              w = clone(one2D);
            } else {
              w = concat([
                one2D,
                slice(wPre, [1, 0], [wPre.shape[0] - 1, wPre.shape[1]])
              ], 0);
            }
            var tau = neg(div(matMul$1(s, u1), normX));
            var rjEndAll = slice(r, [j2, 0], [m - j2, n]);
            var tauTimesW = mul(tau, w);
            var wT = transpose(w);
            if (j2 === 0) {
              r = sub(rjEndAll, matMul$1(tauTimesW, matMul$1(wT, rjEndAll)));
            } else {
              var rTimesTau = sub(rjEndAll, matMul$1(tauTimesW, matMul$1(wT, rjEndAll)));
              r = concat([slice(r, [0, 0], [j2, n]), rTimesTau], 0);
            }
            var tawTimesWT = transpose(tauTimesW);
            var qAllJEnd = slice(q, [0, j2], [m, q.shape[1] - j2]);
            if (j2 === 0) {
              q = sub(qAllJEnd, matMul$1(matMul$1(qAllJEnd, w), tawTimesWT));
            } else {
              var qTimesTau = sub(qAllJEnd, matMul$1(matMul$1(qAllJEnd, w), tawTimesWT));
              q = concat([slice(q, [0, 0], [m, j2]), qTimesTau], 1);
            }
            return [w, r, q];
          }), 3), w = _a[0], r = _a[1], q = _a[2];
          dispose([rTemp, wTemp, qTemp]);
        };
        for (var j = 0; j < iters; ++j) {
          _loop_1(j);
        }
        if (!fullMatrices && m > n) {
          q = slice(q, [0, 0], [m, n]);
          r = slice(r, [0, 0], [n, n]);
        }
        return [q, r];
      });
    }
    var qr = /* @__PURE__ */ op({ qr_ });
    var Reduction;
    (function(Reduction2) {
      Reduction2[Reduction2["NONE"] = 0] = "NONE";
      Reduction2[Reduction2["MEAN"] = 1] = "MEAN";
      Reduction2[Reduction2["SUM"] = 2] = "SUM";
      Reduction2[Reduction2["SUM_BY_NONZERO_WEIGHTS"] = 3] = "SUM_BY_NONZERO_WEIGHTS";
    })(Reduction || (Reduction = {}));
    function computeWeightedLoss_(losses2, weights, reduction2) {
      if (reduction2 === void 0) {
        reduction2 = Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $losses = convertToTensor(losses2, "losses", "computeWeightedLoss");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "computeWeightedLoss");
      }
      var weightedLoss = $weights == null ? $losses : mul($losses, $weights);
      if (reduction2 === Reduction.NONE) {
        return weightedLoss;
      }
      if (reduction2 === Reduction.SUM) {
        return sum(weightedLoss);
      }
      if (reduction2 === Reduction.MEAN) {
        if ($weights == null) {
          return mean(weightedLoss);
        } else {
          var broadcastFactor = $losses.size / $weights.size;
          var result = div(sum(weightedLoss), sum($weights));
          return broadcastFactor > 1 ? div(result, scalar(broadcastFactor)) : result;
        }
      }
      if (reduction2 === Reduction.SUM_BY_NONZERO_WEIGHTS) {
        if ($weights == null) {
          return div(sum(weightedLoss), scalar($losses.size));
        } else {
          var broadcastedWeights = mul($weights, ones($losses.shape));
          var numNonZeros = cast(sum(notEqual(broadcastedWeights, scalar(0))), "float32");
          return div(sum(weightedLoss), numNonZeros);
        }
      }
      throw Error("Unknown reduction: ".concat(reduction2));
    }
    var computeWeightedLoss = /* @__PURE__ */ op({ computeWeightedLoss_ });
    function absoluteDifference_(labels, predictions, weights, reduction2) {
      if (reduction2 === void 0) {
        reduction2 = Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $labels = convertToTensor(labels, "labels", "absoluteDifference");
      var $predictions = convertToTensor(predictions, "predictions", "absoluteDifference");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "absoluteDifference");
      }
      assertShapesMatch($labels.shape, $predictions.shape, "Error in absoluteDifference: ");
      var losses2 = abs(sub($labels, $predictions));
      return computeWeightedLoss(losses2, $weights, reduction2);
    }
    var absoluteDifference = /* @__PURE__ */ op({ absoluteDifference_ });
    function cosineDistance_(labels, predictions, axis, weights, reduction2) {
      if (reduction2 === void 0) {
        reduction2 = Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $labels = convertToTensor(labels, "labels", "cosineDistance");
      var $predictions = convertToTensor(predictions, "predictions", "cosineDistance");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "cosineDistance");
      }
      assertShapesMatch($labels.shape, $predictions.shape, "Error in cosineDistance: ");
      var one = scalar(1);
      var losses2 = sub(one, sum(mul($labels, $predictions), axis, true));
      return computeWeightedLoss(losses2, $weights, reduction2);
    }
    var cosineDistance = /* @__PURE__ */ op({ cosineDistance_ });
    function hingeLoss_(labels, predictions, weights, reduction2) {
      if (reduction2 === void 0) {
        reduction2 = Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $labels = convertToTensor(labels, "labels", "hingeLoss");
      var $predictions = convertToTensor(predictions, "predictions", "hingeLoss");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "hingeLoss");
      }
      assertShapesMatch($labels.shape, $predictions.shape, "Error in hingeLoss: ");
      var one = scalar(1);
      $labels = sub(mul(scalar(2), $labels), one);
      var losses2 = relu(sub(one, mul($labels, $predictions)));
      return computeWeightedLoss(losses2, $weights, reduction2);
    }
    var hingeLoss = /* @__PURE__ */ op({ hingeLoss_ });
    function huberLoss_(labels, predictions, weights, delta, reduction2) {
      if (delta === void 0) {
        delta = 1;
      }
      if (reduction2 === void 0) {
        reduction2 = Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $labels = convertToTensor(labels, "labels", "huberLoss");
      var $predictions = convertToTensor(predictions, "predictions", "huberLoss");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "huberLoss");
      }
      assertShapesMatch($labels.shape, $predictions.shape, "Error in huberLoss: ");
      var deltaScalar = scalar(delta);
      var error = abs(sub($predictions, $labels));
      var quadratic = minimum(error, deltaScalar);
      var linear = sub(error, quadratic);
      var losses2 = add(mul(scalar(0.5), square(quadratic)), mul(deltaScalar, linear));
      return computeWeightedLoss(losses2, $weights, reduction2);
    }
    var huberLoss = /* @__PURE__ */ op({ huberLoss_ });
    function logLoss_(labels, predictions, weights, epsilon, reduction2) {
      if (epsilon === void 0) {
        epsilon = 1e-7;
      }
      if (reduction2 === void 0) {
        reduction2 = Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $labels = convertToTensor(labels, "labels", "logLoss");
      var $predictions = convertToTensor(predictions, "predictions", "logLoss");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "logLoss");
      }
      assertShapesMatch($labels.shape, $predictions.shape, "Error in logLoss: ");
      var one = scalar(1);
      var epsilonScalar = scalar(epsilon);
      var l1 = neg(mul($labels, log(add($predictions, epsilonScalar))));
      var l2 = mul(sub(one, $labels), log(add(sub(one, $predictions), epsilonScalar)));
      var losses2 = sub(l1, l2);
      return computeWeightedLoss(losses2, $weights, reduction2);
    }
    var logLoss = /* @__PURE__ */ op({ logLoss_ });
    function meanSquaredError_(labels, predictions, weights, reduction2) {
      if (reduction2 === void 0) {
        reduction2 = Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $labels = convertToTensor(labels, "labels", "meanSquaredError");
      var $predictions = convertToTensor(predictions, "predictions", "meanSquaredError");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "meanSquaredError");
      }
      assertShapesMatch($labels.shape, $predictions.shape, "Error in meanSquaredError: ");
      var losses2 = squaredDifference($labels, $predictions);
      return computeWeightedLoss(losses2, $weights, reduction2);
    }
    var meanSquaredError = /* @__PURE__ */ op({ meanSquaredError_ });
    function sigmoidCrossEntropyWithLogits_(labels, logits) {
      var $labels = convertToTensor(labels, "labels", "sigmoidCrossEntropyWithLogits");
      var $logits = convertToTensor(logits, "logits", "sigmoidCrossEntropyWithLogits");
      assertShapesMatch($labels.shape, $logits.shape, "Error in sigmoidCrossEntropyWithLogits: ");
      var maxOutput = relu($logits);
      var outputXTarget = mul($logits, $labels);
      var sigmoidOutput = log1p(exp(neg(abs($logits))));
      return add(sub(maxOutput, outputXTarget), sigmoidOutput);
    }
    function sigmoidCrossEntropy_(multiClassLabels, logits, weights, labelSmoothing, reduction2) {
      if (labelSmoothing === void 0) {
        labelSmoothing = 0;
      }
      if (reduction2 === void 0) {
        reduction2 = Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $multiClassLabels = convertToTensor(multiClassLabels, "multiClassLabels", "sigmoidCrossEntropy");
      var $logits = convertToTensor(logits, "logits", "sigmoidCrossEntropy");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "sigmoidCrossEntropy");
      }
      assertShapesMatch($multiClassLabels.shape, $logits.shape, "Error in sigmoidCrossEntropy: ");
      if (labelSmoothing > 0) {
        var labelSmoothingScalar = scalar(labelSmoothing);
        var one = scalar(1);
        var half = scalar(0.5);
        $multiClassLabels = add(mul($multiClassLabels, sub(one, labelSmoothingScalar)), mul(half, labelSmoothingScalar));
      }
      var losses2 = sigmoidCrossEntropyWithLogits_($multiClassLabels, $logits);
      return computeWeightedLoss(losses2, $weights, reduction2);
    }
    var sigmoidCrossEntropy = /* @__PURE__ */ op({ sigmoidCrossEntropy_ });
    function softmaxCrossEntropyWithLogits_(labels, logits, dim) {
      if (dim === void 0) {
        dim = -1;
      }
      if (dim === -1) {
        dim = logits.rank - 1;
      }
      if (dim !== logits.rank - 1) {
        throw Error("Softmax cross entropy along a non-last dimension is not yet " + "supported. Labels / logits was rank ".concat(logits.rank, " ") + "and dim was ".concat(dim));
      }
      var customOp = customGrad(function(labels2, logits2, save) {
        var keepDims = true;
        var lse = logSumExp(logits2, [dim], keepDims);
        var logResult = sub(cast(logits2, "float32"), lse);
        save([labels2, logResult]);
        var costVector = neg(mul(logResult, labels2));
        var value = sum(costVector, [dim]);
        var gradFunc = function(dy, saved) {
          var _a = __read(saved, 2), labels3 = _a[0], logResult2 = _a[1];
          var dyShape = expandShapeToKeepDim(dy.shape, [dim]);
          return [
            mul(reshape(dy, dyShape), sub(cast(labels3, "float32"), exp(logResult2))),
            mul(reshape(dy, dyShape), sub(exp(logResult2), cast(labels3, "float32")))
          ];
        };
        return { value, gradFunc };
      });
      return customOp(labels, logits);
    }
    function softmaxCrossEntropy_(onehotLabels, logits, weights, labelSmoothing, reduction2) {
      if (labelSmoothing === void 0) {
        labelSmoothing = 0;
      }
      if (reduction2 === void 0) {
        reduction2 = Reduction.SUM_BY_NONZERO_WEIGHTS;
      }
      var $onehotLabels = convertToTensor(onehotLabels, "onehotLabels", "softmaxCrossEntropy");
      var $logits = convertToTensor(logits, "logits", "softmaxCrossEntropy");
      var $weights = null;
      if (weights != null) {
        $weights = convertToTensor(weights, "weights", "softmaxCrossEntropy");
      }
      assertShapesMatch($onehotLabels.shape, $logits.shape, "Error in softmaxCrossEntropy: ");
      if (labelSmoothing > 0) {
        var labelSmoothingScalar = scalar(labelSmoothing);
        var one = scalar(1);
        var numClasses = scalar($onehotLabels.shape[1]);
        $onehotLabels = add(mul($onehotLabels, sub(one, labelSmoothingScalar)), div(labelSmoothingScalar, numClasses));
      }
      var losses2 = softmaxCrossEntropyWithLogits_($onehotLabels, $logits);
      return computeWeightedLoss(losses2, $weights, reduction2);
    }
    var softmaxCrossEntropy = /* @__PURE__ */ op({ softmaxCrossEntropy_ });
    function sparseFillEmptyRows_(indices, values, denseShape, defaultValue) {
      var $indices = convertToTensor(indices, "indices", "sparseFillEmptyRows", "int32");
      var $values = convertToTensor(values, "values", "sparseFillEmptyRows");
      var $denseShape = convertToTensor(denseShape, "denseShape", "sparseFillEmptyRows", "int32");
      var $defaultValue = convertToTensor(defaultValue, "defaultValue", "sparseFillEmptyRows", $values.dtype);
      if ($indices.rank !== 2) {
        throw new Error("Indices should be Tensor2D but received shape\n        ".concat($indices.shape));
      }
      if ($values.rank !== 1) {
        throw new Error("Values should be Tensor1D but received shape ".concat($values.shape));
      }
      if ($denseShape.rank !== 1) {
        throw new Error("Dense shape should be Tensor1D but received shape ".concat($denseShape.shape));
      }
      if ($defaultValue.rank !== 0) {
        throw new Error("Default value should be a scalar but received shape ".concat($defaultValue.shape));
      }
      var inputs = {
        indices: $indices,
        values: $values,
        denseShape: $denseShape,
        defaultValue: $defaultValue
      };
      var result = ENGINE.runKernel(SparseFillEmptyRows, inputs);
      return {
        outputIndices: result[0],
        outputValues: result[1],
        emptyRowIndicator: result[2],
        reverseIndexMap: result[3]
      };
    }
    var sparseFillEmptyRows = /* @__PURE__ */ op({ sparseFillEmptyRows_ });
    function sparseReshape_(inputIndices, inputShape, newShape) {
      var $inputIndices = convertToTensor(inputIndices, "inputIndices", "sparseReshape", "int32");
      var $inputShape = convertToTensor(inputShape, "inputShape", "sparseReshape", "int32");
      var $newShape = convertToTensor(newShape, "newShape", "sparseReshape", "int32");
      if ($inputIndices.rank !== 2) {
        throw new Error("Input indices should be Tensor2D but received shape\n        ".concat($inputIndices.shape));
      }
      if ($inputShape.rank !== 1) {
        throw new Error("Input shape should be Tensor1D but received shape ".concat($inputShape.shape));
      }
      if ($newShape.rank !== 1) {
        throw new Error("New shape should be Tensor1D but received shape ".concat($newShape.shape));
      }
      var inputs = {
        inputIndices: $inputIndices,
        inputShape: $inputShape,
        newShape: $newShape
      };
      var result = ENGINE.runKernel(SparseReshape, inputs);
      return { outputIndices: result[0], outputShape: result[1] };
    }
    var sparseReshape = /* @__PURE__ */ op({ sparseReshape_ });
    function sparseSegmentMean_(data, indices, segmentIds) {
      var $data = convertToTensor(data, "data", "sparseSegmentMean");
      var $indices = convertToTensor(indices, "indices", "sparseSegmentMean", "int32");
      var $segmentIds = convertToTensor(segmentIds, "segmentIds", "sparseSegmentMean", "int32");
      if ($data.rank < 1) {
        throw new Error("Data should be at least 1 dimensional but received scalar");
      }
      if ($indices.rank !== 1) {
        throw new Error("Indices should be Tensor1D but received shape\n          ".concat($indices.shape));
      }
      if ($segmentIds.rank !== 1) {
        throw new Error("Segment ids should be Tensor1D but received shape\n          ".concat($segmentIds.shape));
      }
      var inputs = {
        data: $data,
        indices: $indices,
        segmentIds: $segmentIds
      };
      return ENGINE.runKernel(SparseSegmentMean, inputs);
    }
    var sparseSegmentMean = /* @__PURE__ */ op({ sparseSegmentMean_ });
    function sparseSegmentSum_(data, indices, segmentIds) {
      var $data = convertToTensor(data, "data", "sparseSegmentSum");
      var $indices = convertToTensor(indices, "indices", "sparseSegmentSum", "int32");
      var $segmentIds = convertToTensor(segmentIds, "segmentIds", "sparseSegmentSum", "int32");
      if ($data.rank < 1) {
        throw new Error("Data should be at least 1 dimensional but received scalar");
      }
      if ($indices.rank !== 1) {
        throw new Error("Indices should be Tensor1D but received shape\n         ".concat($indices.shape));
      }
      if ($segmentIds.rank !== 1) {
        throw new Error("Segment ids should be Tensor1D but received shape\n         ".concat($segmentIds.shape));
      }
      var inputs = {
        data: $data,
        indices: $indices,
        segmentIds: $segmentIds
      };
      return ENGINE.runKernel(SparseSegmentSum, inputs);
    }
    var sparseSegmentSum = /* @__PURE__ */ op({ sparseSegmentSum_ });
    function stringNGrams_(data, dataSplits, separator, nGramWidths, leftPad, rightPad2, padWidth, preserveShortSequences) {
      var $data = convertToTensor(data, "data", "stringNGrams", "string");
      if ($data.dtype !== "string") {
        throw new Error("Data must be of datatype string");
      }
      if ($data.shape.length !== 1) {
        throw new Error("Data must be a vector, saw: ".concat($data.shape));
      }
      var $dataSplits = convertToTensor(dataSplits, "dataSplits", "stringNGrams");
      if ($dataSplits.dtype !== "int32") {
        throw new Error("Data splits must be of datatype int32");
      }
      var attrs = {
        separator,
        nGramWidths,
        leftPad,
        rightPad: rightPad2,
        padWidth,
        preserveShortSequences
      };
      var inputs = { data: $data, dataSplits: $dataSplits };
      var result = ENGINE.runKernel(StringNGrams, inputs, attrs);
      return { nGrams: result[0], nGramsSplits: result[1] };
    }
    var stringNGrams = /* @__PURE__ */ op({ stringNGrams_ });
    function stringSplit_(input, delimiter, skipEmpty) {
      if (skipEmpty === void 0) {
        skipEmpty = true;
      }
      var $input = convertToTensor(input, "input", "stringSplit", "string");
      var $delimiter = convertToTensor(delimiter, "delimiter", "stringSplit", "string");
      if ($input.rank !== 1) {
        throw new Error("Input should be Tensor1D but received shape ".concat($input.shape));
      }
      if ($delimiter.rank !== 0) {
        throw new Error("Delimiter should be a scalar but received shape ".concat($delimiter.shape));
      }
      var attrs = { skipEmpty };
      var inputs = { input: $input, delimiter: $delimiter };
      var result = ENGINE.runKernel(StringSplit, inputs, attrs);
      return { indices: result[0], values: result[1], shape: result[2] };
    }
    var stringSplit = /* @__PURE__ */ op({ stringSplit_ });
    function stringToHashBucketFast_(input, numBuckets) {
      var $input = convertToTensor(input, "input", "stringToHashBucketFast", "string");
      var attrs = { numBuckets };
      if (numBuckets <= 0) {
        throw new Error("Number of buckets must be at least 1");
      }
      var inputs = { input: $input };
      return ENGINE.runKernel(StringToHashBucketFast, inputs, attrs);
    }
    var stringToHashBucketFast = /* @__PURE__ */ op({ stringToHashBucketFast_ });
    function staticRegexReplace_(input, pattern, rewrite, replaceGlobal) {
      if (replaceGlobal === void 0) {
        replaceGlobal = true;
      }
      var $input = convertToTensor(input, "input", "staticRegexReplace", "string");
      var attrs = { pattern, rewrite, replaceGlobal };
      return ENGINE.runKernel(StaticRegexReplace, { x: $input }, attrs);
    }
    var staticRegexReplace = /* @__PURE__ */ op({ staticRegexReplace_ });
    var spectral = {
      fft,
      ifft,
      rfft,
      irfft
    };
    var signal = {
      hammingWindow,
      hannWindow,
      frame,
      stft
    };
    var image = {
      flipLeftRight,
      grayscaleToRGB,
      resizeNearestNeighbor,
      resizeBilinear,
      rgbToGrayscale,
      rotateWithOffset,
      cropAndResize,
      nonMaxSuppression,
      nonMaxSuppressionAsync,
      nonMaxSuppressionWithScore,
      nonMaxSuppressionWithScoreAsync,
      nonMaxSuppressionPadded,
      nonMaxSuppressionPaddedAsync,
      threshold,
      transform
    };
    var linalg = {
      bandPart,
      gramSchmidt,
      qr
    };
    var losses = {
      absoluteDifference,
      computeWeightedLoss,
      cosineDistance,
      hingeLoss,
      huberLoss,
      logLoss,
      meanSquaredError,
      sigmoidCrossEntropy,
      softmaxCrossEntropy
    };
    var sparse = {
      sparseFillEmptyRows,
      sparseReshape,
      sparseSegmentMean,
      sparseSegmentSum
    };
    var string = {
      stringNGrams,
      stringSplit,
      stringToHashBucketFast,
      staticRegexReplace
    };
    var tfOps = {
      __proto__: null,
      OP_SCOPE_SUFFIX,
      abs,
      acos,
      acosh,
      add,
      addN,
      all,
      any,
      argMax,
      argMin,
      asin,
      asinh,
      atan,
      atan2,
      atanh,
      avgPool,
      avgPool3d,
      basicLSTMCell,
      batchNorm,
      batchNorm2d,
      batchNorm3d,
      batchNorm4d,
      batchToSpaceND,
      bincount,
      bitwiseAnd,
      booleanMaskAsync,
      broadcastArgs,
      broadcastTo,
      buffer,
      cast,
      ceil,
      clipByValue,
      clone,
      complex,
      concat,
      concat1d,
      concat2d,
      concat3d,
      concat4d,
      conv1d,
      conv2d: conv2d$1,
      conv2dTranspose,
      conv3d,
      conv3dTranspose,
      cos,
      cosh,
      cosineWindow,
      cumprod,
      cumsum,
      denseBincount,
      depthToSpace,
      depthwiseConv2d: depthwiseConv2d$1,
      diag,
      dilation2d,
      div,
      divNoNan,
      dot,
      dropout,
      einsum,
      elu,
      enclosingPowerOfTwo,
      ensureShape,
      equal,
      erf,
      euclideanNorm,
      exp,
      expandDims,
      expm1,
      eye,
      fft,
      fill,
      floor,
      floorDiv,
      fused: fused_ops,
      gather,
      gatherND,
      greater,
      greaterEqual,
      ifft,
      imag,
      image,
      inTopKAsync,
      irfft,
      isFinite: isFinite$1,
      isInf,
      isNaN: isNaN$1,
      leakyRelu,
      less,
      lessEqual,
      linalg,
      linspace,
      localResponseNormalization,
      log,
      log1p,
      logSigmoid,
      logSoftmax,
      logSumExp,
      logicalAnd,
      logicalNot,
      logicalOr,
      logicalXor,
      losses,
      lowerBound,
      matMul: matMul$1,
      max,
      maxPool,
      maxPool3d,
      maxPoolWithArgmax,
      maximum,
      mean,
      meshgrid,
      min,
      minimum,
      mirrorPad,
      mod,
      moments,
      movingAverage,
      mul,
      multiRNNCell,
      multinomial,
      neg,
      norm,
      notEqual,
      oneHot,
      ones,
      onesLike,
      op,
      outerProduct,
      pad,
      pad1d,
      pad2d,
      pad3d,
      pad4d,
      pool,
      pow,
      prelu,
      print,
      prod,
      raggedGather,
      raggedRange,
      raggedTensorToTensor,
      rand,
      randomGamma,
      randomNormal,
      randomStandardNormal,
      randomUniform,
      randomUniformInt,
      range,
      real,
      reciprocal,
      relu,
      relu6,
      reshape,
      reverse,
      reverse1d,
      reverse2d,
      reverse3d,
      reverse4d,
      rfft,
      round,
      rsqrt,
      scalar,
      scatterND,
      searchSorted,
      selu,
      separableConv2d,
      setdiff1dAsync,
      sigmoid,
      sign,
      signal,
      sin,
      sinh,
      slice,
      slice1d,
      slice2d,
      slice3d,
      slice4d,
      softmax,
      softplus,
      spaceToBatchND,
      sparse,
      sparseToDense,
      spectral,
      split: split$1,
      sqrt,
      square,
      squaredDifference,
      squeeze,
      stack,
      step,
      stridedSlice,
      string,
      sub,
      sum,
      tan,
      tanh,
      tensor,
      tensor1d,
      tensor2d,
      tensor3d,
      tensor4d,
      tensor5d,
      tensor6d,
      tensorScatterUpdate,
      tile,
      topk,
      transpose,
      truncatedNormal,
      unique,
      unsortedSegmentSum,
      unstack,
      upperBound,
      variable,
      where,
      whereAsync,
      zeros,
      zerosLike
    };
    var executeOp$k = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "BiasAdd":
        case "AddV2":
        case "Add": {
          return [ops.add(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "AddN": {
          return [ops.addN(getParamValue("tensors", node, tensorMap, context))];
        }
        case "FloorMod":
        case "Mod":
          return [ops.mod(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        case "Mul":
          return [ops.mul(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        case "RealDiv":
        case "Div": {
          return [ops.div(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "DivNoNan": {
          return [ops.divNoNan(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "FloorDiv": {
          return [ops.floorDiv(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "Sub": {
          return [ops.sub(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "Minimum": {
          return [ops.minimum(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "Maximum": {
          return [ops.maximum(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "Pow": {
          return [ops.pow(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "SquaredDifference": {
          return [ops.squaredDifference(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    var executeOp$j = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "Abs":
        case "ComplexAbs":
          return [ops.abs(getParamValue("x", node, tensorMap, context))];
        case "Acos":
          return [ops.acos(getParamValue("x", node, tensorMap, context))];
        case "Acosh":
          return [ops.acosh(getParamValue("x", node, tensorMap, context))];
        case "Asin":
          return [ops.asin(getParamValue("x", node, tensorMap, context))];
        case "Asinh":
          return [ops.asinh(getParamValue("x", node, tensorMap, context))];
        case "Atan":
          return [ops.atan(getParamValue("x", node, tensorMap, context))];
        case "Atan2":
          return [ops.atan2(getParamValue("x", node, tensorMap, context), getParamValue("y", node, tensorMap, context))];
        case "Atanh":
          return [ops.atanh(getParamValue("x", node, tensorMap, context))];
        case "Ceil":
          return [ops.ceil(getParamValue("x", node, tensorMap, context))];
        case "Complex":
          return [ops.complex(getParamValue("real", node, tensorMap, context), getParamValue("imag", node, tensorMap, context))];
        case "Cos":
          return [ops.cos(getParamValue("x", node, tensorMap, context))];
        case "Cosh":
          return [ops.cosh(getParamValue("x", node, tensorMap, context))];
        case "Elu":
          return [ops.elu(getParamValue("x", node, tensorMap, context))];
        case "Erf":
          return [ops.erf(getParamValue("x", node, tensorMap, context))];
        case "Exp":
          return [ops.exp(getParamValue("x", node, tensorMap, context))];
        case "Expm1": {
          return [ops.expm1(getParamValue("x", node, tensorMap, context))];
        }
        case "Floor":
          return [ops.floor(getParamValue("x", node, tensorMap, context))];
        case "Log":
          return [ops.log(getParamValue("x", node, tensorMap, context))];
        case "Log1p": {
          return [ops.log1p(getParamValue("x", node, tensorMap, context))];
        }
        case "Imag":
          return [ops.imag(getParamValue("x", node, tensorMap, context))];
        case "Neg":
          return [ops.neg(getParamValue("x", node, tensorMap, context))];
        case "Reciprocal": {
          return [ops.reciprocal(getParamValue("x", node, tensorMap, context))];
        }
        case "Real":
          return [ops.real(getParamValue("x", node, tensorMap, context))];
        case "Relu":
          return [ops.relu(getParamValue("x", node, tensorMap, context))];
        case "Round": {
          return [ops.round(getParamValue("x", node, tensorMap, context))];
        }
        case "Selu":
          return [ops.selu(getParamValue("x", node, tensorMap, context))];
        case "Sigmoid":
          return [ops.sigmoid(getParamValue("x", node, tensorMap, context))];
        case "Sin":
          return [ops.sin(getParamValue("x", node, tensorMap, context))];
        case "Sign": {
          return [ops.sign(getParamValue("x", node, tensorMap, context))];
        }
        case "Sinh": {
          return [ops.sinh(getParamValue("x", node, tensorMap, context))];
        }
        case "Softplus": {
          return [ops.softplus(getParamValue("x", node, tensorMap, context))];
        }
        case "Sqrt": {
          return [ops.sqrt(getParamValue("x", node, tensorMap, context))];
        }
        case "Square": {
          return [ops.square(getParamValue("x", node, tensorMap, context))];
        }
        case "Tanh": {
          return [ops.tanh(getParamValue("x", node, tensorMap, context))];
        }
        case "Tan":
          return [ops.tan(getParamValue("x", node, tensorMap, context))];
        case "ClipByValue":
          return [ops.clipByValue(getParamValue("x", node, tensorMap, context), getParamValue("clipValueMin", node, tensorMap, context), getParamValue("clipValueMax", node, tensorMap, context))];
        case "Relu6":
          return [ops.relu6(getParamValue("x", node, tensorMap, context))];
        case "Rsqrt":
          return [ops.rsqrt(getTensor(node.inputNames[0], tensorMap, context))];
        case "LeakyRelu":
          return [ops.leakyRelu(getParamValue("x", node, tensorMap, context), getParamValue("alpha", node, tensorMap, context))];
        case "Prelu":
          return [ops.prelu(getParamValue("x", node, tensorMap, context), getParamValue("alpha", node, tensorMap, context))];
        case "IsNan":
          return [ops.isNaN(getTensor(node.inputNames[0], tensorMap, context))];
        case "IsInf":
          return [ops.isInf(getTensor(node.inputNames[0], tensorMap, context))];
        case "IsFinite":
          return [ops.isFinite(getTensor(node.inputNames[0], tensorMap, context))];
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    function assertShapesMatchAllowUndefinedSize(shapeA, shapeB, errorMessagePrefix) {
      if (errorMessagePrefix === void 0) {
        errorMessagePrefix = "";
      }
      if (typeof shapeA === "number" || typeof shapeB === "number") {
        return;
      }
      tfc.util.assert(shapeA.length === shapeB.length, function() {
        return errorMessagePrefix + " Shapes ".concat(shapeA, " and ").concat(shapeB, " must match");
      });
      for (var i = 0; i < shapeA.length; i++) {
        var dim0 = shapeA[i];
        var dim1 = shapeB[i];
        tfc.util.assert(dim0 < 0 || dim1 < 0 || dim0 === dim1, function() {
          return errorMessagePrefix + " Shapes ".concat(shapeA, " and ").concat(shapeB, " must match");
        });
      }
    }
    function fullDefinedShape(elementShape) {
      if (typeof elementShape === "number" || elementShape.some(function(dim) {
        return dim < 0;
      })) {
        return false;
      }
      return true;
    }
    function inferElementShape(listElementShape, tensors, elementShape) {
      var partialShape = mergeElementShape(listElementShape, elementShape);
      var notfullDefinedShape = !fullDefinedShape(partialShape);
      if (notfullDefinedShape && tensors.length === 0) {
        throw new Error("Tried to calculate elements of an empty list" + " with non-fully-defined elementShape: ".concat(partialShape));
      }
      if (notfullDefinedShape) {
        tensors.forEach(function(tensor2) {
          partialShape = mergeElementShape(tensor2.shape, partialShape);
        });
      }
      if (!fullDefinedShape(partialShape)) {
        throw new Error("Non-fully-defined elementShape: ".concat(partialShape));
      }
      return partialShape;
    }
    function mergeElementShape(elementShapeA, elementShapeB) {
      if (typeof elementShapeA === "number") {
        return elementShapeB;
      }
      if (typeof elementShapeB === "number") {
        return elementShapeA;
      }
      if (elementShapeA.length !== elementShapeB.length) {
        throw new Error("Incompatible ranks during merge: ".concat(elementShapeA, " vs. ").concat(elementShapeB));
      }
      var result = [];
      for (var i = 0; i < elementShapeA.length; ++i) {
        var dim0 = elementShapeA[i];
        var dim1 = elementShapeB[i];
        if (dim0 >= 0 && dim1 >= 0 && dim0 !== dim1) {
          throw new Error("Incompatible shape during merge: ".concat(elementShapeA, " vs. ").concat(elementShapeB));
        }
        result[i] = dim0 >= 0 ? dim0 : dim1;
      }
      return result;
    }
    var TensorArray = (
      /** @class */
      function() {
        function TensorArray2(name, dtype, maxSize, elementShape, identicalElementShapes, dynamicSize, clearAfterRead) {
          this.name = name;
          this.dtype = dtype;
          this.maxSize = maxSize;
          this.elementShape = elementShape;
          this.identicalElementShapes = identicalElementShapes;
          this.dynamicSize = dynamicSize;
          this.clearAfterRead = clearAfterRead;
          this.tensors = [];
          this.closed_ = false;
          this.idTensor = tfc.scalar(0);
          tfc.keep(this.idTensor);
        }
        Object.defineProperty(TensorArray2.prototype, "id", {
          get: function() {
            return this.idTensor.id;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(TensorArray2.prototype, "closed", {
          get: function() {
            return this.closed_;
          },
          enumerable: false,
          configurable: true
        });
        TensorArray2.prototype.clearAndClose = function(keepIds) {
          this.tensors.forEach(function(tensor2) {
            if (keepIds == null || !keepIds.has(tensor2.tensor.id)) {
              tensor2.tensor.dispose();
            }
          });
          this.tensors = [];
          this.closed_ = true;
          this.idTensor.dispose();
        };
        TensorArray2.prototype.size = function() {
          return this.tensors.length;
        };
        TensorArray2.prototype.read = function(index) {
          if (this.closed_) {
            throw new Error("TensorArray ".concat(this.name, " has already been closed."));
          }
          if (index < 0 || index >= this.size()) {
            throw new Error("Tried to read from index ".concat(index, ", but array size is: ").concat(this.size()));
          }
          var tensorWithState = this.tensors[index];
          if (tensorWithState.cleared) {
            throw new Error("TensorArray ".concat(this.name, ": Could not read index ").concat(index, " twice because it was cleared after a previous read ") + "(perhaps try setting clear_after_read = false?).");
          }
          if (this.clearAfterRead) {
            tensorWithState.cleared = true;
          }
          tensorWithState.read = true;
          return tensorWithState.tensor;
        };
        TensorArray2.prototype.readMany = function(indices) {
          var _this = this;
          return indices.map(function(index) {
            return _this.read(index);
          });
        };
        TensorArray2.prototype.write = function(index, tensor2) {
          if (this.closed_) {
            throw new Error("TensorArray ".concat(this.name, " has already been closed."));
          }
          if (index < 0 || !this.dynamicSize && index >= this.maxSize) {
            throw new Error("Tried to write to index ".concat(index, ", but array is not resizeable and size is: ").concat(this.maxSize));
          }
          var t = this.tensors[index] || {};
          if (tensor2.dtype !== this.dtype) {
            throw new Error("TensorArray ".concat(this.name, ": Could not write to TensorArray index ").concat(index, ",\n          because the value dtype is ").concat(tensor2.dtype, ", but TensorArray dtype is ").concat(this.dtype, "."));
          }
          if (this.size() === 0 && (this.elementShape == null || this.elementShape.length === 0)) {
            this.elementShape = tensor2.shape;
          }
          assertShapesMatchAllowUndefinedSize(this.elementShape, tensor2.shape, "TensorArray ".concat(this.name, ": Could not write to TensorArray index ").concat(index, "."));
          if (t.read) {
            throw new Error("TensorArray ".concat(this.name, ": Could not write to TensorArray index ").concat(index, ", because it has already been read."));
          }
          if (t.written) {
            throw new Error("TensorArray ".concat(this.name, ": Could not write to TensorArray index ").concat(index, ", because it has already been written."));
          }
          t.tensor = tensor2;
          tfc.keep(tensor2);
          t.written = true;
          this.tensors[index] = t;
        };
        TensorArray2.prototype.writeMany = function(indices, tensors) {
          var _this = this;
          if (indices.length !== tensors.length) {
            throw new Error("TensorArray ".concat(this.name, ": could not write multiple tensors,") + "because the index size: ".concat(indices.length, " is not the same as tensors size: ").concat(tensors.length, "."));
          }
          indices.forEach(function(i, index) {
            return _this.write(i, tensors[index]);
          });
        };
        TensorArray2.prototype.gather = function(indices, dtype) {
          if (!!dtype && dtype !== this.dtype) {
            throw new Error("TensorArray dtype is ".concat(this.dtype, " but gather requested dtype ").concat(dtype));
          }
          if (!indices) {
            indices = [];
            for (var i = 0; i < this.size(); i++) {
              indices.push(i);
            }
          } else {
            indices = indices.slice(0, this.size());
          }
          if (indices.length === 0) {
            return tfc.tensor([], [0].concat(this.elementShape));
          }
          var tensors = this.readMany(indices);
          assertShapesMatchAllowUndefinedSize(this.elementShape, tensors[0].shape, "TensorArray shape mismatch: ");
          return tfc.stack(tensors, 0);
        };
        TensorArray2.prototype.concat = function(dtype) {
          if (!!dtype && dtype !== this.dtype) {
            throw new Error("TensorArray dtype is ".concat(this.dtype, " but concat requested dtype ").concat(dtype));
          }
          if (this.size() === 0) {
            return tfc.tensor([], [0].concat(this.elementShape));
          }
          var indices = [];
          for (var i = 0; i < this.size(); i++) {
            indices.push(i);
          }
          var tensors = this.readMany(indices);
          assertShapesMatchAllowUndefinedSize(this.elementShape, tensors[0].shape, "TensorArray shape mismatch: tensor array shape (".concat(this.elementShape, ") vs first tensor shape (").concat(tensors[0].shape, ")"));
          return tfc.concat(tensors, 0);
        };
        TensorArray2.prototype.scatter = function(indices, tensor2) {
          if (tensor2.dtype !== this.dtype) {
            throw new Error("TensorArray dtype is ".concat(this.dtype, " but tensor has dtype ").concat(tensor2.dtype));
          }
          if (indices.length !== tensor2.shape[0]) {
            throw new Error("Expected len(indices) == tensor.shape[0], but saw: ".concat(indices.length, " vs. ").concat(tensor2.shape[0]));
          }
          var maxIndex = Math.max.apply(Math, __spreadArray([], __read(indices), false));
          if (!this.dynamicSize && maxIndex >= this.maxSize) {
            throw new Error("Max index must be < array size (".concat(maxIndex, "  vs. ").concat(this.maxSize, ")"));
          }
          this.writeMany(indices, tfc.unstack(tensor2, 0));
        };
        TensorArray2.prototype.split = function(length, tensor2) {
          var _this = this;
          if (tensor2.dtype !== this.dtype) {
            throw new Error("TensorArray dtype is ".concat(this.dtype, " but tensor has dtype ").concat(tensor2.dtype));
          }
          var totalLength = 0;
          var cumulativeLengths = length.map(function(len) {
            totalLength += len;
            return totalLength;
          });
          if (totalLength !== tensor2.shape[0]) {
            throw new Error("Expected sum of lengths to be equal to\n          tensor.shape[0], but sum of lengths is\n        ".concat(totalLength, ", and tensor's shape is: ").concat(tensor2.shape));
          }
          if (!this.dynamicSize && length.length !== this.maxSize) {
            throw new Error("TensorArray's size is not equal to the size of lengths (".concat(this.maxSize, " vs. ").concat(length.length, "), ") + "and the TensorArray is not marked as dynamically resizeable");
          }
          var elementPerRow = totalLength === 0 ? 0 : tensor2.size / totalLength;
          var tensors = [];
          tfc.tidy(function() {
            tensor2 = tfc.reshape(tensor2, [1, totalLength, elementPerRow]);
            for (var i2 = 0; i2 < length.length; ++i2) {
              var previousLength = i2 === 0 ? 0 : cumulativeLengths[i2 - 1];
              var indices_1 = [0, previousLength, 0];
              var sizes = [1, length[i2], elementPerRow];
              tensors[i2] = tfc.reshape(tfc.slice(tensor2, indices_1, sizes), _this.elementShape);
            }
            return tensors;
          });
          var indices = [];
          for (var i = 0; i < length.length; i++) {
            indices[i] = i;
          }
          this.writeMany(indices, tensors);
        };
        return TensorArray2;
      }()
    );
    var TensorList = (
      /** @class */
      function() {
        function TensorList2(tensors, elementShape, elementDtype, maxNumElements) {
          if (maxNumElements === void 0) {
            maxNumElements = -1;
          }
          this.tensors = tensors;
          this.elementShape = elementShape;
          this.elementDtype = elementDtype;
          if (tensors != null) {
            tensors.forEach(function(tensor2) {
              if (elementDtype !== tensor2.dtype) {
                throw new Error("Invalid data types; op elements ".concat(elementDtype, ", but list elements ").concat(tensor2.dtype));
              }
              assertShapesMatchAllowUndefinedSize(elementShape, tensor2.shape, "TensorList shape mismatch: ");
              tfc.keep(tensor2);
            });
          }
          this.idTensor = tfc.scalar(0);
          this.maxNumElements = maxNumElements;
          tfc.keep(this.idTensor);
        }
        Object.defineProperty(TensorList2.prototype, "id", {
          get: function() {
            return this.idTensor.id;
          },
          enumerable: false,
          configurable: true
        });
        TensorList2.prototype.copy = function() {
          return new TensorList2(__spreadArray([], __read(this.tensors), false), this.elementShape, this.elementDtype);
        };
        TensorList2.prototype.clearAndClose = function(keepIds) {
          this.tensors.forEach(function(tensor2) {
            if (keepIds == null || !keepIds.has(tensor2.id)) {
              tensor2.dispose();
            }
          });
          this.tensors.length = 0;
          this.idTensor.dispose();
        };
        TensorList2.prototype.size = function() {
          return this.tensors.length;
        };
        TensorList2.prototype.stack = function(elementShape, elementDtype, numElements) {
          var _this = this;
          if (numElements === void 0) {
            numElements = -1;
          }
          if (elementDtype !== this.elementDtype) {
            throw new Error("Invalid data types; op elements ".concat(elementDtype, ", but list elements ").concat(this.elementDtype));
          }
          if (numElements !== -1 && this.tensors.length !== numElements) {
            throw new Error("Operation expected a list with ".concat(numElements, " elements but got a list with ").concat(this.tensors.length, " elements."));
          }
          assertShapesMatchAllowUndefinedSize(elementShape, this.elementShape, "TensorList shape mismatch: ");
          var outputElementShape = inferElementShape(this.elementShape, this.tensors, elementShape);
          return tfc.tidy(function() {
            var reshapedTensors = _this.tensors.map(function(tensor2) {
              return tfc.reshape(tensor2, outputElementShape);
            });
            return tfc.stack(reshapedTensors, 0);
          });
        };
        TensorList2.prototype.popBack = function(elementShape, elementDtype) {
          if (elementDtype !== this.elementDtype) {
            throw new Error("Invalid data types; op elements ".concat(elementDtype, ", but list elements ").concat(this.elementDtype));
          }
          if (this.size() === 0) {
            throw new Error("Trying to pop from an empty list.");
          }
          var outputElementShape = inferElementShape(this.elementShape, this.tensors, elementShape);
          var tensor2 = this.tensors.pop();
          tensor2.kept = false;
          assertShapesMatchAllowUndefinedSize(tensor2.shape, elementShape, "TensorList shape mismatch: ");
          return tfc.reshape(tensor2, outputElementShape);
        };
        TensorList2.prototype.pushBack = function(tensor2) {
          if (tensor2.dtype !== this.elementDtype) {
            throw new Error("Invalid data types; op elements ".concat(tensor2.dtype, ", but list elements ").concat(this.elementDtype));
          }
          assertShapesMatchAllowUndefinedSize(tensor2.shape, this.elementShape, "TensorList shape mismatch: ");
          if (this.maxNumElements === this.size()) {
            throw new Error("Trying to push element into a full list.");
          }
          tfc.keep(tensor2);
          this.tensors.push(tensor2);
        };
        TensorList2.prototype.resize = function(size) {
          if (size < 0) {
            throw new Error("TensorListResize expects size to be non-negative. Got: ".concat(size));
          }
          if (this.maxNumElements !== -1 && size > this.maxNumElements) {
            throw new Error("TensorListResize input size ".concat(size, " is greater maxNumElement ").concat(this.maxNumElements, "."));
          }
          var destTensorList = new TensorList2([], this.elementShape, this.elementDtype, this.maxNumElements);
          destTensorList.tensors.length = size;
          for (var i = 0; i < Math.min(this.tensors.length, size); ++i) {
            destTensorList.tensors[i] = this.tensors[i];
          }
          return destTensorList;
        };
        TensorList2.prototype.getItem = function(elementIndex, elementShape, elementDtype) {
          if (elementDtype !== this.elementDtype) {
            throw new Error("Invalid data types; op elements ".concat(elementDtype, ", but list elements ").concat(this.elementDtype));
          }
          if (elementIndex < 0 || elementIndex > this.tensors.length) {
            throw new Error("Trying to access element ".concat(elementIndex, " in a list with ").concat(this.tensors.length, " elements."));
          }
          if (this.tensors[elementIndex] == null) {
            throw new Error("element at index ".concat(elementIndex, " is null."));
          }
          assertShapesMatchAllowUndefinedSize(this.tensors[elementIndex].shape, elementShape, "TensorList shape mismatch: ");
          var outputElementShape = inferElementShape(this.elementShape, this.tensors, elementShape);
          return tfc.reshape(this.tensors[elementIndex], outputElementShape);
        };
        TensorList2.prototype.setItem = function(elementIndex, tensor2) {
          if (tensor2.dtype !== this.elementDtype) {
            throw new Error("Invalid data types; op elements ".concat(tensor2.dtype, ", but list elements ").concat(this.elementDtype));
          }
          if (elementIndex < 0 || this.maxNumElements !== -1 && elementIndex >= this.maxNumElements) {
            throw new Error("Trying to set element ".concat(elementIndex, " in a list with max ").concat(this.maxNumElements, " elements."));
          }
          assertShapesMatchAllowUndefinedSize(this.elementShape, tensor2.shape, "TensorList shape mismatch: ");
          tfc.keep(tensor2);
          if (this.tensors[elementIndex] != null) {
            this.tensors[elementIndex].kept = false;
          }
          this.tensors[elementIndex] = tensor2;
        };
        TensorList2.prototype.gather = function(indices, elementDtype, elementShape) {
          var _this = this;
          if (elementDtype !== this.elementDtype) {
            throw new Error("Invalid data types; op elements ".concat(elementDtype, ", but list elements ").concat(this.elementDtype));
          }
          assertShapesMatchAllowUndefinedSize(this.elementShape, elementShape, "TensorList shape mismatch: ");
          indices = indices.slice(0, this.size());
          var outputElementShape = inferElementShape(this.elementShape, this.tensors, elementShape);
          if (indices.length === 0) {
            return tfc.tensor([], [0].concat(outputElementShape));
          }
          return tfc.tidy(function() {
            var tensors = indices.map(function(i) {
              return tfc.reshape(_this.tensors[i], outputElementShape);
            });
            return tfc.stack(tensors, 0);
          });
        };
        TensorList2.prototype.concat = function(elementDtype, elementShape) {
          var _this = this;
          if (!!elementDtype && elementDtype !== this.elementDtype) {
            throw new Error("TensorList dtype is ".concat(this.elementDtype, " but concat requested dtype ").concat(elementDtype));
          }
          assertShapesMatchAllowUndefinedSize(this.elementShape, elementShape, "TensorList shape mismatch: ");
          var outputElementShape = inferElementShape(this.elementShape, this.tensors, elementShape);
          if (this.size() === 0) {
            return tfc.tensor([], [0].concat(outputElementShape));
          }
          return tfc.tidy(function() {
            var tensors = _this.tensors.map(function(t) {
              return tfc.reshape(t, outputElementShape);
            });
            return tfc.concat(tensors, 0);
          });
        };
        return TensorList2;
      }()
    );
    function fromTensor(tensor2, elementShape, elementDtype) {
      var dtype = tensor2.dtype;
      if (tensor2.shape.length < 1) {
        throw new Error("Tensor must be at least a vector, but saw shape: ".concat(tensor2.shape));
      }
      if (tensor2.dtype !== elementDtype) {
        throw new Error("Invalid data types; op elements ".concat(tensor2.dtype, ", but list elements ").concat(elementDtype));
      }
      var tensorElementShape = tensor2.shape.slice(1);
      assertShapesMatchAllowUndefinedSize(tensorElementShape, elementShape, "TensorList shape mismatch: ");
      var tensorList = tfc.unstack(tensor2);
      return new TensorList(tensorList, elementShape, dtype);
    }
    function reserve(elementShape, elementDtype, numElements, maxNumElements) {
      return new TensorList([], elementShape, elementDtype, maxNumElements);
    }
    function scatter(tensor2, indices, elementShape, numElements) {
      if (indices.length !== tensor2.shape[0]) {
        throw new Error("Expected len(indices) == tensor.shape[0], but saw: ".concat(indices.length, " vs. ").concat(tensor2.shape[0]));
      }
      var maxIndex = Math.max.apply(Math, __spreadArray([], __read(indices), false));
      if (numElements != null && numElements !== -1 && maxIndex >= numElements) {
        throw new Error("Max index must be < array size (".concat(maxIndex, "  vs. ").concat(numElements, ")"));
      }
      var list = new TensorList([], elementShape, tensor2.dtype, numElements);
      var tensors = tfc.unstack(tensor2, 0);
      indices.forEach(function(value, index) {
        list.setItem(value, tensors[index]);
      });
      return list;
    }
    function split(tensor2, length, elementShape) {
      var totalLength = 0;
      var cumulativeLengths = length.map(function(len) {
        totalLength += len;
        return totalLength;
      });
      if (totalLength !== tensor2.shape[0]) {
        throw new Error("Expected sum of lengths to be equal to\n          tensor.shape[0], but sum of lengths is\n        ".concat(totalLength, ", and tensor's shape is: ").concat(tensor2.shape));
      }
      var shapeWithoutFirstDim = tensor2.shape.slice(1);
      var outputElementShape = mergeElementShape(shapeWithoutFirstDim, elementShape);
      var elementPerRow = totalLength === 0 ? 0 : tensor2.size / totalLength;
      var tensors = tfc.tidy(function() {
        var tensors2 = [];
        tensor2 = tfc.reshape(tensor2, [1, totalLength, elementPerRow]);
        for (var i2 = 0; i2 < length.length; ++i2) {
          var previousLength = i2 === 0 ? 0 : cumulativeLengths[i2 - 1];
          var indices = [0, previousLength, 0];
          var sizes = [1, length[i2], elementPerRow];
          tensors2[i2] = tfc.reshape(tfc.slice(tensor2, indices, sizes), outputElementShape);
        }
        tensor2.dispose();
        return tensors2;
      });
      var list = new TensorList([], elementShape, tensor2.dtype, length.length);
      for (var i = 0; i < tensors.length; i++) {
        list.setItem(i, tensors[i]);
      }
      return list;
    }
    var executeOp$i = function(node, tensorMap, context) {
      return __awaiter(void 0, void 0, void 0, function() {
        var _a, thenFunc, elseFunc, cond, args, condValue, bodyFunc, condFunc, args, condResult, argIds_1, condValue, result, _loop_1, pred, pred, data, inputName, data, frameId, data, data, data, size, dtype, elementShape, dynamicSize, clearAfterRead, identicalElementShapes, name, tensorArray, id, index, writeTensor, writeTensorArray, readId, readIndex, readTensorArray, gatherId, gatherIndices, gatherDtype, gatherTensorArray, scatterId, scatterIndices, scatterTensor, scatterTensorArray, concatId, concatTensorArray, concatDtype, splitId, splitTensor, lengths, splitTensorArray, sizeId, sizeTensorArray, closeId, closeTensorArray, idTensor, index, writeTensor, tensorList, idTensor, readIndex, elementShape, elementDType, tensorList, scatterIndices, scatterTensor, elementShape, numElements, tensorList, elementShape, elementDtype, numElementsParam, numElements, maxNumElements, tensorList, gatherId, gatherIndices, elementShape, elementDtype, tensorList, idTensor, elementShape, elementDtype, numElements, tensorList, tensor2, elementShape, elementDtype, tensorList, concatId, tensorList, concatDtype, elementShape, idTensor, writeTensor, tensorList, idTensor, elementShape, elementDType, tensorList, splitTensor, elementShape, lengths, tensorList, idTensor, tensorList, idTensor, size, srcTensorList, destTensorList;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              _a = node.op;
              switch (_a) {
                case "If":
                  return [3, 1];
                case "StatelessIf":
                  return [3, 1];
                case "While":
                  return [3, 3];
                case "StatelessWhile":
                  return [3, 3];
                case "LoopCond":
                  return [3, 9];
                case "Switch":
                  return [3, 10];
                case "Merge":
                  return [3, 12];
                case "Enter":
                  return [3, 13];
                case "Exit":
                  return [3, 14];
                case "NextIteration":
                  return [3, 15];
                case "TensorArrayV3":
                  return [3, 16];
                case "TensorArrayWriteV3":
                  return [3, 17];
                case "TensorArrayReadV3":
                  return [3, 18];
                case "TensorArrayGatherV3":
                  return [3, 19];
                case "TensorArrayScatterV3":
                  return [3, 20];
                case "TensorArrayConcatV3":
                  return [3, 21];
                case "TensorArraySplitV3":
                  return [3, 22];
                case "TensorArraySizeV3":
                  return [3, 23];
                case "TensorArrayCloseV3":
                  return [3, 24];
                case "TensorListSetItem":
                  return [3, 25];
                case "TensorListGetItem":
                  return [3, 26];
                case "TensorListScatterV2":
                  return [3, 27];
                case "TensorListScatter":
                  return [3, 27];
                case "TensorListReserve":
                  return [3, 28];
                case "EmptyTensorList":
                  return [3, 28];
                case "TensorListGather":
                  return [3, 29];
                case "TensorListStack":
                  return [3, 30];
                case "TensorListFromTensor":
                  return [3, 31];
                case "TensorListConcat":
                  return [3, 32];
                case "TensorListConcatV2":
                  return [3, 32];
                case "TensorListPushBack":
                  return [3, 33];
                case "TensorListPopBack":
                  return [3, 34];
                case "TensorListSplit":
                  return [3, 35];
                case "TensorListLength":
                  return [3, 36];
                case "TensorListResize":
                  return [3, 37];
              }
              return [3, 38];
            case 1:
              thenFunc = getParamValue("thenBranch", node, tensorMap, context);
              elseFunc = getParamValue("elseBranch", node, tensorMap, context);
              cond = getParamValue("cond", node, tensorMap, context);
              args = getParamValue("args", node, tensorMap, context);
              return [4, cond.data()];
            case 2:
              condValue = _b.sent();
              if (condValue[0]) {
                return [2, context.functionMap[thenFunc].executeFunctionAsync(args, context.tensorArrayMap, context.tensorListMap)];
              } else {
                return [2, context.functionMap[elseFunc].executeFunctionAsync(args, context.tensorArrayMap, context.tensorListMap)];
              }
            case 3:
              bodyFunc = getParamValue("body", node, tensorMap, context);
              condFunc = getParamValue("cond", node, tensorMap, context);
              args = getParamValue("args", node, tensorMap, context);
              return [4, context.functionMap[condFunc].executeFunctionAsync(args, context.tensorArrayMap, context.tensorListMap)];
            case 4:
              condResult = _b.sent();
              argIds_1 = args.map(function(tensor3) {
                return tensor3.id;
              });
              return [4, condResult[0].data()];
            case 5:
              condValue = _b.sent();
              condResult.forEach(function(tensor3) {
                if (!tensor3.kept && argIds_1.indexOf(tensor3.id) === -1) {
                  tensor3.dispose();
                }
              });
              result = args;
              _loop_1 = function() {
                var origResult, resultIds, condResult_1;
                return __generator(this, function(_c) {
                  switch (_c.label) {
                    case 0:
                      origResult = result;
                      return [4, context.functionMap[bodyFunc].executeFunctionAsync(result, context.tensorArrayMap, context.tensorListMap)];
                    case 1:
                      result = _c.sent();
                      resultIds = result.map(function(tensor3) {
                        return tensor3.id;
                      });
                      origResult.forEach(function(tensor3) {
                        if (!tensor3.kept && argIds_1.indexOf(tensor3.id) === -1 && resultIds.indexOf(tensor3.id) === -1) {
                          tensor3.dispose();
                        }
                      });
                      return [4, context.functionMap[condFunc].executeFunctionAsync(result, context.tensorArrayMap, context.tensorListMap)];
                    case 2:
                      condResult_1 = _c.sent();
                      return [4, condResult_1[0].data()];
                    case 3:
                      condValue = _c.sent();
                      condResult_1.forEach(function(tensor3) {
                        if (!tensor3.kept && argIds_1.indexOf(tensor3.id) === -1 && resultIds.indexOf(tensor3.id) === -1) {
                          tensor3.dispose();
                        }
                      });
                      return [
                        2
                        /*return*/
                      ];
                  }
                });
              };
              _b.label = 6;
            case 6:
              if (!condValue[0]) return [3, 8];
              return [5, _loop_1()];
            case 7:
              _b.sent();
              return [3, 6];
            case 8:
              return [2, result];
            case 9: {
              pred = getParamValue("pred", node, tensorMap, context);
              return [2, [cloneTensor(pred)]];
            }
            case 10:
              pred = getParamValue("pred", node, tensorMap, context);
              data = getParamValue("data", node, tensorMap, context);
              if (!data.kept) {
                data = cloneTensor(data);
              }
              return [4, pred.data()];
            case 11:
              return [2, _b.sent()[0] ? [void 0, data] : [data, void 0]];
            case 12: {
              inputName = node.inputNames.find(function(name2) {
                return getTensor(name2, tensorMap, context) !== void 0;
              });
              if (inputName) {
                data = getTensor(inputName, tensorMap, context);
                return [2, [cloneTensor(data)]];
              }
              return [2, void 0];
            }
            case 13: {
              frameId = getParamValue("frameName", node, tensorMap, context);
              data = getParamValue("tensor", node, tensorMap, context);
              context.enterFrame(frameId);
              return [2, [cloneTensor(data)]];
            }
            case 14: {
              data = getParamValue("tensor", node, tensorMap, context);
              context.exitFrame();
              return [2, [cloneTensor(data)]];
            }
            case 15: {
              data = getParamValue("tensor", node, tensorMap, context);
              context.nextIteration();
              return [2, [cloneTensor(data)]];
            }
            case 16: {
              size = getParamValue("size", node, tensorMap, context);
              dtype = getParamValue("dtype", node, tensorMap, context);
              elementShape = getParamValue("elementShape", node, tensorMap, context);
              dynamicSize = getParamValue("dynamicSize", node, tensorMap, context);
              clearAfterRead = getParamValue("clearAfterRead", node, tensorMap, context);
              identicalElementShapes = getParamValue("identicalElementShapes", node, tensorMap, context);
              name = getParamValue("name", node, tensorMap, context);
              tensorArray = new TensorArray(name, dtype, size, elementShape, identicalElementShapes, dynamicSize, clearAfterRead);
              context.addTensorArray(tensorArray);
              return [2, [tensorArray.idTensor, tfc.scalar(1)]];
            }
            case 17: {
              id = getParamValue("tensorArrayId", node, tensorMap, context);
              index = getParamValue("index", node, tensorMap, context);
              writeTensor = getParamValue("tensor", node, tensorMap, context);
              writeTensorArray = context.getTensorArray(id.id);
              writeTensorArray.write(index, writeTensor);
              return [2, [writeTensorArray.idTensor]];
            }
            case 18: {
              readId = getParamValue("tensorArrayId", node, tensorMap, context);
              readIndex = getParamValue("index", node, tensorMap, context);
              readTensorArray = context.getTensorArray(readId.id);
              return [2, [readTensorArray.read(readIndex)]];
            }
            case 19: {
              gatherId = getParamValue("tensorArrayId", node, tensorMap, context);
              gatherIndices = getParamValue("indices", node, tensorMap, context);
              gatherDtype = getParamValue("dtype", node, tensorMap, context);
              gatherTensorArray = context.getTensorArray(gatherId.id);
              return [2, [gatherTensorArray.gather(gatherIndices, gatherDtype)]];
            }
            case 20: {
              scatterId = getParamValue("tensorArrayId", node, tensorMap, context);
              scatterIndices = getParamValue("indices", node, tensorMap, context);
              scatterTensor = getParamValue("tensor", node, tensorMap, context);
              scatterTensorArray = context.getTensorArray(scatterId.id);
              scatterTensorArray.scatter(scatterIndices, scatterTensor);
              return [2, [scatterTensorArray.idTensor]];
            }
            case 21: {
              concatId = getParamValue("tensorArrayId", node, tensorMap, context);
              concatTensorArray = context.getTensorArray(concatId.id);
              concatDtype = getParamValue("dtype", node, tensorMap, context);
              return [2, [concatTensorArray.concat(concatDtype)]];
            }
            case 22: {
              splitId = getParamValue("tensorArrayId", node, tensorMap, context);
              splitTensor = getParamValue("tensor", node, tensorMap, context);
              lengths = getParamValue("lengths", node, tensorMap, context);
              splitTensorArray = context.getTensorArray(splitId.id);
              splitTensorArray.split(lengths, splitTensor);
              return [2, [splitTensorArray.idTensor]];
            }
            case 23: {
              sizeId = getParamValue("tensorArrayId", node, tensorMap, context);
              sizeTensorArray = context.getTensorArray(sizeId.id);
              return [2, [tfc.scalar(sizeTensorArray.size(), "int32")]];
            }
            case 24: {
              closeId = getParamValue("tensorArrayId", node, tensorMap, context);
              closeTensorArray = context.getTensorArray(closeId.id);
              closeTensorArray.clearAndClose();
              return [2, [closeTensorArray.idTensor]];
            }
            case 25: {
              idTensor = getParamValue("tensorListId", node, tensorMap, context);
              index = getParamValue("index", node, tensorMap, context);
              writeTensor = getParamValue("tensor", node, tensorMap, context);
              tensorList = context.getTensorList(idTensor.id);
              tensorList.setItem(index, writeTensor);
              return [2, [tensorList.idTensor]];
            }
            case 26: {
              idTensor = getParamValue("tensorListId", node, tensorMap, context);
              readIndex = getParamValue("index", node, tensorMap, context);
              elementShape = getParamValue("elementShape", node, tensorMap, context);
              elementDType = getParamValue("elementDType", node, tensorMap, context);
              tensorList = context.getTensorList(idTensor.id);
              return [2, [tensorList.getItem(readIndex, elementShape, elementDType)]];
            }
            case 27: {
              scatterIndices = getParamValue("indices", node, tensorMap, context);
              scatterTensor = getParamValue("tensor", node, tensorMap, context);
              elementShape = getParamValue("elementShape", node, tensorMap, context);
              numElements = getParamValue("numElements", node, tensorMap, context);
              tensorList = scatter(scatterTensor, scatterIndices, elementShape, numElements);
              context.addTensorList(tensorList);
              return [2, [tensorList.idTensor]];
            }
            case 28: {
              elementShape = getParamValue("elementShape", node, tensorMap, context);
              elementDtype = getParamValue("elementDType", node, tensorMap, context);
              numElementsParam = void 0;
              if (node.op === "TensorListReserve") {
                numElementsParam = "numElements";
              } else {
                numElementsParam = "maxNumElements";
              }
              numElements = getParamValue(numElementsParam, node, tensorMap, context);
              maxNumElements = node.op === "TensorListReserve" ? -1 : numElements;
              tensorList = reserve(elementShape, elementDtype, numElements, maxNumElements);
              context.addTensorList(tensorList);
              return [2, [tensorList.idTensor]];
            }
            case 29: {
              gatherId = getParamValue("tensorListId", node, tensorMap, context);
              gatherIndices = getParamValue("indices", node, tensorMap, context);
              elementShape = getParamValue("elementShape", node, tensorMap, context);
              elementDtype = getParamValue("elementDType", node, tensorMap, context);
              tensorList = context.getTensorList(gatherId.id);
              return [2, [tensorList.gather(gatherIndices, elementDtype, elementShape)]];
            }
            case 30: {
              idTensor = getParamValue("tensorListId", node, tensorMap, context);
              elementShape = getParamValue("elementShape", node, tensorMap, context);
              elementDtype = getParamValue("elementDType", node, tensorMap, context);
              numElements = getParamValue("numElements", node, tensorMap, context);
              tensorList = context.getTensorList(idTensor.id);
              return [2, [tensorList.stack(elementShape, elementDtype, numElements)]];
            }
            case 31: {
              tensor2 = getParamValue("tensor", node, tensorMap, context);
              elementShape = getParamValue("elementShape", node, tensorMap, context);
              elementDtype = getParamValue("elementDType", node, tensorMap, context);
              tensorList = fromTensor(tensor2, elementShape, elementDtype);
              context.addTensorList(tensorList);
              return [2, [tensorList.idTensor]];
            }
            case 32: {
              concatId = getParamValue("tensorListId", node, tensorMap, context);
              tensorList = context.getTensorList(concatId.id);
              concatDtype = getParamValue("dtype", node, tensorMap, context);
              elementShape = getParamValue("elementShape", node, tensorMap, context);
              return [2, [tensorList.concat(concatDtype, elementShape)]];
            }
            case 33: {
              idTensor = getParamValue("tensorListId", node, tensorMap, context);
              writeTensor = getParamValue("tensor", node, tensorMap, context);
              tensorList = context.getTensorList(idTensor.id);
              tensorList.pushBack(writeTensor);
              return [2, [tensorList.idTensor]];
            }
            case 34: {
              idTensor = getParamValue("tensorListId", node, tensorMap, context);
              elementShape = getParamValue("elementShape", node, tensorMap, context);
              elementDType = getParamValue("elementDType", node, tensorMap, context);
              tensorList = context.getTensorList(idTensor.id);
              return [2, [tensorList.popBack(elementShape, elementDType)]];
            }
            case 35: {
              splitTensor = getParamValue("tensor", node, tensorMap, context);
              elementShape = getParamValue("elementShape", node, tensorMap, context);
              lengths = getParamValue("lengths", node, tensorMap, context);
              tensorList = split(splitTensor, lengths, elementShape);
              context.addTensorList(tensorList);
              return [2, [tensorList.idTensor]];
            }
            case 36: {
              idTensor = getParamValue("tensorListId", node, tensorMap, context);
              tensorList = context.getTensorList(idTensor.id);
              return [2, [tfc.scalar(tensorList.size(), "int32")]];
            }
            case 37: {
              idTensor = getParamValue("tensorListId", node, tensorMap, context);
              size = getParamValue("size", node, tensorMap, context);
              srcTensorList = context.getTensorList(idTensor.id);
              destTensorList = srcTensorList.resize(size);
              context.addTensorList(destTensorList);
              return [2, [destTensorList.idTensor]];
            }
            case 38:
              throw TypeError("Node type ".concat(node.op, " is not implemented"));
          }
        });
      });
    };
    function fusedConvAndDepthWiseParams(node, tensorMap, context) {
      var _a = __read(getParamValue("fusedOps", node, tensorMap, context), 2), extraOp = _a[0], activationFunc = _a[1];
      var isBiasAdd = extraOp === "biasadd";
      var noBiasAdd = !isBiasAdd;
      var isPrelu = activationFunc === "prelu";
      var isBatchNorm = extraOp === "fusedbatchnorm";
      var numArgs = getParamValue("numArgs", node, tensorMap, context);
      if (isBiasAdd) {
        if (isPrelu && numArgs !== 2) {
          throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");
        }
        if (!isPrelu && isBiasAdd && numArgs !== 1) {
          throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.");
        }
      }
      if (isBatchNorm) {
        throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");
      }
      var stride = getParamValue("strides", node, tensorMap, context);
      var pad2 = getPadding(node, tensorMap, context);
      var dataFormat = getParamValue("dataFormat", node, tensorMap, context).toUpperCase();
      var dilations = getParamValue("dilations", node, tensorMap, context);
      var _b = __read(getParamValue("args", node, tensorMap, context), 2), biasArg = _b[0], preluArg = _b[1];
      if (noBiasAdd) {
        preluArg = biasArg;
        biasArg = void 0;
      }
      var leakyreluAlpha = getParamValue("leakyreluAlpha", node, tensorMap, context);
      return {
        stride,
        pad: pad2,
        dataFormat,
        dilations,
        biasArg,
        preluArg,
        activationFunc,
        leakyreluAlpha
      };
    }
    var executeOp$h = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "Conv1D": {
          var stride = getParamValue("stride", node, tensorMap, context);
          var pad2 = getParamValue("pad", node, tensorMap, context);
          var dataFormat = getParamValue("dataFormat", node, tensorMap, context).toUpperCase();
          var dilation = getParamValue("dilation", node, tensorMap, context);
          return [ops.conv1d(getParamValue("x", node, tensorMap, context), getParamValue("filter", node, tensorMap, context), stride, pad2, dataFormat, dilation)];
        }
        case "Conv2D": {
          var stride = getParamValue("strides", node, tensorMap, context);
          var pad2 = getPadding(node, tensorMap, context);
          var dataFormat = getParamValue("dataFormat", node, tensorMap, context).toUpperCase();
          var dilations = getParamValue("dilations", node, tensorMap, context);
          return [ops.conv2d(getParamValue("x", node, tensorMap, context), getParamValue("filter", node, tensorMap, context), [stride[1], stride[2]], pad2, dataFormat, [dilations[1], dilations[2]])];
        }
        case "_FusedConv2D": {
          var _a = fusedConvAndDepthWiseParams(node, tensorMap, context), stride = _a.stride, pad2 = _a.pad, dataFormat = _a.dataFormat, dilations = _a.dilations, biasArg = _a.biasArg, preluArg = _a.preluArg, activationFunc = _a.activationFunc, leakyreluAlpha = _a.leakyreluAlpha;
          return [ops.fused.conv2d({
            x: getParamValue("x", node, tensorMap, context),
            filter: getParamValue("filter", node, tensorMap, context),
            strides: [stride[1], stride[2]],
            pad: pad2,
            dataFormat,
            dilations: [dilations[1], dilations[2]],
            bias: biasArg,
            activation: activationFunc,
            preluActivationWeights: preluArg,
            leakyreluAlpha
          })];
        }
        case "FusedDepthwiseConv2dNative": {
          var _b = fusedConvAndDepthWiseParams(node, tensorMap, context), stride = _b.stride, pad2 = _b.pad, dataFormat = _b.dataFormat, dilations = _b.dilations, biasArg = _b.biasArg, preluArg = _b.preluArg, activationFunc = _b.activationFunc, leakyreluAlpha = _b.leakyreluAlpha;
          return [ops.fused.depthwiseConv2d({
            x: getParamValue("x", node, tensorMap, context),
            filter: getParamValue("filter", node, tensorMap, context),
            strides: [stride[1], stride[2]],
            pad: pad2,
            dataFormat,
            dilations: [dilations[1], dilations[2]],
            bias: biasArg,
            activation: activationFunc,
            preluActivationWeights: preluArg,
            leakyreluAlpha
          })];
        }
        case "Conv2DBackpropInput":
        case "Conv2dTranspose": {
          var shape = getParamValue("outputShape", node, tensorMap, context);
          var stride = getParamValue("strides", node, tensorMap, context);
          var pad2 = getPadding(node, tensorMap, context);
          return [ops.conv2dTranspose(getParamValue("x", node, tensorMap, context), getParamValue("filter", node, tensorMap, context), shape, [stride[1], stride[2]], pad2)];
        }
        case "DepthwiseConv2dNative":
        case "DepthwiseConv2d": {
          var stride = getParamValue("strides", node, tensorMap, context);
          var pad2 = getPadding(node, tensorMap, context);
          var dilations = getParamValue("dilations", node, tensorMap, context);
          var dataFormat = getParamValue("dataFormat", node, tensorMap, context).toUpperCase();
          return [ops.depthwiseConv2d(getParamValue("input", node, tensorMap, context), getParamValue("filter", node, tensorMap, context), [stride[1], stride[2]], pad2, dataFormat, [dilations[1], dilations[2]])];
        }
        case "Conv3D": {
          var stride = getParamValue("strides", node, tensorMap, context);
          var pad2 = getParamValue("pad", node, tensorMap, context);
          var dataFormat = getParamValue("dataFormat", node, tensorMap, context).toUpperCase();
          var dilations = getParamValue("dilations", node, tensorMap, context);
          return [ops.conv3d(getParamValue("x", node, tensorMap, context), getParamValue("filter", node, tensorMap, context), [stride[1], stride[2], stride[3]], pad2, dataFormat, [dilations[1], dilations[2], dilations[3]])];
        }
        case "AvgPool": {
          var stride = getParamValue("strides", node, tensorMap, context);
          var pad2 = getParamValue("pad", node, tensorMap, context);
          var kernelSize = getParamValue("kernelSize", node, tensorMap, context);
          return [ops.avgPool(getParamValue("x", node, tensorMap, context), [kernelSize[1], kernelSize[2]], [stride[1], stride[2]], pad2)];
        }
        case "MaxPool": {
          var stride = getParamValue("strides", node, tensorMap, context);
          var pad2 = getParamValue("pad", node, tensorMap, context);
          var kernelSize = getParamValue("kernelSize", node, tensorMap, context);
          return [ops.maxPool(getParamValue("x", node, tensorMap, context), [kernelSize[1], kernelSize[2]], [stride[1], stride[2]], pad2)];
        }
        case "MaxPoolWithArgmax": {
          var stride = getParamValue("strides", node, tensorMap, context);
          var pad2 = getParamValue("pad", node, tensorMap, context);
          var kernelSize = getParamValue("kernelSize", node, tensorMap, context);
          var includeBatchInIndex = getParamValue("includeBatchInIndex", node, tensorMap, context);
          var _c = ops.maxPoolWithArgmax(getParamValue("x", node, tensorMap, context), [kernelSize[1], kernelSize[2]], [stride[1], stride[2]], pad2, includeBatchInIndex), result = _c.result, indexes = _c.indexes;
          return [result, indexes];
        }
        case "AvgPool3D": {
          var stride = getParamValue("strides", node, tensorMap, context);
          var pad2 = getParamValue("pad", node, tensorMap, context);
          var kernelSize = getParamValue("kernelSize", node, tensorMap, context);
          return [ops.avgPool3d(getParamValue("x", node, tensorMap, context), [kernelSize[1], kernelSize[2], kernelSize[3]], [stride[1], stride[2], stride[3]], pad2)];
        }
        case "MaxPool3D": {
          var stride = getParamValue("strides", node, tensorMap, context);
          var pad2 = getParamValue("pad", node, tensorMap, context);
          var kernelSize = getParamValue("kernelSize", node, tensorMap, context);
          return [ops.maxPool3d(getParamValue("x", node, tensorMap, context), [kernelSize[1], kernelSize[2], kernelSize[3]], [stride[1], stride[2], stride[3]], pad2)];
        }
        case "Dilation2D": {
          var strides = getParamValue("strides", node, tensorMap, context);
          var pad2 = getParamValue("pad", node, tensorMap, context);
          var dilations = getParamValue("dilations", node, tensorMap, context);
          var strideHeight = strides[1];
          var strideWidth = strides[2];
          var dilationHeight = dilations[1];
          var dilationWidth = dilations[2];
          return [ops.dilation2d(
            getParamValue("x", node, tensorMap, context),
            getParamValue("filter", node, tensorMap, context),
            [strideHeight, strideWidth],
            pad2,
            [dilationHeight, dilationWidth],
            "NHWC"
            /* dataFormat */
          )];
        }
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    var executeOp$g = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "Fill": {
          var shape = getParamValue("shape", node, tensorMap, context);
          var dtype = getParamValue("dtype", node, tensorMap, context);
          var value = getParamValue("value", node, tensorMap, context);
          return [ops.fill(shape, value, dtype)];
        }
        case "LinSpace": {
          var start = getParamValue("start", node, tensorMap, context);
          var stop = getParamValue("stop", node, tensorMap, context);
          var num = getParamValue("num", node, tensorMap, context);
          return [ops.linspace(start, stop, num)];
        }
        case "Multinomial": {
          var logits = getParamValue("logits", node, tensorMap, context);
          var numSamples = getParamValue("numSamples", node, tensorMap, context);
          var seed = getParamValue("seed", node, tensorMap, context);
          return [ops.multinomial(logits, numSamples, seed)];
        }
        case "OneHot": {
          var indices = getParamValue("indices", node, tensorMap, context);
          var depth = getParamValue("depth", node, tensorMap, context);
          var onValue = getParamValue("onValue", node, tensorMap, context);
          var offValue = getParamValue("offValue", node, tensorMap, context);
          var dtype = getParamValue("dtype", node, tensorMap, context);
          return [ops.oneHot(indices, depth, onValue, offValue, dtype)];
        }
        case "Ones": {
          return [ops.ones(getParamValue("shape", node, tensorMap, context), getParamValue("dtype", node, tensorMap, context))];
        }
        case "OnesLike": {
          return [ops.onesLike(getParamValue("x", node, tensorMap, context))];
        }
        case "RandomStandardNormal": {
          return [ops.randomStandardNormal(getParamValue("shape", node, tensorMap, context), getParamValue("dtype", node, tensorMap, context), getParamValue("seed", node, tensorMap, context))];
        }
        case "RandomUniform": {
          return [ops.randomUniform(
            // tslint:disable-next-line:no-any
            getParamValue("shape", node, tensorMap, context),
            getParamValue("minval", node, tensorMap, context),
            getParamValue("maxval", node, tensorMap, context),
            getParamValue("dtype", node, tensorMap, context)
          )];
        }
        case "RandomUniformInt": {
          return [ops.randomUniformInt(getParamValue("shape", node, tensorMap, context), getParamValue("minval", node, tensorMap, context), getParamValue("maxval", node, tensorMap, context), getParamValue("seed", node, tensorMap, context))];
        }
        case "Range": {
          var start = getParamValue("start", node, tensorMap, context);
          var stop = getParamValue("stop", node, tensorMap, context);
          var step2 = getParamValue("step", node, tensorMap, context);
          return [ops.range(start, stop, step2, getParamValue("dtype", node, tensorMap, context))];
        }
        case "TruncatedNormal": {
          var shape = getParamValue("shape", node, tensorMap, context);
          var mean2 = getParamValue("mean", node, tensorMap, context);
          var stdDev = getParamValue("stdDev", node, tensorMap, context);
          var seed = getParamValue("seed", node, tensorMap, context);
          return [ops.truncatedNormal(shape, mean2, stdDev, getParamValue("dtype", node, tensorMap, context), seed)];
        }
        case "Zeros": {
          return [ops.zeros(getParamValue("shape", node, tensorMap, context), getParamValue("dtype", node, tensorMap, context))];
        }
        case "ZerosLike": {
          return [ops.zerosLike(getParamValue("x", node, tensorMap, context))];
        }
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    function nmsParams(node, tensorMap, context) {
      var boxes = getParamValue("boxes", node, tensorMap, context);
      var scores = getParamValue("scores", node, tensorMap, context);
      var maxOutputSize = getParamValue("maxOutputSize", node, tensorMap, context);
      var iouThreshold = getParamValue("iouThreshold", node, tensorMap, context);
      var scoreThreshold = getParamValue("scoreThreshold", node, tensorMap, context);
      var softNmsSigma = getParamValue("softNmsSigma", node, tensorMap, context);
      return {
        boxes,
        scores,
        maxOutputSize,
        iouThreshold,
        scoreThreshold,
        softNmsSigma
      };
    }
    var executeOp$f = function(node, tensorMap, context, resourceManager, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      return __awaiter(void 0, void 0, void 0, function() {
        var _a, _b, boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma, result, _c, boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize, result, _d, boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, condition, result;
        return __generator(this, function(_e) {
          switch (_e.label) {
            case 0:
              _a = node.op;
              switch (_a) {
                case "NonMaxSuppressionV5":
                  return [3, 1];
                case "NonMaxSuppressionV4":
                  return [3, 3];
                case "NonMaxSuppressionV3":
                  return [3, 5];
                case "NonMaxSuppressionV2":
                  return [3, 5];
                case "Where":
                  return [3, 7];
                case "ListDiff":
                  return [3, 9];
              }
              return [3, 10];
            case 1:
              _b = nmsParams(node, tensorMap, context), boxes = _b.boxes, scores = _b.scores, maxOutputSize = _b.maxOutputSize, iouThreshold = _b.iouThreshold, scoreThreshold = _b.scoreThreshold, softNmsSigma = _b.softNmsSigma;
              return [4, ops.image.nonMaxSuppressionWithScoreAsync(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma)];
            case 2:
              result = _e.sent();
              return [2, [result.selectedIndices, result.selectedScores]];
            case 3:
              _c = nmsParams(node, tensorMap, context), boxes = _c.boxes, scores = _c.scores, maxOutputSize = _c.maxOutputSize, iouThreshold = _c.iouThreshold, scoreThreshold = _c.scoreThreshold;
              padToMaxOutputSize = getParamValue("padToMaxOutputSize", node, tensorMap, context);
              return [4, ops.image.nonMaxSuppressionPaddedAsync(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize)];
            case 4:
              result = _e.sent();
              return [2, [result.selectedIndices, result.validOutputs]];
            case 5:
              _d = nmsParams(node, tensorMap, context), boxes = _d.boxes, scores = _d.scores, maxOutputSize = _d.maxOutputSize, iouThreshold = _d.iouThreshold, scoreThreshold = _d.scoreThreshold;
              return [4, ops.image.nonMaxSuppressionAsync(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold)];
            case 6:
              return [2, [_e.sent()]];
            case 7:
              condition = ops.cast(getParamValue("condition", node, tensorMap, context), "bool");
              return [4, ops.whereAsync(condition)];
            case 8:
              result = [_e.sent()];
              condition.dispose();
              return [2, result];
            case 9: {
              return [2, ops.setdiff1dAsync(getParamValue("x", node, tensorMap, context), getParamValue("y", node, tensorMap, context))];
            }
            case 10:
              throw TypeError("Node type ".concat(node.op, " is not implemented"));
          }
        });
      });
    };
    var executeOp$e = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "LowerBound": {
          var sortedSequence = getParamValue("sortedSequence", node, tensorMap, context);
          var values = getParamValue("values", node, tensorMap, context);
          return [ops.lowerBound(sortedSequence, values)];
        }
        case "TopKV2": {
          var x = getParamValue("x", node, tensorMap, context);
          var k = getParamValue("k", node, tensorMap, context);
          var sorted = getParamValue("sorted", node, tensorMap, context);
          var result = ops.topk(x, k, sorted);
          return [result.values, result.indices];
        }
        case "UpperBound": {
          var sortedSequence = getParamValue("sortedSequence", node, tensorMap, context);
          var values = getParamValue("values", node, tensorMap, context);
          return [ops.upperBound(sortedSequence, values)];
        }
        case "Unique": {
          var x = getParamValue("x", node, tensorMap, context);
          var result = ops.unique(x);
          return [result.values, result.indices];
        }
        case "UniqueV2": {
          var x = getParamValue("x", node, tensorMap, context);
          var axis = getParamValue("axis", node, tensorMap, context);
          var result = ops.unique(x, axis);
          return [result.values, result.indices];
        }
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    var executeOp$d = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "Const": {
          return tensorMap[node.name];
        }
        case "PlaceholderWithDefault":
          var def = getParamValue("default", node, tensorMap, context);
          return [getTensor(node.name, tensorMap, context) || def];
        case "Placeholder":
          return [getTensor(node.name, tensorMap, context)];
        case "Identity":
        case "StopGradient":
        case "FakeQuantWithMinMaxVars": {
          var data_1 = getParamValue("x", node, tensorMap, context);
          return [cloneTensor(data_1)];
        }
        case "IdentityN":
          return getParamValue("x", node, tensorMap, context).map(function(t) {
            return cloneTensor(t);
          });
        case "Snapshot":
          var snapshot = getParamValue("x", node, tensorMap, context);
          return [cloneTensor(snapshot)];
        case "Shape":
          return [ops.tensor1d(getParamValue("x", node, tensorMap, context).shape, "int32")];
        case "ShapeN":
          return getParamValue("x", node, tensorMap, context).map(function(t) {
            return ops.tensor1d(t.shape);
          });
        case "Size":
          return [ops.scalar(getParamValue("x", node, tensorMap, context).size, "int32")];
        case "Rank":
          return [ops.scalar(getParamValue("x", node, tensorMap, context).rank, "int32")];
        case "NoOp":
          return [ops.scalar(1)];
        case "Print":
          var input = getParamValue("x", node, tensorMap, context);
          var data = getParamValue("data", node, tensorMap, context);
          var message = getParamValue("message", node, tensorMap, context);
          var summarize = getParamValue("summarize", node, tensorMap, context);
          console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance.");
          console.log(message);
          for (var i = 0; i < data.length; i++) {
            console.log(Array.prototype.slice.call(data[i].dataSync()).slice(0, summarize));
          }
          return [input];
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    var HashTable = (
      /** @class */
      function() {
        function HashTable2(keyDType, valueDType) {
          this.keyDType = keyDType;
          this.valueDType = valueDType;
          this.handle = tfc.scalar(0);
          this.tensorMap = /* @__PURE__ */ new Map();
          tfc.keep(this.handle);
        }
        Object.defineProperty(HashTable2.prototype, "id", {
          get: function() {
            return this.handle.id;
          },
          enumerable: false,
          configurable: true
        });
        HashTable2.prototype.clearAndClose = function() {
          this.tensorMap.forEach(function(value) {
            return value.dispose();
          });
          this.tensorMap.clear();
          this.handle.dispose();
        };
        HashTable2.prototype.size = function() {
          return this.tensorMap.size;
        };
        HashTable2.prototype.tensorSize = function() {
          return scalar(this.size(), "int32");
        };
        HashTable2.prototype.import = function(keys, values) {
          return __awaiter(this, void 0, void 0, function() {
            var $keys;
            var _this = this;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  this.checkKeyAndValueTensor(keys, values);
                  return [4, keys.data()];
                case 1:
                  $keys = _a.sent();
                  this.tensorMap.forEach(function(value) {
                    return value.dispose();
                  });
                  this.tensorMap.clear();
                  return [2, tfc.tidy(function() {
                    var $values = tfc.unstack(values);
                    var keysLength = $keys.length;
                    var valuesLength = $values.length;
                    tfc.util.assert(keysLength === valuesLength, function() {
                      return "The number of elements doesn't match, keys has " + "".concat(keysLength, " elements, the values has ").concat(valuesLength, " ") + "elements.";
                    });
                    for (var i = 0; i < keysLength; i++) {
                      var key = $keys[i];
                      var value = $values[i];
                      tfc.keep(value);
                      _this.tensorMap.set(key, value);
                    }
                    return _this.handle;
                  })];
              }
            });
          });
        };
        HashTable2.prototype.find = function(keys, defaultValue) {
          return __awaiter(this, void 0, void 0, function() {
            var $keys;
            var _this = this;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  this.checkKeyAndValueTensor(keys, defaultValue);
                  return [4, keys.data()];
                case 1:
                  $keys = _a.sent();
                  return [2, tfc.tidy(function() {
                    var result = [];
                    for (var i = 0; i < $keys.length; i++) {
                      var key = $keys[i];
                      var value = _this.findWithDefault(key, defaultValue);
                      result.push(value);
                    }
                    return tfc.stack(result);
                  })];
              }
            });
          });
        };
        HashTable2.prototype.findWithDefault = function(key, defaultValue) {
          var result = this.tensorMap.get(key);
          return result != null ? result : defaultValue;
        };
        HashTable2.prototype.checkKeyAndValueTensor = function(key, value) {
          if (key.dtype !== this.keyDType) {
            throw new Error("Expect key dtype ".concat(this.keyDType, ", but got ") + "".concat(key.dtype));
          }
          if (value.dtype !== this.valueDType) {
            throw new Error("Expect value dtype ".concat(this.valueDType, ", but got ") + "".concat(value.dtype));
          }
        };
        return HashTable2;
      }()
    );
    var executeOp$c = function(node, tensorMap, context, resourceManager) {
      return __awaiter(void 0, void 0, void 0, function() {
        var _a, existingTableHandle, keyDType, valueDType, hashTable2, handle, keys, values, hashTable2, handle, keys, defaultValue, hashTable2, handle, hashTable2;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              _a = node.op;
              switch (_a) {
                case "HashTable":
                  return [3, 1];
                case "HashTableV2":
                  return [3, 1];
                case "InitializeTable":
                  return [3, 2];
                case "InitializeTableV2":
                  return [3, 2];
                case "LookupTableImport":
                  return [3, 2];
                case "LookupTableImportV2":
                  return [3, 2];
                case "LookupTableFind":
                  return [3, 4];
                case "LookupTableFindV2":
                  return [3, 4];
                case "LookupTableSize":
                  return [3, 6];
                case "LookupTableSizeV2":
                  return [3, 6];
              }
              return [3, 7];
            case 1: {
              existingTableHandle = resourceManager.getHashTableHandleByName(node.name);
              if (existingTableHandle != null) {
                return [2, [existingTableHandle]];
              } else {
                keyDType = getParamValue("keyDType", node, tensorMap, context);
                valueDType = getParamValue("valueDType", node, tensorMap, context);
                hashTable2 = new HashTable(keyDType, valueDType);
                resourceManager.addHashTable(node.name, hashTable2);
                return [2, [hashTable2.handle]];
              }
            }
            case 2:
              handle = getParamValue("tableHandle", node, tensorMap, context, resourceManager);
              keys = getParamValue("keys", node, tensorMap, context);
              values = getParamValue("values", node, tensorMap, context);
              hashTable2 = resourceManager.getHashTableById(handle.id);
              return [4, hashTable2.import(keys, values)];
            case 3:
              return [2, [_b.sent()]];
            case 4:
              handle = getParamValue("tableHandle", node, tensorMap, context, resourceManager);
              keys = getParamValue("keys", node, tensorMap, context);
              defaultValue = getParamValue("defaultValue", node, tensorMap, context);
              hashTable2 = resourceManager.getHashTableById(handle.id);
              return [4, hashTable2.find(keys, defaultValue)];
            case 5:
              return [2, [_b.sent()]];
            case 6: {
              handle = getParamValue("tableHandle", node, tensorMap, context, resourceManager);
              hashTable2 = resourceManager.getHashTableById(handle.id);
              return [2, [hashTable2.tensorSize()]];
            }
            case 7:
              throw TypeError("Node type ".concat(node.op, " is not implemented"));
          }
        });
      });
    };
    var executeOp$b = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "ResizeBilinear": {
          var images = getParamValue("images", node, tensorMap, context);
          var size = getParamValue("size", node, tensorMap, context);
          var alignCorners = getParamValue("alignCorners", node, tensorMap, context);
          var halfPixelCenters = getParamValue("halfPixelCenters", node, tensorMap, context);
          return [ops.image.resizeBilinear(images, [size[0], size[1]], alignCorners, halfPixelCenters)];
        }
        case "ResizeNearestNeighbor": {
          var images = getParamValue("images", node, tensorMap, context);
          var size = getParamValue("size", node, tensorMap, context);
          var alignCorners = getParamValue("alignCorners", node, tensorMap, context);
          var halfPixelCenters = getParamValue("halfPixelCenters", node, tensorMap, context);
          return [ops.image.resizeNearestNeighbor(images, [size[0], size[1]], alignCorners, halfPixelCenters)];
        }
        case "CropAndResize": {
          var image2 = getParamValue("image", node, tensorMap, context);
          var boxes = getParamValue("boxes", node, tensorMap, context);
          var boxInd = getParamValue("boxInd", node, tensorMap, context);
          var cropSize = getParamValue("cropSize", node, tensorMap, context);
          var method = getParamValue("method", node, tensorMap, context);
          var extrapolationValue = getParamValue("extrapolationValue", node, tensorMap, context);
          return [ops.image.cropAndResize(image2, boxes, boxInd, cropSize, method, extrapolationValue)];
        }
        case "ImageProjectiveTransformV3": {
          var images = getParamValue("images", node, tensorMap, context);
          var transforms = getParamValue("transforms", node, tensorMap, context);
          var outputShape = getParamValue("outputShape", node, tensorMap, context);
          var fillValue = getParamValue("fillValue", node, tensorMap, context);
          var interpolation = getParamValue("interpolation", node, tensorMap, context);
          var fillMode = getParamValue("fillMode", node, tensorMap, context);
          return [ops.image.transform(images, transforms, interpolation.toLowerCase(), fillMode.toLowerCase(), fillValue, outputShape)];
        }
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    var executeOp$a = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "Equal": {
          return [ops.equal(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "NotEqual": {
          return [ops.notEqual(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "Greater": {
          return [ops.greater(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "GreaterEqual": {
          return [ops.greaterEqual(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "Less": {
          return [ops.less(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "LessEqual": {
          return [ops.lessEqual(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "LogicalAnd": {
          return [ops.logicalAnd(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "LogicalNot": {
          return [ops.logicalNot(getParamValue("a", node, tensorMap, context))];
        }
        case "LogicalOr": {
          return [ops.logicalOr(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "Select":
        case "SelectV2": {
          return [ops.where(getParamValue("condition", node, tensorMap, context), getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        case "BitwiseAnd": {
          return [ops.bitwiseAnd(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context))];
        }
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    var executeOp$9 = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "BatchMatMul":
        case "BatchMatMulV2":
        case "MatMul":
          return [ops.matMul(getParamValue("a", node, tensorMap, context), getParamValue("b", node, tensorMap, context), getParamValue("transposeA", node, tensorMap, context), getParamValue("transposeB", node, tensorMap, context))];
        case "Einsum":
          return [ops.einsum.apply(ops, __spreadArray([getParamValue("equation", node, tensorMap, context)], __read(getParamValue("tensors", node, tensorMap, context)), false))];
        case "Transpose":
          return [ops.transpose(getParamValue("x", node, tensorMap, context), getParamValue("perm", node, tensorMap, context))];
        case "_FusedMatMul":
          var _a = __read(getParamValue("fusedOps", node, tensorMap, context), 2), extraOp = _a[0], activationFunc = _a[1];
          var isBiasAdd = extraOp === "biasadd";
          var isPrelu = activationFunc === "prelu";
          var numArgs = getParamValue("numArgs", node, tensorMap, context);
          var leakyreluAlpha = getParamValue("leakyreluAlpha", node, tensorMap, context);
          if (isBiasAdd) {
            if (isPrelu && numArgs !== 2) {
              throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");
            }
            if (!isPrelu && numArgs !== 1) {
              throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.");
            }
          }
          var _b = __read(getParamValue("args", node, tensorMap, context), 2), biasArg = _b[0], preluArg = _b[1];
          return [ops.fused.matMul({
            a: getParamValue("a", node, tensorMap, context),
            b: getParamValue("b", node, tensorMap, context),
            transposeA: getParamValue("transposeA", node, tensorMap, context),
            transposeB: getParamValue("transposeB", node, tensorMap, context),
            bias: biasArg,
            activation: activationFunc,
            preluActivationWeights: preluArg,
            leakyreluAlpha
          })];
        case "MatrixBandPart":
          return [ops.linalg.bandPart(getParamValue("a", node, tensorMap, context), getParamValue("numLower", node, tensorMap, context), getParamValue("numUpper", node, tensorMap, context))];
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    var executeOp$8 = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "EuclideanNorm":
          return [ops.euclideanNorm(getParamValue("x", node, tensorMap, context), getParamValue("axis", node, tensorMap, context), getParamValue("keepDims", node, tensorMap, context))];
        case "FusedBatchNorm":
        case "FusedBatchNormV2": {
          return [ops.batchNorm(getParamValue("x", node, tensorMap, context), getParamValue("mean", node, tensorMap, context), getParamValue("variance", node, tensorMap, context), getParamValue("offset", node, tensorMap, context), getParamValue("scale", node, tensorMap, context), getParamValue("epsilon", node, tensorMap, context))];
        }
        case "FusedBatchNormV3": {
          return [ops.batchNorm(getParamValue("x", node, tensorMap, context), getParamValue("mean", node, tensorMap, context), getParamValue("variance", node, tensorMap, context), getParamValue("offset", node, tensorMap, context), getParamValue("scale", node, tensorMap, context), getParamValue("epsilon", node, tensorMap, context))];
        }
        case "LRN": {
          return [ops.localResponseNormalization(getParamValue("x", node, tensorMap, context), getParamValue("radius", node, tensorMap, context), getParamValue("bias", node, tensorMap, context), getParamValue("alpha", node, tensorMap, context), getParamValue("beta", node, tensorMap, context))];
        }
        case "Softmax": {
          return [ops.softmax(getParamValue("x", node, tensorMap, context))];
        }
        case "LogSoftmax": {
          return [ops.logSoftmax(getParamValue("x", node, tensorMap, context))];
        }
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    var executeOp$7 = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "RaggedGather": {
          var _a = ops.raggedGather(getParamValue("paramsNestedSplits", node, tensorMap, context), getParamValue("paramsDenseValues", node, tensorMap, context), getParamValue("indices", node, tensorMap, context), getParamValue("outputRaggedRank", node, tensorMap, context)), outputNestedSplits = _a.outputNestedSplits, outputDenseValues = _a.outputDenseValues;
          return outputNestedSplits.concat(outputDenseValues);
        }
        case "RaggedRange": {
          var _b = ops.raggedRange(getParamValue("starts", node, tensorMap, context), getParamValue("limits", node, tensorMap, context), getParamValue("splits", node, tensorMap, context)), rtNestedSplits = _b.rtNestedSplits, rtDenseValues = _b.rtDenseValues;
          return [rtNestedSplits, rtDenseValues];
        }
        case "RaggedTensorToTensor": {
          return [ops.raggedTensorToTensor(getParamValue("shape", node, tensorMap, context), getParamValue("values", node, tensorMap, context), getParamValue("defaultValue", node, tensorMap, context), getParamValue("rowPartitionTensors", node, tensorMap, context), getParamValue("rowPartitionTypes", node, tensorMap, context))];
        }
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    var executeOp$6 = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "Max": {
          var axis = getParamValue("axis", node, tensorMap, context);
          var keepDims = getParamValue("keepDims", node, tensorMap, context);
          return [ops.max(getParamValue("x", node, tensorMap, context), axis, keepDims)];
        }
        case "Mean": {
          var axis = getParamValue("axis", node, tensorMap, context);
          var keepDims = getParamValue("keepDims", node, tensorMap, context);
          return [ops.mean(getParamValue("x", node, tensorMap, context), axis, keepDims)];
        }
        case "Min": {
          var axis = getParamValue("axis", node, tensorMap, context);
          var keepDims = getParamValue("keepDims", node, tensorMap, context);
          return [ops.min(getParamValue("x", node, tensorMap, context), axis, keepDims)];
        }
        case "Sum": {
          var axis = getParamValue("axis", node, tensorMap, context);
          var keepDims = getParamValue("keepDims", node, tensorMap, context);
          return [ops.sum(getParamValue("x", node, tensorMap, context), axis, keepDims)];
        }
        case "All": {
          var axis = getParamValue("axis", node, tensorMap, context);
          var keepDims = getParamValue("keepDims", node, tensorMap, context);
          return [ops.all(getParamValue("x", node, tensorMap, context), axis, keepDims)];
        }
        case "Any": {
          var axis = getParamValue("axis", node, tensorMap, context);
          var keepDims = getParamValue("keepDims", node, tensorMap, context);
          return [ops.any(getParamValue("x", node, tensorMap, context), axis, keepDims)];
        }
        case "ArgMax": {
          var axis = getParamValue("axis", node, tensorMap, context);
          return [ops.argMax(getParamValue("x", node, tensorMap, context), axis)];
        }
        case "ArgMin": {
          var axis = getParamValue("axis", node, tensorMap, context);
          return [ops.argMin(getParamValue("x", node, tensorMap, context), axis)];
        }
        case "Prod": {
          var axis = getParamValue("axis", node, tensorMap, context);
          var keepDims = getParamValue("keepDims", node, tensorMap, context);
          return [ops.prod(getParamValue("x", node, tensorMap, context), axis, keepDims)];
        }
        case "Cumprod": {
          var axis = getParamValue("axis", node, tensorMap, context);
          var exclusive = getParamValue("exclusive", node, tensorMap, context);
          var reverse2 = getParamValue("reverse", node, tensorMap, context);
          return [ops.cumprod(getParamValue("x", node, tensorMap, context), axis, exclusive, reverse2)];
        }
        case "Cumsum": {
          var axis = getParamValue("axis", node, tensorMap, context);
          var exclusive = getParamValue("exclusive", node, tensorMap, context);
          var reverse2 = getParamValue("reverse", node, tensorMap, context);
          return [ops.cumsum(getParamValue("x", node, tensorMap, context), axis, exclusive, reverse2)];
        }
        case "Bincount":
          var x = getParamValue("x", node, tensorMap, context);
          var weights = getParamValue("weights", node, tensorMap, context);
          var size = getParamValue("size", node, tensorMap, context);
          return [ops.bincount(x, weights, size)];
        case "DenseBincount": {
          var x_1 = getParamValue("x", node, tensorMap, context);
          var weights_1 = getParamValue("weights", node, tensorMap, context);
          var size_1 = getParamValue("size", node, tensorMap, context);
          var binaryOutput = getParamValue("binaryOutput", node, tensorMap, context);
          return [ops.denseBincount(x_1, weights_1, size_1, binaryOutput)];
        }
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    var executeOp$5 = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "ConcatV2":
        case "Concat": {
          var n = getParamValue("n", node, tensorMap, context);
          var axis = getParamValue("axis", node, tensorMap, context);
          var inputs = getParamValue("tensors", node, tensorMap, context);
          inputs = inputs.slice(0, n);
          return [ops.concat(inputs, axis)];
        }
        case "Gather": {
          var input = getParamValue("x", node, tensorMap, context);
          var indices = getParamValue("indices", node, tensorMap, context);
          return [ops.gather(input, ops.cast(indices, "int32"), 0)];
        }
        case "GatherV2": {
          var axis = getParamValue("axis", node, tensorMap, context);
          var batchDims = getParamValue("batchDims", node, tensorMap, context);
          var input = getParamValue("x", node, tensorMap, context);
          var indices = getParamValue("indices", node, tensorMap, context);
          return [ops.gather(input, ops.cast(indices, "int32"), axis, batchDims)];
        }
        case "Reverse": {
          var dims = getParamValue("dims", node, tensorMap, context);
          var axis = [];
          for (var i = 0; i < dims.length; i++) {
            if (dims[i]) {
              axis.push(i);
            }
          }
          var input = getParamValue("x", node, tensorMap, context);
          return [ops.reverse(input, axis)];
        }
        case "ReverseV2": {
          var axis = getParamValue("axis", node, tensorMap, context);
          var input = getParamValue("x", node, tensorMap, context);
          return [ops.reverse(input, axis)];
        }
        case "Slice": {
          var begin = getParamValue("begin", node, tensorMap, context);
          var size = getParamValue("size", node, tensorMap, context);
          return [ops.slice(getParamValue("x", node, tensorMap, context), begin, size)];
        }
        case "StridedSlice": {
          var begin = getParamValue("begin", node, tensorMap, context);
          var end = getParamValue("end", node, tensorMap, context);
          var strides = getParamValue("strides", node, tensorMap, context);
          var beginMask = getParamValue("beginMask", node, tensorMap, context);
          var endMask = getParamValue("endMask", node, tensorMap, context);
          var ellipsisMask = getParamValue("ellipsisMask", node, tensorMap, context);
          var newAxisMask = getParamValue("newAxisMask", node, tensorMap, context);
          var shrinkAxisMask = getParamValue("shrinkAxisMask", node, tensorMap, context);
          var tensor2 = getParamValue("x", node, tensorMap, context);
          return [ops.stridedSlice(tensor2, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask)];
        }
        case "Pack": {
          return tfc.tidy(function() {
            var axis2 = getParamValue("axis", node, tensorMap, context);
            var tensors = getParamValue("tensors", node, tensorMap, context);
            var shape2 = tensors[0].shape;
            var squeezedShape = ops.squeeze(tensors[0]).shape;
            var mapped = tensors.map(function(tensor3) {
              var sameShape = tfc.util.arraysEqual(tensor3.shape, shape2);
              if (!sameShape && !tfc.util.arraysEqual(ops.squeeze(tensor3).shape, squeezedShape)) {
                throw new Error("the input tensors shape does not match");
              }
              return sameShape ? tensor3 : ops.reshape(tensor3, shape2);
            });
            return [ops.stack(mapped, axis2)];
          });
        }
        case "Unpack": {
          var axis = getParamValue("axis", node, tensorMap, context);
          var tensor2 = getParamValue("tensor", node, tensorMap, context);
          return ops.unstack(tensor2, axis);
        }
        case "Tile": {
          var reps = getParamValue("reps", node, tensorMap, context);
          return [ops.tile(getParamValue("x", node, tensorMap, context), reps)];
        }
        case "Split":
        case "SplitV": {
          var axis = getParamValue("axis", node, tensorMap, context);
          var numOrSizeSplits = getParamValue("numOrSizeSplits", node, tensorMap, context);
          var tensor2 = getParamValue("x", node, tensorMap, context);
          return ops.split(tensor2, numOrSizeSplits, axis);
        }
        case "ScatterNd": {
          var indices = getParamValue("indices", node, tensorMap, context);
          var values = getParamValue("values", node, tensorMap, context);
          var shape = getParamValue("shape", node, tensorMap, context);
          return [ops.scatterND(indices, values, shape)];
        }
        case "GatherNd": {
          var x = getParamValue("x", node, tensorMap, context);
          var indices = getParamValue("indices", node, tensorMap, context);
          return [ops.gatherND(x, indices)];
        }
        case "SparseToDense": {
          var indices = getParamValue("sparseIndices", node, tensorMap, context);
          var shape = getParamValue("outputShape", node, tensorMap, context);
          var sparseValues = getParamValue("sparseValues", node, tensorMap, context);
          var defaultValue = getParamValue("defaultValue", node, tensorMap, context);
          return [ops.sparseToDense(indices, sparseValues, shape, sparseValues.dtype === defaultValue.dtype ? defaultValue : ops.cast(defaultValue, sparseValues.dtype))];
        }
        case "TensorScatterUpdate": {
          var indices = getParamValue("indices", node, tensorMap, context);
          var values = getParamValue("values", node, tensorMap, context);
          var tensor2 = getParamValue("tensor", node, tensorMap, context);
          return [ops.tensorScatterUpdate(tensor2, indices, values)];
        }
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    var executeOp$4 = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "SparseFillEmptyRows": {
          var _a = ops.sparse.sparseFillEmptyRows(getParamValue("indices", node, tensorMap, context), getParamValue("values", node, tensorMap, context), getParamValue("denseShape", node, tensorMap, context), getParamValue("defaultValue", node, tensorMap, context)), outputIndices = _a.outputIndices, outputValues = _a.outputValues, emptyRowIndicator = _a.emptyRowIndicator, reverseIndexMap = _a.reverseIndexMap;
          return [
            outputIndices,
            outputValues,
            emptyRowIndicator,
            reverseIndexMap
          ];
        }
        case "SparseReshape": {
          var _b = ops.sparse.sparseReshape(getParamValue("inputIndices", node, tensorMap, context), getParamValue("inputShape", node, tensorMap, context), getParamValue("newShape", node, tensorMap, context)), outputIndices = _b.outputIndices, outputShape = _b.outputShape;
          return [outputIndices, outputShape];
        }
        case "SparseSegmentMean": {
          var outputData = ops.sparse.sparseSegmentMean(getParamValue("data", node, tensorMap, context), getParamValue("indices", node, tensorMap, context), getParamValue("segmentIds", node, tensorMap, context));
          return [outputData];
        }
        case "SparseSegmentSum": {
          var outputData = ops.sparse.sparseSegmentSum(getParamValue("data", node, tensorMap, context), getParamValue("indices", node, tensorMap, context), getParamValue("segmentIds", node, tensorMap, context));
          return [outputData];
        }
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    var executeOp$3 = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "FFT": {
          return [ops.fft(getParamValue("x", node, tensorMap, context))];
        }
        case "IFFT": {
          return [ops.ifft(getParamValue("x", node, tensorMap, context))];
        }
        case "RFFT": {
          return [ops.rfft(getParamValue("x", node, tensorMap, context))];
        }
        case "IRFFT": {
          return [ops.irfft(getParamValue("x", node, tensorMap, context))];
        }
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    var executeOp$2 = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "StaticRegexReplace": {
          return [ops.string.staticRegexReplace(getParamValue("input", node, tensorMap, context), getParamValue("pattern", node, tensorMap, context), getParamValue("rewrite", node, tensorMap, context), getParamValue("replaceGlobal", node, tensorMap, context))];
        }
        case "StringNGrams": {
          var _a = ops.string.stringNGrams(getParamValue("data", node, tensorMap, context), getParamValue("dataSplits", node, tensorMap, context), getParamValue("separator", node, tensorMap, context), getParamValue("nGramWidths", node, tensorMap, context), getParamValue("leftPad", node, tensorMap, context), getParamValue("rightPad", node, tensorMap, context), getParamValue("padWidth", node, tensorMap, context), getParamValue("preserveShortSequences", node, tensorMap, context)), nGrams = _a.nGrams, nGramsSplits = _a.nGramsSplits;
          return [nGrams, nGramsSplits];
        }
        case "StringSplit": {
          var _b = ops.string.stringSplit(getParamValue("input", node, tensorMap, context), getParamValue("delimiter", node, tensorMap, context), getParamValue("skipEmpty", node, tensorMap, context)), indices = _b.indices, values = _b.values, shape = _b.shape;
          return [indices, values, shape];
        }
        case "StringToHashBucketFast": {
          var output = ops.string.stringToHashBucketFast(getParamValue("input", node, tensorMap, context), getParamValue("numBuckets", node, tensorMap, context));
          return [output];
        }
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    var executeOp$1 = function(node, tensorMap, context, ops) {
      if (ops === void 0) {
        ops = tfOps;
      }
      switch (node.op) {
        case "Cast": {
          return [ops.cast(getParamValue("x", node, tensorMap, context), getParamValue("dtype", node, tensorMap, context))];
        }
        case "ExpandDims": {
          var axis = getParamValue("axis", node, tensorMap, context);
          return [ops.expandDims(getParamValue("x", node, tensorMap, context), axis)];
        }
        case "Squeeze": {
          var axis = getParamValue("axis", node, tensorMap, context);
          return [ops.squeeze(getParamValue("x", node, tensorMap, context), axis)];
        }
        case "Reshape": {
          return [ops.reshape(getParamValue("x", node, tensorMap, context), getParamValue("shape", node, tensorMap, context))];
        }
        case "EnsureShape": {
          return [ops.ensureShape(getParamValue("x", node, tensorMap, context), getParamValue("shape", node, tensorMap, context))];
        }
        case "MirrorPad": {
          return [ops.mirrorPad(getParamValue("x", node, tensorMap, context), getParamValue("padding", node, tensorMap, context), getParamValue("mode", node, tensorMap, context))];
        }
        case "PadV2":
        case "Pad": {
          return [ops.pad(getParamValue("x", node, tensorMap, context), getParamValue("padding", node, tensorMap, context), getParamValue("constantValue", node, tensorMap, context))];
        }
        case "SpaceToBatchND": {
          var blockShape = getParamValue("blockShape", node, tensorMap, context);
          var paddings = getParamValue("paddings", node, tensorMap, context);
          return [ops.spaceToBatchND(getParamValue("x", node, tensorMap, context), blockShape, paddings)];
        }
        case "BatchToSpaceND": {
          var blockShape = getParamValue("blockShape", node, tensorMap, context);
          var crops = getParamValue("crops", node, tensorMap, context);
          return [ops.batchToSpaceND(getParamValue("x", node, tensorMap, context), blockShape, crops)];
        }
        case "DepthToSpace": {
          var blockSize = getParamValue("blockSize", node, tensorMap, context);
          var dataFormat = getParamValue("dataFormat", node, tensorMap, context).toUpperCase();
          return [ops.depthToSpace(getParamValue("x", node, tensorMap, context), blockSize, dataFormat)];
        }
        case "BroadcastTo": {
          return [ops.broadcastTo(getParamValue("x", node, tensorMap, context), getParamValue("shape", node, tensorMap, context))];
        }
        case "BroadcastArgs": {
          return [ops.broadcastArgs(getParamValue("s0", node, tensorMap, context), getParamValue("s1", node, tensorMap, context))];
        }
        default:
          throw TypeError("Node type ".concat(node.op, " is not implemented"));
      }
    };
    function executeOp(node, tensorMap, context, resourceManager, tidy2) {
      if (tidy2 === void 0) {
        tidy2 = tfc__namespace.tidy;
      }
      var value = function(node2, tensorMap2, context2) {
        switch (node2.category) {
          case "arithmetic":
            return tidy2(function() {
              return executeOp$k(node2, tensorMap2, context2);
            });
          case "basic_math":
            return tidy2(function() {
              return executeOp$j(node2, tensorMap2, context2);
            });
          case "control":
            return executeOp$i(node2, tensorMap2, context2);
          case "convolution":
            return tidy2(function() {
              return executeOp$h(node2, tensorMap2, context2);
            });
          case "creation":
            return tidy2(function() {
              return executeOp$g(node2, tensorMap2, context2);
            });
          case "dynamic":
            return executeOp$f(node2, tensorMap2, context2);
          case "evaluation":
            return tidy2(function() {
              return executeOp$e(node2, tensorMap2, context2);
            });
          case "image":
            return tidy2(function() {
              return executeOp$b(node2, tensorMap2, context2);
            });
          case "graph":
            return tidy2(function() {
              return executeOp$d(node2, tensorMap2, context2);
            });
          case "logical":
            return tidy2(function() {
              return executeOp$a(node2, tensorMap2, context2);
            });
          case "matrices":
            return tidy2(function() {
              return executeOp$9(node2, tensorMap2, context2);
            });
          case "normalization":
            return tidy2(function() {
              return executeOp$8(node2, tensorMap2, context2);
            });
          case "ragged":
            return tidy2(function() {
              return executeOp$7(node2, tensorMap2, context2);
            });
          case "reduction":
            return tidy2(function() {
              return executeOp$6(node2, tensorMap2, context2);
            });
          case "slice_join":
            return tidy2(function() {
              return executeOp$5(node2, tensorMap2, context2);
            });
          case "sparse":
            return tidy2(function() {
              return executeOp$4(node2, tensorMap2, context2);
            });
          case "spectral":
            return tidy2(function() {
              return executeOp$3(node2, tensorMap2, context2);
            });
          case "string":
            return tidy2(function() {
              return executeOp$2(node2, tensorMap2, context2);
            });
          case "transformation":
            return tidy2(function() {
              return executeOp$1(node2, tensorMap2, context2);
            });
          case "hash_table":
            return executeOp$c(node2, tensorMap2, context2, resourceManager);
          case "custom":
            var opMapper = getRegisteredOp(node2.op);
            if (opMapper && opMapper.customExecutor) {
              return opMapper.customExecutor(new NodeValueImpl(node2, tensorMap2, context2));
            } else {
              throw TypeError("Custom op ".concat(node2.op, " is not registered."));
            }
          default:
            throw TypeError("Unknown op '".concat(node2.op, "'. File an issue at ") + "https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()");
        }
      }(node, tensorMap, context);
      if (tfc__namespace.util.isPromise(value)) {
        return value.then(function(data) {
          return [].concat(data);
        });
      }
      return [].concat(value);
    }
    var ExecutionContext = (
      /** @class */
      function() {
        function ExecutionContext2(weightMap, tensorArrayMap, tensorListMap, functionMap, parseNodeNameCache) {
          if (weightMap === void 0) {
            weightMap = {};
          }
          if (tensorArrayMap === void 0) {
            tensorArrayMap = {};
          }
          if (tensorListMap === void 0) {
            tensorListMap = {};
          }
          if (functionMap === void 0) {
            functionMap = {};
          }
          this.weightMap = weightMap;
          this.tensorArrayMap = tensorArrayMap;
          this.tensorListMap = tensorListMap;
          this.functionMap = functionMap;
          this.parseNodeNameCache = parseNodeNameCache;
          this.rootContext = { id: 0, frameName: "", iterationId: 0 };
          this.contexts = [this.rootContext];
          this.lastId = 0;
          this.generateCurrentContextIds();
        }
        ExecutionContext2.prototype.newFrame = function(id, frameName) {
          return { id, frameName, iterationId: 0 };
        };
        Object.defineProperty(ExecutionContext2.prototype, "currentContext", {
          get: function() {
            return this.contexts;
          },
          /**
           * Set the current context
           * @param contexts: ExecutionContextInfo[] the current path of execution
           * frames
           */
          set: function(contexts) {
            if (this.contexts !== contexts) {
              this.contexts = contexts;
              this.generateCurrentContextIds();
            }
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(ExecutionContext2.prototype, "currentContextId", {
          /**
           * Returns the current context in string format.
           */
          get: function() {
            return this._currentContextIds[0];
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(ExecutionContext2.prototype, "currentContextIds", {
          /**
           * Returns the current context and all parent contexts in string format.
           * This allow access to the nodes in the current and parent frames.
           */
          get: function() {
            return this._currentContextIds;
          },
          enumerable: false,
          configurable: true
        });
        ExecutionContext2.prototype.generateCurrentContextIds = function() {
          var names = [];
          for (var i = 0; i < this.contexts.length - 1; i++) {
            var contexts = this.contexts.slice(0, this.contexts.length - i);
            names.push(this.contextIdforContexts(contexts));
          }
          names.push("");
          this._currentContextIds = names;
        };
        ExecutionContext2.prototype.contextIdforContexts = function(contexts) {
          return contexts ? contexts.map(function(context) {
            return context.id === 0 && context.iterationId === 0 ? "" : "".concat(context.frameName, "-").concat(context.iterationId);
          }).join("/") : "";
        };
        ExecutionContext2.prototype.enterFrame = function(frameId) {
          if (this.contexts) {
            this.lastId++;
            this.contexts = this.contexts.slice();
            this.contexts.push(this.newFrame(this.lastId, frameId));
            this._currentContextIds.unshift(this.contextIdforContexts(this.contexts));
          }
        };
        ExecutionContext2.prototype.exitFrame = function() {
          if (this.contexts && this.contexts.length > 1) {
            this.contexts = this.contexts.slice();
            this.contexts.splice(-1);
            this.currentContextIds.shift();
          } else {
            throw new Error("Cannot exit frame, the context is empty");
          }
        };
        ExecutionContext2.prototype.nextIteration = function() {
          if (this.contexts && this.contexts.length > 0) {
            this.contexts = this.contexts.slice();
            this.lastId++;
            var context = Object.assign({}, this.contexts[this.contexts.length - 1]);
            context.iterationId += 1;
            context.id = this.lastId;
            this.contexts.splice(-1, 1, context);
            this._currentContextIds.splice(0, 1, this.contextIdforContexts(this.contexts));
          } else {
            throw new Error("Cannot increase frame iteration, the context is empty");
          }
        };
        ExecutionContext2.prototype.getWeight = function(name) {
          return this.weightMap[name];
        };
        ExecutionContext2.prototype.addTensorArray = function(tensorArray) {
          this.tensorArrayMap[tensorArray.id] = tensorArray;
        };
        ExecutionContext2.prototype.getTensorArray = function(id) {
          return this.tensorArrayMap[id];
        };
        ExecutionContext2.prototype.addTensorList = function(tensorList) {
          this.tensorListMap[tensorList.id] = tensorList;
        };
        ExecutionContext2.prototype.getTensorList = function(id) {
          return this.tensorListMap[id];
        };
        ExecutionContext2.prototype.dispose = function(keepIds) {
          for (var key in this.tensorArrayMap) {
            this.tensorArrayMap[key].clearAndClose(keepIds);
          }
          for (var key in this.tensorListMap) {
            this.tensorListMap[key].clearAndClose(keepIds);
          }
        };
        return ExecutionContext2;
      }()
    );
    function getExecutionSubgraph(inputs, outputs, weightMap, initNodes) {
      var usedNodes = /* @__PURE__ */ new Set();
      var missingInputs = [];
      var dynamicNode = null;
      var syncInputs = null;
      var seen = /* @__PURE__ */ new Set();
      var inputNodeNames = new Set(Object.keys(inputs).map(function(name) {
        return parseNodeName(name)[0];
      }));
      initNodes = initNodes || [];
      var initNodeNames = new Set(initNodes.map(function(node2) {
        return parseNodeName(node2.name)[0];
      }));
      var frontier = __spreadArray([], __read(outputs), false);
      while (frontier.length > 0) {
        var node = frontier.pop();
        if (isControlFlow(node) || isDynamicShape(node) || isHashTable(node)) {
          if (dynamicNode == null) {
            dynamicNode = node;
            syncInputs = dynamicNode.children.map(function(child) {
              return child.name;
            }).filter(function(name) {
              return usedNodes.has(name);
            });
          }
        }
        usedNodes.add(node.name);
        if (weightMap[node.name] != null) {
          continue;
        }
        if (inputNodeNames.has(node.name)) {
          continue;
        }
        if (initNodeNames.has(node.name)) {
          continue;
        }
        if (node.inputs.length === 0) {
          missingInputs.push(node.name);
          continue;
        }
        node.inputs.forEach(function(input) {
          if (seen.has(input.name)) {
            return;
          }
          seen.add(input.name);
          frontier.push(input);
        });
      }
      return { inputs, outputs, usedNodes, missingInputs, dynamicNode, syncInputs };
    }
    function getNodesInTopologicalOrder(graph2, executionInfo) {
      var e_1, _a, e_2, _b, e_3, _c;
      var usedNodes = executionInfo.usedNodes, inputs = executionInfo.inputs;
      var inputNodes = Object.keys(inputs).map(function(name) {
        return parseNodeName(name)[0];
      }).map(function(name) {
        return graph2.nodes[name];
      });
      var initNodes = graph2.initNodes || [];
      var isUsed = function(node2) {
        return usedNodes.has(typeof node2 === "string" ? node2 : node2.name);
      };
      function unique2(nodes) {
        return __spreadArray([], __read(new Map(nodes.map(function(node2) {
          return [node2.name, node2];
        })).values()), false);
      }
      var predefinedNodes = unique2(__spreadArray(__spreadArray(__spreadArray([], __read(inputNodes), false), __read(graph2.weights), false), __read(initNodes), false)).filter(isUsed);
      var allNodes = unique2(__spreadArray(__spreadArray([], __read(predefinedNodes), false), __read(Object.values(graph2.nodes)), false)).filter(isUsed);
      var nameToNode = new Map(allNodes.map(function(node2) {
        return [node2.name, node2];
      }));
      var inCounts = {};
      try {
        for (var allNodes_1 = __values(allNodes), allNodes_1_1 = allNodes_1.next(); !allNodes_1_1.done; allNodes_1_1 = allNodes_1.next()) {
          var node = allNodes_1_1.value;
          inCounts[node.name] = inCounts[node.name] || 0;
          try {
            for (var _d = (e_2 = void 0, __values(node.children)), _e = _d.next(); !_e.done; _e = _d.next()) {
              var child = _e.value;
              if (!isUsed(child)) {
                inCounts[child.name] = Number.POSITIVE_INFINITY;
              }
              inCounts[child.name] = (inCounts[child.name] || 0) + 1;
            }
          } catch (e_2_1) {
            e_2 = { error: e_2_1 };
          } finally {
            try {
              if (_e && !_e.done && (_b = _d.return)) _b.call(_d);
            } finally {
              if (e_2) throw e_2.error;
            }
          }
        }
      } catch (e_1_1) {
        e_1 = { error: e_1_1 };
      } finally {
        try {
          if (allNodes_1_1 && !allNodes_1_1.done && (_a = allNodes_1.return)) _a.call(allNodes_1);
        } finally {
          if (e_1) throw e_1.error;
        }
      }
      var frontier = Object.entries(inCounts).filter(function(_a2) {
        var _b2 = __read(_a2, 2), inCount = _b2[1];
        return inCount === 0;
      }).map(function(_a2) {
        var _b2 = __read(_a2, 1), name = _b2[0];
        return name;
      });
      var orderedNodeNames = __spreadArray([], __read(frontier), false);
      while (frontier.length > 0) {
        var nodeName = frontier.pop();
        var node = nameToNode.get(nodeName);
        try {
          for (var _f = (e_3 = void 0, __values(node.children.filter(isUsed))), _g = _f.next(); !_g.done; _g = _f.next()) {
            var child = _g.value;
            if (--inCounts[child.name] === 0) {
              orderedNodeNames.push(child.name);
              frontier.push(child.name);
            }
          }
        } catch (e_3_1) {
          e_3 = { error: e_3_1 };
        } finally {
          try {
            if (_g && !_g.done && (_c = _f.return)) _c.call(_f);
          } finally {
            if (e_3) throw e_3.error;
          }
        }
      }
      var orderedNodes = orderedNodeNames.map(function(name) {
        return nameToNode.get(name);
      });
      var filteredOrderedNodes = filterPredefinedReachableNodes(orderedNodes, predefinedNodes);
      validateNodesExecutionOrder(filteredOrderedNodes, predefinedNodes);
      return filteredOrderedNodes;
    }
    function filterPredefinedReachableNodes(orderedNodes, predefinedNodes) {
      var e_4, _a;
      var nameToNode = new Map(orderedNodes.map(function(node2) {
        return [node2.name, node2];
      }));
      var stack2 = predefinedNodes.map(function(node2) {
        return node2.name;
      });
      var predefinedReachableNodeNames = new Set(stack2);
      while (stack2.length > 0) {
        var nodeName = stack2.pop();
        var node = nameToNode.get(nodeName);
        try {
          for (var _b = (e_4 = void 0, __values(node.children)), _c = _b.next(); !_c.done; _c = _b.next()) {
            var child = _c.value;
            if (!nameToNode.has(child.name) || predefinedReachableNodeNames.has(child.name)) {
              continue;
            }
            predefinedReachableNodeNames.add(child.name);
            stack2.push(child.name);
          }
        } catch (e_4_1) {
          e_4 = { error: e_4_1 };
        } finally {
          try {
            if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
          } finally {
            if (e_4) throw e_4.error;
          }
        }
      }
      var filteredOrderedNodes = orderedNodes.filter(function(node2) {
        return predefinedReachableNodeNames.has(node2.name);
      });
      return filteredOrderedNodes;
    }
    var NodesExecutionOrderError = (
      /** @class */
      function(_super) {
        __extends(NodesExecutionOrderError2, _super);
        function NodesExecutionOrderError2(message) {
          return _super.call(this, "NodesExecutionOrderError: ".concat(message)) || this;
        }
        return NodesExecutionOrderError2;
      }(Error)
    );
    function validateNodesExecutionOrder(orderedNodes, predefinedNodes) {
      var e_5, _a, e_6, _b, e_7, _c;
      var nodeNameToOrder = new Map(orderedNodes.map(function(node2, order) {
        return [node2.name, order];
      }));
      var predefinedNodeNames = new Set(predefinedNodes.map(function(node2) {
        return node2.name;
      }));
      var isPredefined = function(node2) {
        return predefinedNodeNames.has(typeof node2 === "string" ? node2 : node2.name);
      };
      var willBeExecutedNodeNames = new Set(orderedNodes.map(function(node2) {
        return node2.name;
      }));
      var willBeExecuted = function(node2) {
        return willBeExecutedNodeNames.has(typeof node2 === "string" ? node2 : node2.name);
      };
      try {
        for (var orderedNodes_1 = __values(orderedNodes), orderedNodes_1_1 = orderedNodes_1.next(); !orderedNodes_1_1.done; orderedNodes_1_1 = orderedNodes_1.next()) {
          var node = orderedNodes_1_1.value;
          try {
            for (var _d = (e_6 = void 0, __values(node.children.filter(willBeExecuted))), _e = _d.next(); !_e.done; _e = _d.next()) {
              var child = _e.value;
              if (!nodeNameToOrder.has(child.name)) {
                throw new NodesExecutionOrderError("Child ".concat(child.name, " of node ").concat(node.name, " is unreachable."));
              }
              if (nodeNameToOrder.get(node.name) > nodeNameToOrder.get(child.name)) {
                throw new NodesExecutionOrderError("Node ".concat(node.name, " is scheduled to run after its child ").concat(child.name, "."));
              }
            }
          } catch (e_6_1) {
            e_6 = { error: e_6_1 };
          } finally {
            try {
              if (_e && !_e.done && (_b = _d.return)) _b.call(_d);
            } finally {
              if (e_6) throw e_6.error;
            }
          }
          if (!isPredefined(node)) {
            try {
              for (var _f = (e_7 = void 0, __values(node.inputs)), _g = _f.next(); !_g.done; _g = _f.next()) {
                var input = _g.value;
                if (!nodeNameToOrder.has(input.name)) {
                  throw new NodesExecutionOrderError("Input ".concat(input.name, " of node ").concat(node.name, " is unreachable."));
                }
                if (nodeNameToOrder.get(input.name) > nodeNameToOrder.get(node.name)) {
                  throw new NodesExecutionOrderError("Node ".concat(node.name, " is scheduled to run before its input ").concat(input.name, "."));
                }
              }
            } catch (e_7_1) {
              e_7 = { error: e_7_1 };
            } finally {
              try {
                if (_g && !_g.done && (_c = _f.return)) _c.call(_f);
              } finally {
                if (e_7) throw e_7.error;
              }
            }
          }
        }
      } catch (e_5_1) {
        e_5 = { error: e_5_1 };
      } finally {
        try {
          if (orderedNodes_1_1 && !orderedNodes_1_1.done && (_a = orderedNodes_1.return)) _a.call(orderedNodes_1);
        } finally {
          if (e_5) throw e_5.error;
        }
      }
    }
    function getNodeLiveUntilMap(orderedNodes) {
      var nodeNameToOrder = new Map(orderedNodes.map(function(node2, order) {
        return [node2.name, order];
      }));
      var INF_LIFE = Number.MAX_SAFE_INTEGER;
      var selfLifespans = orderedNodes.map(function(node2, nodeOrder2) {
        return isControlFlow(node2) ? INF_LIFE : nodeOrder2;
      });
      var getSelfLifeSpan = function(node2) {
        var selfLife = selfLifespans[nodeNameToOrder.get(node2.name)];
        if (selfLife == null) {
          return -1;
        }
        return selfLife;
      };
      var liveUntilOrders = orderedNodes.map(function(node2, nodeOrder2) {
        return node2.children.map(getSelfLifeSpan).reduce(function(a, b) {
          return Math.max(a, b);
        }, selfLifespans[nodeOrder2]);
      });
      var liveUntilMap = /* @__PURE__ */ new Map();
      for (var nodeOrder = 0; nodeOrder < orderedNodes.length; ++nodeOrder) {
        var liveUntilOrder = liveUntilOrders[nodeOrder];
        if (liveUntilOrder === INF_LIFE) {
          continue;
        }
        var node = orderedNodes[nodeOrder];
        var liveUntilNode = orderedNodes[liveUntilOrder];
        if (!liveUntilMap.has(liveUntilNode.name)) {
          liveUntilMap.set(liveUntilNode.name, []);
        }
        liveUntilMap.get(liveUntilNode.name).push(node);
      }
      return liveUntilMap;
    }
    var CONTROL_FLOW_OPS = /* @__PURE__ */ new Set([
      "Switch",
      "Merge",
      "Enter",
      "Exit",
      "NextIteration",
      "StatelessIf",
      "StatelessWhile",
      "if",
      "While"
    ]);
    var DYNAMIC_SHAPE_OPS = /* @__PURE__ */ new Set([
      "NonMaxSuppressionV2",
      "NonMaxSuppressionV3",
      "NonMaxSuppressionV5",
      "Where"
    ]);
    var HASH_TABLE_OPS = /* @__PURE__ */ new Set([
      "HashTable",
      "HashTableV2",
      "LookupTableImport",
      "LookupTableImportV2",
      "LookupTableFind",
      "LookupTableFindV2",
      "LookupTableSize",
      "LookupTableSizeV2"
    ]);
    function isControlFlow(node) {
      return CONTROL_FLOW_OPS.has(node.op);
    }
    function isDynamicShape(node) {
      return DYNAMIC_SHAPE_OPS.has(node.op);
    }
    function isHashTable(node) {
      return HASH_TABLE_OPS.has(node.op);
    }
    var GraphExecutor = (
      /** @class */
      function() {
        function GraphExecutor2(graph2, parent) {
          var _this = this;
          this.graph = graph2;
          this.parent = parent;
          this.compiledMap = /* @__PURE__ */ new Map();
          this.parseNodeNameCache = /* @__PURE__ */ new Map();
          this._weightMap = {};
          this.SEPARATOR = ",";
          this._functions = {};
          this._functionExecutorMap = {};
          this.keepIntermediateTensors = false;
          this._outputs = graph2.outputs;
          this._inputs = graph2.inputs;
          this._initNodes = graph2.initNodes;
          this._signature = graph2.signature;
          this._functions = graph2.functions;
          if (graph2.functions != null) {
            Object.keys(graph2.functions).forEach(function(name) {
              _this._functionExecutorMap[name] = new GraphExecutor2(graph2.functions[name], _this);
            });
          }
        }
        Object.defineProperty(GraphExecutor2.prototype, "weightIds", {
          get: function() {
            return this.parent ? this.parent.weightIds : this._weightIds;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(GraphExecutor2.prototype, "functionExecutorMap", {
          get: function() {
            return this.parent ? this.parent.functionExecutorMap : this._functionExecutorMap;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(GraphExecutor2.prototype, "weightMap", {
          get: function() {
            return this.parent ? this.parent.weightMap : this._weightMap;
          },
          set: function(weightMap) {
            var weightIds = Object.keys(weightMap).map(function(key) {
              return weightMap[key].map(function(tensor2) {
                return tensor2.id;
              });
            });
            this._weightIds = [].concat.apply([], __spreadArray([], __read(weightIds), false));
            this._weightMap = weightMap;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(GraphExecutor2.prototype, "resourceManager", {
          /**
           * Set `ResourceManager` shared by executors of a model.
           * @param resourceManager: `ResourceManager` of the `GraphModel`.
           */
          set: function(resourceManager) {
            this._resourceManager = resourceManager;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(GraphExecutor2.prototype, "inputs", {
          get: function() {
            return this._inputs.map(function(node) {
              return {
                name: node.name,
                shape: node.attrParams["shape"] ? node.attrParams["shape"].value : void 0,
                dtype: node.attrParams["dtype"] ? node.attrParams["dtype"].value : void 0
              };
            });
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(GraphExecutor2.prototype, "outputs", {
          get: function() {
            return this._outputs.map(function(node) {
              return {
                name: node.name,
                shape: node.attrParams["shape"] ? node.attrParams["shape"].value : void 0,
                dtype: node.attrParams["dtype"] ? node.attrParams["dtype"].value : void 0
              };
            });
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(GraphExecutor2.prototype, "inputNodes", {
          get: function() {
            return this._inputs.map(function(node) {
              return node.signatureKey || node.name;
            });
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(GraphExecutor2.prototype, "outputNodes", {
          get: function() {
            return this._outputs.map(function(node) {
              var name = node.signatureKey || node.name;
              return node.defaultOutput ? "".concat(name, ":").concat(node.defaultOutput) : name;
            });
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(GraphExecutor2.prototype, "functions", {
          get: function() {
            var _this = this;
            return Object.keys(this._functions).reduce(function(map, key) {
              map[key] = _this._functions[key].signature;
              return map;
            }, {});
          },
          enumerable: false,
          configurable: true
        });
        GraphExecutor2.prototype.getCompilationKey = function(inputs, outputs) {
          var sortedInputs = inputs.map(function(node) {
            return node.name;
          }).sort();
          var sortedOutputs = outputs.map(function(node) {
            return node.name;
          }).sort();
          return sortedInputs.join(this.SEPARATOR) + "--" + sortedOutputs.join(this.SEPARATOR);
        };
        GraphExecutor2.prototype.compile = function(inputs, outputs) {
          var executionInfo = getExecutionSubgraph(inputs, outputs, this.weightMap, this._initNodes);
          var missingInputs = executionInfo.missingInputs, dynamicNode = executionInfo.dynamicNode, syncInputs = executionInfo.syncInputs;
          if (dynamicNode != null) {
            throw new Error("This execution contains the node '".concat(dynamicNode.name, "', which has ") + "the dynamic op '".concat(dynamicNode.op, "'. Please use ") + "model.executeAsync() instead. Alternatively, to avoid the " + "dynamic ops, specify the inputs [".concat(syncInputs, "]"));
          }
          if (missingInputs.length > 0) {
            var outNames = outputs.map(function(n) {
              return n.name;
            });
            var inNames = Object.keys(inputs);
            throw new Error("Cannot compute the outputs [".concat(outNames, "] from the provided inputs ") + "[".concat(inNames, "]. Missing the following inputs: [").concat(missingInputs, "]"));
          }
          var orderedNodes = getNodesInTopologicalOrder(this.graph, executionInfo);
          var nodeLiveUntilMap = getNodeLiveUntilMap(orderedNodes);
          return { orderedNodes, nodeLiveUntilMap };
        };
        GraphExecutor2.prototype.cloneAndKeepTensor = function(tensor2) {
          if (tensor2 == null) {
            return null;
          }
          var clone2 = tensor2.clone();
          tfc.keep(clone2);
          return clone2;
        };
        GraphExecutor2.prototype.cloneTensorList = function(tensors) {
          var _this = this;
          if (!tensors) {
            return null;
          }
          var clonedTensor = tensors.map(function(tensor2) {
            return _this.cloneAndKeepTensor(tensor2);
          });
          return clonedTensor;
        };
        GraphExecutor2.prototype.cloneTensorMap = function(tensorsMap) {
          var _this = this;
          return Object.fromEntries(Object.entries(tensorsMap).map(function(_c) {
            var _d = __read(_c, 2), name = _d[0], tensorsList = _d[1];
            return [name, _this.cloneTensorList(tensorsList)];
          }));
        };
        GraphExecutor2.prototype.execute = function(inputs, outputs) {
          var _this = this;
          this.disposeIntermediateTensors();
          inputs = this.mapInputs(inputs);
          var names = Object.keys(inputs).sort();
          this.checkInputs(inputs);
          this.checkInputShapeAndType(inputs);
          outputs = this.mapOutputs(outputs);
          this.checkOutputs(outputs);
          var inputNodes = names.map(function(name) {
            return _this.graph.nodes[parseNodeName(name)[0]];
          });
          var outputNodeNames = outputs.map(function(name) {
            return parseNodeName(name)[0];
          });
          var outputNodeNameSet = new Set(outputNodeNames);
          var outputNodes = outputNodeNames.map(function(name) {
            return _this.graph.nodes[name];
          });
          if (outputNodes.length === 0) {
            outputNodes = this._outputs;
          }
          var compilationKey = this.getCompilationKey(inputNodes, outputNodes);
          var compilation = this.compiledMap.get(compilationKey);
          if (compilation == null) {
            compilation = this.compile(inputs, outputNodes);
            this.compiledMap.set(compilationKey, compilation);
          }
          try {
            this.keepIntermediateTensors = tfc.env().getBool("KEEP_INTERMEDIATE_TENSORS");
          } catch (e) {
            this.keepIntermediateTensors = false;
            console.warn(e.message);
          }
          var tensorArrayMap = {};
          var tensorListMap = {};
          return tfc.tidy(function() {
            var e_1, _c;
            var context = new ExecutionContext(_this.weightMap, tensorArrayMap, tensorListMap, _this.functionExecutorMap, _this.parseNodeNameCache);
            var tensorsMap = Object.assign({}, _this.weightMap);
            if (_this.keepIntermediateTensors) {
              _this.clonedTensorsMap = _this.cloneTensorMap(_this.weightMap);
            }
            Object.keys(inputs).forEach(function(name) {
              var _c2 = __read(parseNodeName(name, context), 2), nodeName = _c2[0], index = _c2[1];
              var tensors2 = [];
              tensors2[index] = inputs[name];
              tensorsMap[nodeName] = tensors2;
              if (_this.keepIntermediateTensors) {
                _this.clonedTensorsMap[nodeName] = _this.cloneTensorList(tensors2);
              }
            });
            var tensorsToKeep = _this.getFrozenTensorIds(tensorsMap);
            var orderedNodes = compilation.orderedNodes, nodeLiveUntilMap = compilation.nodeLiveUntilMap;
            try {
              for (var orderedNodes_1 = __values(orderedNodes), orderedNodes_1_1 = orderedNodes_1.next(); !orderedNodes_1_1.done; orderedNodes_1_1 = orderedNodes_1.next()) {
                var node = orderedNodes_1_1.value;
                if (tensorsMap[node.name]) {
                  continue;
                }
                var tensors = executeOp(node, tensorsMap, context, _this._resourceManager);
                if (tfc.util.isPromise(tensors)) {
                  throw new Error("The execution of the op '".concat(node.op, "' returned a promise. ") + "Please use model.executeAsync() instead.");
                }
                tensorsMap[node.name] = tensors;
                if (_this.keepIntermediateTensors) {
                  _this.clonedTensorsMap[node.name] = _this.cloneTensorList(tensors);
                }
                _this.checkTensorForDisposalWithNodeLiveUntilInfo(node, tensorsMap, context, tensorsToKeep, outputNodeNameSet, nodeLiveUntilMap.get(node.name));
              }
            } catch (e_1_1) {
              e_1 = { error: e_1_1 };
            } finally {
              try {
                if (orderedNodes_1_1 && !orderedNodes_1_1.done && (_c = orderedNodes_1.return)) _c.call(orderedNodes_1);
              } finally {
                if (e_1) throw e_1.error;
              }
            }
            if (_this.parent == null) {
              context.dispose(tensorsToKeep);
            }
            return outputs.map(function(name) {
              return getTensor(name, tensorsMap, context);
            });
          });
        };
        GraphExecutor2.prototype.getFrozenTensorIds = function(tensorMap) {
          var ids = [].concat.apply([], Object.keys(tensorMap).map(function(key) {
            return tensorMap[key];
          }).map(function(tensors) {
            return tensors.map(function(tensor2) {
              return tensor2.id;
            });
          }));
          return new Set(ids);
        };
        GraphExecutor2.prototype.checkTensorForDisposal = function(nodeName, node, tensorMap, context, tensorsToKeep, outputNodeNameSet, intermediateTensorConsumerCount) {
          var e_2, _c, e_3, _d, e_4, _e;
          if (isControlFlow(node) || outputNodeNameSet.has(nodeName)) {
            return;
          }
          try {
            for (var _f = __values(tensorMap[nodeName]), _g = _f.next(); !_g.done; _g = _f.next()) {
              var tensor2 = _g.value;
              if (tensor2 == null) {
                continue;
              }
              intermediateTensorConsumerCount[tensor2.id] = (intermediateTensorConsumerCount[tensor2.id] || 0) + node.children.length;
            }
          } catch (e_2_1) {
            e_2 = { error: e_2_1 };
          } finally {
            try {
              if (_g && !_g.done && (_c = _f.return)) _c.call(_f);
            } finally {
              if (e_2) throw e_2.error;
            }
          }
          try {
            for (var _h = __values(node.inputs), _j = _h.next(); !_j.done; _j = _h.next()) {
              var input = _j.value;
              if (isControlFlow(input)) {
                continue;
              }
              var tensors = getTensorsForCurrentContext(input.name, tensorMap, context);
              if (tensors == null) {
                continue;
              }
              try {
                for (var tensors_1 = (e_4 = void 0, __values(tensors)), tensors_1_1 = tensors_1.next(); !tensors_1_1.done; tensors_1_1 = tensors_1.next()) {
                  var tensor2 = tensors_1_1.value;
                  if (!tensor2 || tensor2.kept || tensorsToKeep.has(tensor2.id)) {
                    continue;
                  }
                  var count = intermediateTensorConsumerCount[tensor2.id];
                  if (count === 1) {
                    tensor2.dispose();
                    delete intermediateTensorConsumerCount[tensor2.id];
                  } else if (count != null) {
                    intermediateTensorConsumerCount[tensor2.id]--;
                  }
                }
              } catch (e_4_1) {
                e_4 = { error: e_4_1 };
              } finally {
                try {
                  if (tensors_1_1 && !tensors_1_1.done && (_e = tensors_1.return)) _e.call(tensors_1);
                } finally {
                  if (e_4) throw e_4.error;
                }
              }
            }
          } catch (e_3_1) {
            e_3 = { error: e_3_1 };
          } finally {
            try {
              if (_j && !_j.done && (_d = _h.return)) _d.call(_h);
            } finally {
              if (e_3) throw e_3.error;
            }
          }
        };
        GraphExecutor2.prototype.checkTensorForDisposalWithNodeLiveUntilInfo = function(node, tensorMap, context, tensorsToKeep, outputNodeNameSet, liveUntilNodes) {
          var e_5, _c, e_6, _d;
          function isNonDisposableNode(node2) {
            return isControlFlow(node2) || outputNodeNameSet.has(node2.name);
          }
          if (isControlFlow(node) || liveUntilNodes == null) {
            return;
          }
          try {
            for (var liveUntilNodes_1 = __values(liveUntilNodes), liveUntilNodes_1_1 = liveUntilNodes_1.next(); !liveUntilNodes_1_1.done; liveUntilNodes_1_1 = liveUntilNodes_1.next()) {
              var nodeToDispose = liveUntilNodes_1_1.value;
              if (isNonDisposableNode(nodeToDispose)) {
                continue;
              }
              var tensors = getTensorsForCurrentContext(nodeToDispose.name, tensorMap, context);
              try {
                for (var tensors_2 = (e_6 = void 0, __values(tensors)), tensors_2_1 = tensors_2.next(); !tensors_2_1.done; tensors_2_1 = tensors_2.next()) {
                  var tensor2 = tensors_2_1.value;
                  if (!tensor2 || tensor2.kept || tensorsToKeep.has(tensor2.id)) {
                    continue;
                  }
                  tensor2.dispose();
                }
              } catch (e_6_1) {
                e_6 = { error: e_6_1 };
              } finally {
                try {
                  if (tensors_2_1 && !tensors_2_1.done && (_d = tensors_2.return)) _d.call(tensors_2);
                } finally {
                  if (e_6) throw e_6.error;
                }
              }
            }
          } catch (e_5_1) {
            e_5 = { error: e_5_1 };
          } finally {
            try {
              if (liveUntilNodes_1_1 && !liveUntilNodes_1_1.done && (_c = liveUntilNodes_1.return)) _c.call(liveUntilNodes_1);
            } finally {
              if (e_5) throw e_5.error;
            }
          }
        };
        GraphExecutor2.prototype.executeAsync = function(inputs, outputs) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_c) {
              return [2, this._executeAsync(inputs, outputs)];
            });
          });
        };
        GraphExecutor2.prototype.disposeIntermediateTensors = function() {
          if (!this.clonedTensorsMap) {
            return;
          }
          Object.values(this.clonedTensorsMap).forEach(function(tensorsList) {
            var e_7, _c;
            try {
              for (var tensorsList_1 = __values(tensorsList), tensorsList_1_1 = tensorsList_1.next(); !tensorsList_1_1.done; tensorsList_1_1 = tensorsList_1.next()) {
                var tensor2 = tensorsList_1_1.value;
                if (tensor2 && !tensor2.isDisposed) {
                  tensor2.dispose();
                }
              }
            } catch (e_7_1) {
              e_7 = { error: e_7_1 };
            } finally {
              try {
                if (tensorsList_1_1 && !tensorsList_1_1.done && (_c = tensorsList_1.return)) _c.call(tensorsList_1);
              } finally {
                if (e_7) throw e_7.error;
              }
            }
          });
          this.clonedTensorsMap = null;
        };
        GraphExecutor2.prototype.getIntermediateTensors = function() {
          return this.clonedTensorsMap;
        };
        GraphExecutor2.prototype._executeAsync = function(inputs, outputs, isFunctionExecution, tensorArrayMap, tensorListMap) {
          if (isFunctionExecution === void 0) {
            isFunctionExecution = false;
          }
          if (tensorArrayMap === void 0) {
            tensorArrayMap = {};
          }
          if (tensorListMap === void 0) {
            tensorListMap = {};
          }
          return __awaiter(this, void 0, void 0, function() {
            var context, tensorsMap, results, outputIds, inputIds, keepIds;
            return __generator(this, function(_c) {
              switch (_c.label) {
                case 0:
                  this.disposeIntermediateTensors();
                  if (!isFunctionExecution) {
                    inputs = this.mapInputs(inputs);
                    this.checkInputs(inputs);
                    this.checkInputShapeAndType(inputs);
                    outputs = this.mapOutputs(outputs);
                    this.checkOutputs(outputs);
                  }
                  try {
                    this.keepIntermediateTensors = tfc.env().getBool("KEEP_INTERMEDIATE_TENSORS");
                  } catch (e) {
                    this.keepIntermediateTensors = false;
                    console.warn(e.message);
                  }
                  context = new ExecutionContext(this.weightMap, tensorArrayMap, tensorListMap, this.functionExecutorMap, this.parseNodeNameCache);
                  if (this.keepIntermediateTensors) {
                    this.clonedTensorsMap = this.cloneTensorMap(this.weightMap);
                  }
                  return [4, this.executeWithControlFlow(inputs, context, outputs, isFunctionExecution)];
                case 1:
                  tensorsMap = _c.sent();
                  results = outputs.map(function(name) {
                    return getTensor(name, tensorsMap, context);
                  });
                  outputIds = results.map(function(t) {
                    return t.id;
                  });
                  inputIds = Object.keys(inputs).map(function(name) {
                    return inputs[name].id;
                  });
                  keepIds = new Set(__spreadArray(__spreadArray(__spreadArray([], __read(outputIds), false), __read(inputIds), false), __read(this.weightIds), false));
                  Object.values(tensorsMap).forEach(function(tensorsList) {
                    tensorsList.forEach(function(tensor2) {
                      if (tensor2 && !tensor2.isDisposed && !keepIds.has(tensor2.id)) {
                        tensor2.dispose();
                      }
                    });
                  });
                  if (this.parent == null) {
                    context.dispose(keepIds);
                  }
                  return [2, results];
              }
            });
          });
        };
        GraphExecutor2.prototype.executeFunctionAsync = function(inputs, tensorArrayMap, tensorListMap) {
          return __awaiter(this, void 0, void 0, function() {
            var mappedInputs;
            var _this = this;
            return __generator(this, function(_c) {
              mappedInputs = inputs.reduce(function(map, tensor2, index) {
                map[_this.inputs[index].name] = tensor2;
                return map;
              }, {});
              return [2, this._executeAsync(mappedInputs, this.outputNodes, true, tensorArrayMap, tensorListMap)];
            });
          });
        };
        GraphExecutor2.prototype.executeWithControlFlow = function(inputs, context, outputNames, isFunctionExecution) {
          return __awaiter(this, void 0, void 0, function() {
            var names, inputNodes, outputNodeNames, outputNodeNameSet, outputNodes, _c, usedNodes, missingInputs, dynamicNode, syncInputs, stack2, tensorsMap, intermediateTensorConsumerCount, tensorsToKeep, added, promises, missingOutputs, alternativeMsg;
            var _this = this;
            return __generator(this, function(_d) {
              switch (_d.label) {
                case 0:
                  names = Object.keys(inputs);
                  inputNodes = names.map(function(name) {
                    return _this.graph.nodes[parseNodeName(name)[0]];
                  });
                  outputNodeNames = outputNames.map(function(name) {
                    return parseNodeName(name)[0];
                  });
                  outputNodeNameSet = new Set(outputNodeNames);
                  outputNodes = outputNodeNames.map(function(name) {
                    return _this.graph.nodes[name];
                  });
                  if (outputNodes.length === 0) {
                    outputNodes = this._outputs;
                  }
                  _c = getExecutionSubgraph(inputs, outputNodes, this.weightMap, this._initNodes), usedNodes = _c.usedNodes, missingInputs = _c.missingInputs, dynamicNode = _c.dynamicNode, syncInputs = _c.syncInputs;
                  stack2 = __spreadArray(__spreadArray(__spreadArray([], __read(inputNodes), false), __read(this.graph.weights), false), __read(this._initNodes || []), false).map(function(node) {
                    return { node, contexts: context.currentContext };
                  });
                  tensorsMap = Object.assign({}, this.weightMap);
                  Object.keys(inputs).forEach(function(name) {
                    var _c2 = __read(parseNodeName(name), 2), nodeName = _c2[0], index = _c2[1];
                    var tensors = [];
                    tensors[index] = inputs[name];
                    tensorsMap[nodeName] = tensors;
                  });
                  intermediateTensorConsumerCount = {};
                  tensorsToKeep = this.getFrozenTensorIds(tensorsMap);
                  added = {};
                  _d.label = 1;
                case 1:
                  if (!(stack2.length > 0)) return [3, 3];
                  promises = this.processStack(inputNodes, stack2, context, tensorsMap, added, tensorsToKeep, outputNodeNameSet, intermediateTensorConsumerCount, usedNodes);
                  return [4, Promise.all(promises)];
                case 2:
                  _d.sent();
                  return [3, 1];
                case 3:
                  if (dynamicNode == null && !isFunctionExecution) {
                    console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");
                  }
                  missingOutputs = outputNodes.filter(function(node) {
                    return !isControlFlow(node) && !getTensor(node.name, tensorsMap, context);
                  }).map(function(node) {
                    return node.name;
                  });
                  if (missingOutputs.length > 0) {
                    alternativeMsg = "";
                    if (dynamicNode != null) {
                      alternativeMsg = "Alternatively, to avoid the dynamic ops, use model.execute() " + "and specify the inputs [".concat(syncInputs, "]");
                    }
                    throw new Error("Cannot compute the outputs [".concat(missingOutputs, "] from the provided ") + "inputs [".concat(names, "]. Consider providing the following inputs: ") + "[".concat(missingInputs, "]. ").concat(alternativeMsg));
                  }
                  return [2, tensorsMap];
              }
            });
          });
        };
        GraphExecutor2.prototype.processStack = function(inputNodes, stack2, context, tensorMap, added, tensorsToKeep, outputNodeNameSet, intermediateTensorConsumerCount, usedNodes) {
          var _this = this;
          var promises = [];
          var _loop_1 = function() {
            var _c, _d;
            var item = stack2.pop();
            context.currentContext = item.contexts;
            var nodeName = "";
            if (item.node.op === "Enter" && getParamValue("isConstant", item.node, tensorMap, context)) {
              _c = __read(getNodeNameAndIndex(item.node.name, context), 1), nodeName = _c[0];
            }
            if (tensorMap[item.node.name] == null) {
              var tensors = executeOp(item.node, tensorMap, context, this_1._resourceManager);
              if (!nodeName) {
                _d = __read(getNodeNameAndIndex(item.node.name, context), 1), nodeName = _d[0];
              }
              var currentContext_1 = context.currentContext;
              if (tfc.util.isPromise(tensors)) {
                promises.push(tensors.then(function(t) {
                  tensorMap[nodeName] = t;
                  if (_this.keepIntermediateTensors) {
                    _this.clonedTensorsMap[nodeName] = _this.cloneTensorList(t);
                  }
                  context.currentContext = currentContext_1;
                  _this.checkTensorForDisposal(nodeName, item.node, tensorMap, context, tensorsToKeep, outputNodeNameSet, intermediateTensorConsumerCount);
                  _this.processChildNodes(item.node, stack2, context, tensorMap, added, usedNodes);
                  return t;
                }));
              } else {
                tensorMap[nodeName] = tensors;
                if (this_1.keepIntermediateTensors) {
                  this_1.clonedTensorsMap[nodeName] = this_1.cloneTensorList(tensors);
                }
                this_1.checkTensorForDisposal(nodeName, item.node, tensorMap, context, tensorsToKeep, outputNodeNameSet, intermediateTensorConsumerCount);
                this_1.processChildNodes(item.node, stack2, context, tensorMap, added, usedNodes);
              }
            } else {
              this_1.processChildNodes(item.node, stack2, context, tensorMap, added, usedNodes);
            }
          };
          var this_1 = this;
          while (stack2.length > 0) {
            _loop_1();
          }
          return promises;
        };
        GraphExecutor2.prototype.processChildNodes = function(node, stack2, context, tensorMap, added, usedNodes) {
          node.children.forEach(function(childNode) {
            var _c = __read(getNodeNameAndIndex(childNode.name, context), 1), nodeName = _c[0];
            if (added[nodeName] || !usedNodes.has(childNode.name)) {
              return;
            }
            if (childNode.op === "Merge") {
              if (childNode.inputNames.some(function(name) {
                return !!getTensor(name, tensorMap, context);
              })) {
                added[nodeName] = true;
                stack2.push({ contexts: context.currentContext, node: childNode });
              }
            } else if (childNode.inputNames.every(function(name) {
              return !!getTensor(name, tensorMap, context);
            })) {
              added[nodeName] = true;
              stack2.push({ contexts: context.currentContext, node: childNode });
            }
          });
        };
        GraphExecutor2.prototype.dispose = function() {
          var _this = this;
          Object.keys(this.weightMap).forEach(function(key) {
            return _this.weightMap[key].forEach(function(tensor2) {
              return tensor2.dispose();
            });
          });
        };
        GraphExecutor2.prototype.checkInputShapeAndType = function(inputs) {
          var _this = this;
          Object.keys(inputs).forEach(function(name) {
            var input = inputs[name];
            var _c = __read(parseNodeName(name), 1), nodeName = _c[0];
            var node = _this.graph.nodes[nodeName];
            if (node.attrParams["shape"] && node.attrParams["shape"].value) {
              var shape_1 = node.attrParams["shape"].value;
              var match = shape_1.length === input.shape.length && input.shape.every(function(dim, index) {
                return shape_1[index] === -1 || shape_1[index] === dim;
              });
              tfc.util.assert(match, function() {
                return "The shape of dict['".concat(node.name, "'] provided in ") + "model.execute(dict) must be [".concat(shape_1, "], but was ") + "[".concat(input.shape, "]");
              });
            }
            if (node.attrParams["dtype"] && node.attrParams["dtype"].value) {
              tfc.util.assert(input.dtype === node.attrParams["dtype"].value, function() {
                return "The dtype of dict['".concat(node.name, "'] provided in ") + "model.execute(dict) must be " + "".concat(node.attrParams["dtype"].value, ", but was ").concat(input.dtype);
              });
            }
          });
        };
        GraphExecutor2.prototype.mapInputs = function(inputs) {
          var _a, _b;
          var result = {};
          for (var inputName in inputs) {
            var tensor2 = (_b = (_a = this._signature) === null || _a === void 0 ? void 0 : _a.inputs) === null || _b === void 0 ? void 0 : _b[inputName];
            if (tensor2 != null) {
              result[tensor2.name] = inputs[inputName];
            } else {
              result[inputName] = inputs[inputName];
            }
          }
          return result;
        };
        GraphExecutor2.prototype.checkInputs = function(inputs) {
          var _this = this;
          var notInGraph = Object.keys(inputs).filter(function(name) {
            var _c = __read(parseNodeName(name), 1), nodeName = _c[0];
            return _this.graph.nodes[nodeName] == null;
          });
          if (notInGraph.length > 0) {
            throw new Error("The dict provided in model.execute(dict) has " + "keys: [".concat(notInGraph, "] that are not part of graph"));
          }
        };
        GraphExecutor2.prototype.mapOutputs = function(outputs) {
          var _this = this;
          return outputs.map(function(name) {
            var _a, _b;
            var tensor2 = (_b = (_a = _this._signature) === null || _a === void 0 ? void 0 : _a.outputs) === null || _b === void 0 ? void 0 : _b[name];
            if (tensor2 != null) {
              return tensor2.name;
            }
            return name;
          }, {});
        };
        GraphExecutor2.prototype.checkOutputs = function(outputs) {
          var _this = this;
          outputs.forEach(function(name) {
            var _c = __read(parseNodeName(name), 1), normalizedName = _c[0];
            if (!_this.graph.nodes[normalizedName]) {
              throw new Error("The output '".concat(name, "' is not found in the graph"));
            }
          });
        };
        return GraphExecutor2;
      }()
    );
    var ResourceManager = (
      /** @class */
      function() {
        function ResourceManager2(hashTableNameToHandle, hashTableMap) {
          if (hashTableNameToHandle === void 0) {
            hashTableNameToHandle = {};
          }
          if (hashTableMap === void 0) {
            hashTableMap = {};
          }
          this.hashTableNameToHandle = hashTableNameToHandle;
          this.hashTableMap = hashTableMap;
        }
        ResourceManager2.prototype.addHashTable = function(name, hashTable2) {
          this.hashTableNameToHandle[name] = hashTable2.handle;
          this.hashTableMap[hashTable2.id] = hashTable2;
        };
        ResourceManager2.prototype.getHashTableHandleByName = function(name) {
          return this.hashTableNameToHandle[name];
        };
        ResourceManager2.prototype.getHashTableById = function(id) {
          return this.hashTableMap[id];
        };
        ResourceManager2.prototype.dispose = function() {
          for (var key in this.hashTableMap) {
            this.hashTableMap[key].clearAndClose();
            delete this.hashTableMap[key];
          }
          for (var name in this.hashTableNameToHandle) {
            this.hashTableNameToHandle[name].dispose();
            delete this.hashTableNameToHandle[name];
          }
        };
        return ResourceManager2;
      }()
    );
    var DTYPE_VALUE_SIZE_MAP = {
      "float32": 4,
      "float16": 2,
      "int32": 4,
      "uint16": 2,
      "uint8": 1,
      "bool": 1,
      "complex64": 8
    };
    var NUM_BYTES_STRING_LENGTH = 4;
    function getWeightBytelengthAsync(spec, slice2) {
      return __awaiter(this, void 0, void 0, function() {
        var size, bytesPerValue, quantization, byteLength, i, _a, _b, _c;
        return __generator(this, function(_d) {
          switch (_d.label) {
            case 0:
              size = sizeFromShape(spec.shape);
              if (!("quantization" in spec)) return [3, 1];
              quantization = spec.quantization;
              bytesPerValue = DTYPE_VALUE_SIZE_MAP[quantization.dtype];
              return [3, 7];
            case 1:
              if (!(spec.dtype === "string")) return [3, 6];
              byteLength = 0;
              i = 0;
              _d.label = 2;
            case 2:
              if (!(i < size)) return [3, 5];
              _a = byteLength;
              _b = NUM_BYTES_STRING_LENGTH;
              _c = Uint32Array.bind;
              return [4, slice2(byteLength, byteLength + NUM_BYTES_STRING_LENGTH)];
            case 3:
              byteLength = _a + (_b + new (_c.apply(Uint32Array, [void 0, _d.sent()]))()[0]);
              _d.label = 4;
            case 4:
              i++;
              return [3, 2];
            case 5:
              return [2, byteLength];
            case 6:
              bytesPerValue = DTYPE_VALUE_SIZE_MAP[spec.dtype];
              _d.label = 7;
            case 7:
              return [2, size * bytesPerValue];
          }
        });
      });
    }
    function decodeWeight(spec, byteBuffer) {
      var name = spec.name;
      var dtype = spec.dtype;
      var shape = spec.shape;
      var size = sizeFromShape(shape);
      var values;
      var offset = 0;
      if ("quantization" in spec) {
        var quantization = spec.quantization;
        if (quantization.dtype === "uint8" || quantization.dtype === "uint16") {
          if (!("min" in quantization && "scale" in quantization)) {
            throw new Error("Weight ".concat(spec.name, " with quantization ").concat(quantization.dtype, " ") + "doesn't have corresponding metadata min and scale.");
          }
        } else if (quantization.dtype === "float16") {
          if (dtype !== "float32") {
            throw new Error("Weight ".concat(spec.name, " is quantized with ").concat(quantization.dtype, " ") + "which only supports weights of type float32 not ".concat(dtype, "."));
          }
        } else {
          throw new Error("Weight ".concat(spec.name, " has unknown ") + "quantization dtype ".concat(quantization.dtype, ". ") + "Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.");
        }
        var quantizationSizeFactor = DTYPE_VALUE_SIZE_MAP[quantization.dtype];
        var quantizedArray = quantization.dtype === "uint8" ? new Uint8Array(byteBuffer) : new Uint16Array(byteBuffer);
        if (dtype === "float32") {
          if (quantization.dtype === "uint8" || quantization.dtype === "uint16") {
            values = new Float32Array(quantizedArray.length);
            for (var i = 0; i < quantizedArray.length; i++) {
              var v = quantizedArray[i];
              values[i] = v * quantization.scale + quantization.min;
            }
          } else if (quantization.dtype === "float16") {
            var float16Decode = getFloat16Decoder();
            values = float16Decode(quantizedArray);
          } else {
            throw new Error("Unsupported quantization type ".concat(quantization.dtype, " ") + "for weight type float32.");
          }
        } else if (dtype === "int32") {
          if (quantization.dtype !== "uint8" && quantization.dtype !== "uint16") {
            throw new Error("Unsupported quantization type ".concat(quantization.dtype, " ") + "for weight type int32.");
          }
          values = new Int32Array(quantizedArray.length);
          for (var i = 0; i < quantizedArray.length; i++) {
            var v = quantizedArray[i];
            values[i] = Math.round(v * quantization.scale + quantization.min);
          }
        } else {
          throw new Error("Unsupported dtype in weight '".concat(name, "': ").concat(dtype));
        }
        offset += size * quantizationSizeFactor;
      } else if (dtype === "string") {
        var size_1 = sizeFromShape(spec.shape);
        values = [];
        for (var i = 0; i < size_1; i++) {
          var byteLength = new Uint32Array(byteBuffer.slice(offset, offset + NUM_BYTES_STRING_LENGTH))[0];
          offset += NUM_BYTES_STRING_LENGTH;
          var bytes = new Uint8Array(byteBuffer.slice(offset, offset + byteLength));
          values.push(bytes);
          offset += byteLength;
        }
      } else {
        var dtypeFactor = DTYPE_VALUE_SIZE_MAP[dtype];
        if (dtype === "float32") {
          values = new Float32Array(byteBuffer);
        } else if (dtype === "int32") {
          values = new Int32Array(byteBuffer);
        } else if (dtype === "bool") {
          values = new Uint8Array(byteBuffer);
        } else if (dtype === "complex64") {
          values = new Float32Array(byteBuffer);
          var real2 = new Float32Array(values.length / 2);
          var image2 = new Float32Array(values.length / 2);
          for (var i = 0; i < real2.length; i++) {
            real2[i] = values[i * 2];
            image2[i] = values[i * 2 + 1];
          }
          var realTensor = tensor(real2, shape, "float32");
          var imageTensor = tensor(image2, shape, "float32");
          var complexTensor = complex(realTensor, imageTensor);
          realTensor.dispose();
          imageTensor.dispose();
          return complexTensor;
        } else {
          throw new Error("Unsupported dtype in weight '".concat(name, "': ").concat(dtype));
        }
        offset += size * dtypeFactor;
      }
      return tensor(values, shape, dtype);
    }
    function readToLength(reader, initialData, length) {
      return __awaiter(this, void 0, void 0, function() {
        var data, _a, done, value, missing, newData;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              data = new Uint8Array(initialData);
              _b.label = 1;
            case 1:
              if (!(data.byteLength < length)) return [3, 3];
              return [4, reader.read()];
            case 2:
              _a = _b.sent(), done = _a.done, value = _a.value;
              if (done && value == null) {
                missing = length - data.byteLength;
                throw new Error("Reader is done but ".concat(missing, " bytes are still expected"));
              }
              newData = new Uint8Array(data.length + value.byteLength);
              newData.set(data, 0);
              newData.set(new Uint8Array(value), data.length);
              data = newData;
              return [3, 1];
            case 3:
              return [2, data.buffer];
          }
        });
      });
    }
    function decodeWeightsStream(weightStream, specs) {
      return __awaiter(this, void 0, void 0, function() {
        var tensors, reader, data, specs_2, specs_2_1, spec, byteLength, tensorData, weightTensor, b, e_2_1;
        var e_2, _a;
        var _this = this;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              tensors = {};
              reader = weightStream.getReader();
              data = new ArrayBuffer(0);
              _b.label = 1;
            case 1:
              _b.trys.push([1, 7, 8, 9]);
              specs_2 = __values(specs), specs_2_1 = specs_2.next();
              _b.label = 2;
            case 2:
              if (!!specs_2_1.done) return [3, 6];
              spec = specs_2_1.value;
              return [4, getWeightBytelengthAsync(spec, function(start, end) {
                return __awaiter(_this, void 0, void 0, function() {
                  return __generator(this, function(_a2) {
                    switch (_a2.label) {
                      case 0:
                        return [4, readToLength(reader, data, end)];
                      case 1:
                        data = _a2.sent();
                        return [2, data.slice(start, end)];
                    }
                  });
                });
              })];
            case 3:
              byteLength = _b.sent();
              return [4, readToLength(reader, data, byteLength)];
            case 4:
              data = _b.sent();
              tensorData = data.slice(0, byteLength);
              data = data.slice(byteLength);
              weightTensor = decodeWeight(spec, tensorData);
              tensors[spec.name] = weightTensor;
              if (getBackend() === "webgpu") {
                b = backend();
                if ("uploadToGPU" in b && sizeFromShape(weightTensor.shape) >= env().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")) {
                  b.uploadToGPU(weightTensor.dataId);
                }
              }
              _b.label = 5;
            case 5:
              specs_2_1 = specs_2.next();
              return [3, 2];
            case 6:
              return [3, 9];
            case 7:
              e_2_1 = _b.sent();
              e_2 = { error: e_2_1 };
              return [3, 9];
            case 8:
              try {
                if (specs_2_1 && !specs_2_1.done && (_a = specs_2.return)) _a.call(specs_2);
              } finally {
                if (e_2) throw e_2.error;
              }
              return [
                7
                /*endfinally*/
              ];
            case 9:
              return [2, tensors];
          }
        });
      });
    }
    function computeFloat16MantisaTable() {
      var convertMantissa = function(i2) {
        var m = i2 << 13;
        var e = 0;
        while ((m & 8388608) === 0) {
          e -= 8388608;
          m <<= 1;
        }
        m &= ~8388608;
        e += 947912704;
        return m | e;
      };
      var mantisaTable = new Uint32Array(2048);
      mantisaTable[0] = 0;
      for (var i = 1; i < 1024; i++) {
        mantisaTable[i] = convertMantissa(i);
      }
      for (var i = 1024; i < 2048; i++) {
        mantisaTable[i] = 939524096 + (i - 1024 << 13);
      }
      return mantisaTable;
    }
    function computeFloat16ExponentTable() {
      var exponentTable = new Uint32Array(64);
      exponentTable[0] = 0;
      exponentTable[31] = 1199570944;
      exponentTable[32] = 2147483648;
      exponentTable[63] = 3347054592;
      for (var i = 1; i < 31; i++) {
        exponentTable[i] = i << 23;
      }
      for (var i = 33; i < 63; i++) {
        exponentTable[i] = 2147483648 + (i - 32 << 23);
      }
      return exponentTable;
    }
    function computeFloat16OffsetTable() {
      var offsetTable = new Uint32Array(64);
      for (var i = 0; i < 64; i++) {
        offsetTable[i] = 1024;
      }
      offsetTable[0] = offsetTable[32] = 0;
      return offsetTable;
    }
    function getFloat16Decoder() {
      var mantisaTable = computeFloat16MantisaTable();
      var exponentTable = computeFloat16ExponentTable();
      var offsetTable = computeFloat16OffsetTable();
      return function(quantizedArray) {
        var buffer2 = new ArrayBuffer(4 * quantizedArray.length);
        var bufferUint32View = new Uint32Array(buffer2);
        for (var index = 0; index < quantizedArray.length; index++) {
          var float16Bits = quantizedArray[index];
          var float32Bits = mantisaTable[offsetTable[float16Bits >> 10] + (float16Bits & 1023)] + exponentTable[float16Bits >> 10];
          bufferUint32View[index] = float32Bits;
        }
        return new Float32Array(buffer2);
      };
    }
    var TFHUB_SEARCH_PARAM = "?tfjs-format=file";
    var DEFAULT_MODEL_NAME = "model.json";
    var GraphModel = (
      /** @class */
      function() {
        function GraphModel2(modelUrl, loadOptions, tfio) {
          if (loadOptions === void 0) {
            loadOptions = {};
          }
          if (tfio === void 0) {
            tfio = tfc.io;
          }
          this.modelUrl = modelUrl;
          this.loadOptions = loadOptions;
          this.version = "n/a";
          this.io = tfio;
          if (loadOptions == null) {
            this.loadOptions = {};
          }
          this.resourceManager = new ResourceManager();
        }
        Object.defineProperty(GraphModel2.prototype, "modelVersion", {
          // Returns the version information for the tensorflow model GraphDef.
          get: function() {
            return this.version;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(GraphModel2.prototype, "inputNodes", {
          get: function() {
            return this.executor.inputNodes;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(GraphModel2.prototype, "outputNodes", {
          get: function() {
            return this.executor.outputNodes;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(GraphModel2.prototype, "inputs", {
          get: function() {
            return this.executor.inputs;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(GraphModel2.prototype, "outputs", {
          get: function() {
            return this.executor.outputs;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(GraphModel2.prototype, "weights", {
          get: function() {
            return this.executor.weightMap;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(GraphModel2.prototype, "metadata", {
          get: function() {
            return this.artifacts.userDefinedMetadata;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(GraphModel2.prototype, "modelSignature", {
          get: function() {
            return this.signature;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(GraphModel2.prototype, "modelStructuredOutputKeys", {
          get: function() {
            return this.structuredOutputKeys;
          },
          enumerable: false,
          configurable: true
        });
        GraphModel2.prototype.findIOHandler = function() {
          var path = this.modelUrl;
          if (path.load != null) {
            this.handler = path;
          } else if (this.loadOptions.requestInit != null) {
            this.handler = this.io.browserHTTPRequest(path, this.loadOptions);
          } else {
            var handlers = this.io.getLoadHandlers(path, this.loadOptions);
            if (handlers.length === 0) {
              handlers.push(this.io.browserHTTPRequest(path, this.loadOptions));
            } else if (handlers.length > 1) {
              throw new Error("Found more than one (".concat(handlers.length, ") load handlers for ") + "URL '".concat([path], "'"));
            }
            this.handler = handlers[0];
          }
        };
        GraphModel2.prototype.load = function() {
          var _this = this;
          this.findIOHandler();
          if (this.handler.load == null) {
            throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");
          }
          var loadResult = this.handler.load();
          if (tfc.util.isPromise(loadResult)) {
            return loadResult.then(function(artifacts) {
              if (artifacts.getWeightStream == null) {
                return _this.loadSync(artifacts);
              }
              return _this.loadStreaming(artifacts);
            });
          }
          return this.loadSync(loadResult);
        };
        GraphModel2.prototype.loadSync = function(artifacts) {
          var weightMap = this.io.decodeWeights(artifacts.weightData, artifacts.weightSpecs);
          return this.loadWithWeightMap(artifacts, weightMap);
        };
        GraphModel2.prototype.loadStreaming = function(artifacts) {
          return __awaiter(this, void 0, void 0, function() {
            var weightMap;
            return __generator(this, function(_d) {
              switch (_d.label) {
                case 0:
                  if (artifacts.getWeightStream == null) {
                    throw new Error("Model artifacts missing streamWeights function");
                  }
                  return [4, decodeWeightsStream(artifacts.getWeightStream(), artifacts.weightSpecs)];
                case 1:
                  weightMap = _d.sent();
                  return [2, this.loadWithWeightMap(artifacts, weightMap)];
              }
            });
          });
        };
        GraphModel2.prototype.loadWithWeightMap = function(artifacts, weightMap) {
          this.artifacts = artifacts;
          var graph2 = this.artifacts.modelTopology;
          var signature = this.artifacts.signature;
          if (this.artifacts.userDefinedMetadata != null) {
            var metadata = this.artifacts.userDefinedMetadata;
            if (metadata.signature != null) {
              signature = metadata.signature;
            }
            if (metadata.structuredOutputKeys != null) {
              this.structuredOutputKeys = metadata.structuredOutputKeys;
            }
          }
          this.signature = signature;
          this.version = "".concat(graph2.versions.producer, ".").concat(graph2.versions.minConsumer);
          this.executor = new GraphExecutor(OperationMapper.Instance.transformGraph(graph2, this.signature));
          this.executor.weightMap = this.convertTensorMapToTensorsMap(weightMap);
          this.executor.resourceManager = this.resourceManager;
          if (artifacts.modelInitializer != null && artifacts.modelInitializer.node != null) {
            var initializer = OperationMapper.Instance.transformGraph(artifacts.modelInitializer);
            this.initializer = new GraphExecutor(initializer);
            this.initializer.weightMap = this.executor.weightMap;
            this.initializer.resourceManager = this.resourceManager;
            this.initializerSignature = artifacts.initializerSignature;
          }
          return true;
        };
        GraphModel2.prototype.save = function(handlerOrURL, config) {
          return __awaiter(this, void 0, void 0, function() {
            var handlers;
            return __generator(this, function(_d) {
              if (typeof handlerOrURL === "string") {
                handlers = this.io.getSaveHandlers(handlerOrURL);
                if (handlers.length === 0) {
                  throw new Error("Cannot find any save handlers for URL '".concat(handlerOrURL, "'"));
                } else if (handlers.length > 1) {
                  throw new Error("Found more than one (".concat(handlers.length, ") save handlers for ") + "URL '".concat(handlerOrURL, "'"));
                }
                handlerOrURL = handlers[0];
              }
              if (handlerOrURL.save == null) {
                throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");
              }
              return [2, handlerOrURL.save(this.artifacts)];
            });
          });
        };
        GraphModel2.prototype.addStructuredOutputNames = function(outputTensors) {
          var _this = this;
          if (this.structuredOutputKeys) {
            var outputTensorsArray = outputTensors instanceof tfc.Tensor ? [outputTensors] : outputTensors;
            var outputTensorMap_1 = {};
            outputTensorsArray.forEach(function(outputTensor, i) {
              return outputTensorMap_1[_this.structuredOutputKeys[i]] = outputTensor;
            });
            return outputTensorMap_1;
          }
          return outputTensors;
        };
        GraphModel2.prototype.predict = function(inputs, config) {
          var outputTensors = this.execute(inputs, this.outputNodes);
          return this.addStructuredOutputNames(outputTensors);
        };
        GraphModel2.prototype.predictAsync = function(inputs, config) {
          return __awaiter(this, void 0, void 0, function() {
            var outputTensors;
            return __generator(this, function(_d) {
              switch (_d.label) {
                case 0:
                  return [4, this.executeAsync(inputs, this.outputNodes)];
                case 1:
                  outputTensors = _d.sent();
                  return [2, this.addStructuredOutputNames(outputTensors)];
              }
            });
          });
        };
        GraphModel2.prototype.normalizeInputs = function(inputs) {
          var _this = this;
          var _a;
          if (!(inputs instanceof tfc.Tensor) && !Array.isArray(inputs)) {
            var signatureInputs = (_a = this.signature) === null || _a === void 0 ? void 0 : _a.inputs;
            if (signatureInputs != null) {
              for (var input in signatureInputs) {
                var tensor2 = signatureInputs[input];
                if (tensor2.resourceId != null) {
                  inputs[input] = this.resourceIdToCapturedInput[tensor2.resourceId];
                }
              }
            }
            return inputs;
          }
          inputs = Array.isArray(inputs) ? inputs : [inputs];
          var numCapturedInputs = Object.keys(this.resourceIdToCapturedInput).length;
          if (inputs.length + numCapturedInputs !== this.inputNodes.length) {
            throw new Error("Input tensor count mismatch, the graph model has ".concat(this.inputNodes.length - numCapturedInputs, " non-resource placeholders, while there are ").concat(inputs.length, " input tensors provided."));
          }
          var inputIndex = 0;
          return this.inputNodes.reduce(function(map, inputName) {
            var _a2, _b, _c;
            var resourceId = (_c = (_b = (_a2 = _this.signature) === null || _a2 === void 0 ? void 0 : _a2.inputs) === null || _b === void 0 ? void 0 : _b[inputName]) === null || _c === void 0 ? void 0 : _c.resourceId;
            if (resourceId != null) {
              map[inputName] = _this.resourceIdToCapturedInput[resourceId];
            } else {
              map[inputName] = inputs[inputIndex++];
            }
            return map;
          }, {});
        };
        GraphModel2.prototype.normalizeOutputs = function(outputs) {
          outputs = outputs || this.outputNodes;
          return !Array.isArray(outputs) ? [outputs] : outputs;
        };
        GraphModel2.prototype.executeInitializerGraph = function() {
          if (this.initializer == null) {
            return [];
          }
          if (this.initializerSignature == null) {
            return this.initializer.execute({}, []);
          } else {
            return this.initializer.execute({}, Object.keys(this.initializerSignature.outputs));
          }
        };
        GraphModel2.prototype.executeInitializerGraphAsync = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_d) {
              if (this.initializer == null) {
                return [2, []];
              }
              if (this.initializerSignature == null) {
                return [2, this.initializer.executeAsync({}, [])];
              } else {
                return [2, this.initializer.executeAsync({}, Object.keys(this.initializerSignature.outputs))];
              }
            });
          });
        };
        GraphModel2.prototype.setResourceIdToCapturedInput = function(outputs) {
          this.resourceIdToCapturedInput = {};
          if (this.initializerSignature) {
            var signatureOutputs = this.initializerSignature.outputs;
            var outputNames = Object.keys(signatureOutputs);
            for (var i = 0; i < outputNames.length; i++) {
              var outputName = outputNames[i];
              var tensorInfo = signatureOutputs[outputName];
              this.resourceIdToCapturedInput[tensorInfo.resourceId] = outputs[i];
            }
          }
        };
        GraphModel2.prototype.execute = function(inputs, outputs) {
          if (this.resourceIdToCapturedInput == null) {
            this.setResourceIdToCapturedInput(this.executeInitializerGraph());
          }
          inputs = this.normalizeInputs(inputs);
          outputs = this.normalizeOutputs(outputs);
          var result = this.executor.execute(inputs, outputs);
          return result.length > 1 ? result : result[0];
        };
        GraphModel2.prototype.executeAsync = function(inputs, outputs) {
          return __awaiter(this, void 0, void 0, function() {
            var _d, result;
            return __generator(this, function(_e) {
              switch (_e.label) {
                case 0:
                  if (!(this.resourceIdToCapturedInput == null)) return [3, 2];
                  _d = this.setResourceIdToCapturedInput;
                  return [4, this.executeInitializerGraphAsync()];
                case 1:
                  _d.apply(this, [_e.sent()]);
                  _e.label = 2;
                case 2:
                  inputs = this.normalizeInputs(inputs);
                  outputs = this.normalizeOutputs(outputs);
                  return [4, this.executor.executeAsync(inputs, outputs)];
                case 3:
                  result = _e.sent();
                  return [2, result.length > 1 ? result : result[0]];
              }
            });
          });
        };
        GraphModel2.prototype.getIntermediateTensors = function() {
          return this.executor.getIntermediateTensors();
        };
        GraphModel2.prototype.disposeIntermediateTensors = function() {
          this.executor.disposeIntermediateTensors();
        };
        GraphModel2.prototype.convertTensorMapToTensorsMap = function(map) {
          return Object.keys(map).reduce(function(newMap, key) {
            newMap[key] = [map[key]];
            return newMap;
          }, {});
        };
        GraphModel2.prototype.dispose = function() {
          this.executor.dispose();
          if (this.initializer) {
            this.initializer.dispose();
            if (this.resourceIdToCapturedInput) {
              tfc.dispose(this.resourceIdToCapturedInput);
            }
          }
          this.resourceManager.dispose();
        };
        return GraphModel2;
      }()
    );
    function loadGraphModel(modelUrl, options, tfio) {
      if (options === void 0) {
        options = {};
      }
      if (tfio === void 0) {
        tfio = tfc.io;
      }
      return __awaiter(this, void 0, void 0, function() {
        var model;
        return __generator(this, function(_d) {
          switch (_d.label) {
            case 0:
              if (modelUrl == null) {
                throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");
              }
              if (options == null) {
                options = {};
              }
              if (options.fromTFHub && typeof modelUrl === "string") {
                modelUrl = getTFHubUrl(modelUrl);
              }
              model = new GraphModel(modelUrl, options, tfio);
              return [4, model.load()];
            case 1:
              _d.sent();
              return [2, model];
          }
        });
      });
    }
    function loadGraphModelSync(modelSource) {
      if (modelSource == null) {
        throw new Error("modelUrl in loadGraphModelSync() cannot be null. Please provide model artifacts or an IOHandler that loads the model");
      }
      var ioHandler;
      if (modelSource instanceof Array) {
        var _d = __read(modelSource, 2), modelJSON = _d[0], weights = _d[1];
        if (!modelJSON) {
          throw new Error("modelJSON must be the first element of the array");
        }
        if (!weights || !(weights instanceof ArrayBuffer)) {
          throw new Error("An ArrayBuffer of weights must be the second element of the array");
        }
        if (!("modelTopology" in modelJSON)) {
          throw new Error("Model JSON is missing 'modelTopology'");
        }
        if (!("weightsManifest" in modelJSON)) {
          throw new Error("Model JSON is missing 'weightsManifest'");
        }
        var weightSpecs = tfc.io.getWeightSpecs(modelJSON.weightsManifest);
        var modelArtifacts = tfc.io.getModelArtifactsForJSONSync(modelJSON, weightSpecs, weights);
        ioHandler = tfc.io.fromMemorySync(modelArtifacts);
      } else if ("load" in modelSource) {
        ioHandler = modelSource;
      } else if ("modelTopology" in modelSource && "weightSpecs" in modelSource && "weightData" in modelSource) {
        ioHandler = tfc.io.fromMemorySync(modelSource);
      } else {
        throw new Error("Unknown model format");
      }
      var model = new GraphModel(ioHandler);
      model.load();
      return model;
    }
    function getTFHubUrl(modelUrl) {
      if (!modelUrl.endsWith("/")) {
        modelUrl = modelUrl + "/";
      }
      return "".concat(modelUrl).concat(DEFAULT_MODEL_NAME).concat(TFHUB_SEARCH_PARAM);
    }
    var version = "4.22.0";
    exports2.GraphModel = GraphModel;
    exports2.deregisterOp = deregisterOp;
    exports2.loadGraphModel = loadGraphModel;
    exports2.loadGraphModelSync = loadGraphModelSync;
    exports2.registerOp = registerOp;
    exports2.version_converter = version;
  }
});

// node_modules/@tensorflow/tfjs-data/dist/tf-data.node.js
var require_tf_data_node = __commonJS({
  "node_modules/@tensorflow/tfjs-data/dist/tf-data.node.js"(exports2) {
    "use strict";
    var tf = require_tf_core_node();
    function _interopNamespaceDefault(e) {
      var n = /* @__PURE__ */ Object.create(null);
      if (e) {
        Object.keys(e).forEach(function(k) {
          if (k !== "default") {
            var d = Object.getOwnPropertyDescriptor(e, k);
            Object.defineProperty(n, k, d.get ? d : {
              enumerable: true,
              get: function() {
                return e[k];
              }
            });
          }
        });
      }
      n.default = e;
      return n;
    }
    var tf__namespace = /* @__PURE__ */ _interopNamespaceDefault(tf);
    var extendStatics = function(d, b) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
        d2.__proto__ = b2;
      } || function(d2, b2) {
        for (var p in b2)
          if (Object.prototype.hasOwnProperty.call(b2, p))
            d2[p] = b2[p];
      };
      return extendStatics(d, b);
    };
    function __extends(d, b) {
      if (typeof b !== "function" && b !== null)
        throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
      extendStatics(d, b);
      function __() {
        this.constructor = d;
      }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }
    function __awaiter(thisArg, _arguments, P, generator2) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator2.next(value));
          } catch (e) {
            reject(e);
          }
        }
        function rejected(value) {
          try {
            step(generator2["throw"](value));
          } catch (e) {
            reject(e);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator2 = generator2.apply(thisArg, _arguments || [])).next());
      });
    }
    function __generator(thisArg, body) {
      var _ = { label: 0, sent: function() {
        if (t[0] & 1)
          throw t[1];
        return t[1];
      }, trys: [], ops: [] }, f, y, t, g;
      return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
        return this;
      }), g;
      function verb(n) {
        return function(v) {
          return step([n, v]);
        };
      }
      function step(op) {
        if (f)
          throw new TypeError("Generator is already executing.");
        while (_)
          try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
              return t;
            if (y = 0, t)
              op = [op[0] & 2, t.value];
            switch (op[0]) {
              case 0:
              case 1:
                t = op;
                break;
              case 4:
                _.label++;
                return { value: op[1], done: false };
              case 5:
                _.label++;
                y = op[1];
                op = [0];
                continue;
              case 7:
                op = _.ops.pop();
                _.trys.pop();
                continue;
              default:
                if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                  _ = 0;
                  continue;
                }
                if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                  _.label = op[1];
                  break;
                }
                if (op[0] === 6 && _.label < t[1]) {
                  _.label = t[1];
                  t = op;
                  break;
                }
                if (t && _.label < t[2]) {
                  _.label = t[2];
                  _.ops.push(op);
                  break;
                }
                if (t[2])
                  _.ops.pop();
                _.trys.pop();
                continue;
            }
            op = body.call(thisArg, _);
          } catch (e) {
            op = [6, e];
            y = 0;
          } finally {
            f = t = 0;
          }
        if (op[0] & 5)
          throw op[1];
        return { value: op[0] ? op[1] : void 0, done: true };
      }
    }
    function __values(o) {
      var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
      if (m)
        return m.call(o);
      if (o && typeof o.length === "number")
        return {
          next: function() {
            if (o && i >= o.length)
              o = void 0;
            return { value: o && o[i++], done: !o };
          }
        };
      throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    }
    function __read(o, n) {
      var m = typeof Symbol === "function" && o[Symbol.iterator];
      if (!m)
        return o;
      var i = m.call(o), r, ar = [], e;
      try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
          ar.push(r.value);
      } catch (error) {
        e = { error };
      } finally {
        try {
          if (r && !r.done && (m = i["return"]))
            m.call(i);
        } finally {
          if (e)
            throw e.error;
        }
      }
      return ar;
    }
    function __spreadArray(to, from, pack) {
      if (pack || arguments.length === 2)
        for (var i = 0, l = from.length, ar; i < l; i++) {
          if (ar || !(i in from)) {
            if (!ar)
              ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
          }
        }
      return to.concat(ar || Array.prototype.slice.call(from));
    }
    var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
    function getAugmentedNamespace(n) {
      if (n.__esModule)
        return n;
      var f = n.default;
      if (typeof f == "function") {
        var a = function a2() {
          if (this instanceof a2) {
            var args = [null];
            args.push.apply(args, arguments);
            var Ctor = Function.bind.apply(f, args);
            return new Ctor();
          }
          return f.apply(this, arguments);
        };
        a.prototype = f.prototype;
      } else
        a = {};
      Object.defineProperty(a, "__esModule", { value: true });
      Object.keys(n).forEach(function(k) {
        var d = Object.getOwnPropertyDescriptor(n, k);
        Object.defineProperty(a, k, d.get ? d : {
          enumerable: true,
          get: function() {
            return n[k];
          }
        });
      });
      return a;
    }
    var alea$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function Alea(seed) {
          var me = this, mash = Mash();
          me.next = function() {
            var t = 2091639 * me.s0 + me.c * 23283064365386963e-26;
            me.s0 = me.s1;
            me.s1 = me.s2;
            return me.s2 = t - (me.c = t | 0);
          };
          me.c = 1;
          me.s0 = mash(" ");
          me.s1 = mash(" ");
          me.s2 = mash(" ");
          me.s0 -= mash(seed);
          if (me.s0 < 0) {
            me.s0 += 1;
          }
          me.s1 -= mash(seed);
          if (me.s1 < 0) {
            me.s1 += 1;
          }
          me.s2 -= mash(seed);
          if (me.s2 < 0) {
            me.s2 += 1;
          }
          mash = null;
        }
        function copy(f, t) {
          t.c = f.c;
          t.s0 = f.s0;
          t.s1 = f.s1;
          t.s2 = f.s2;
          return t;
        }
        function impl(seed, opts) {
          var xg = new Alea(seed), state = opts && opts.state, prng = xg.next;
          prng.int32 = function() {
            return xg.next() * 4294967296 | 0;
          };
          prng.double = function() {
            return prng() + (prng() * 2097152 | 0) * 11102230246251565e-32;
          };
          prng.quick = prng;
          if (state) {
            if (typeof state == "object")
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        function Mash() {
          var n = 4022871197;
          var mash = function(data) {
            data = String(data);
            for (var i = 0; i < data.length; i++) {
              n += data.charCodeAt(i);
              var h = 0.02519603282416938 * n;
              n = h >>> 0;
              h -= n;
              h *= n;
              n = h >>> 0;
              h -= n;
              n += h * 4294967296;
            }
            return (n >>> 0) * 23283064365386963e-26;
          };
          return mash;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.alea = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(alea$1);
    var aleaExports = alea$1.exports;
    var xor128$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this, strseed = "";
          me.x = 0;
          me.y = 0;
          me.z = 0;
          me.w = 0;
          me.next = function() {
            var t = me.x ^ me.x << 11;
            me.x = me.y;
            me.y = me.z;
            me.z = me.w;
            return me.w ^= me.w >>> 19 ^ t ^ t >>> 8;
          };
          if (seed === (seed | 0)) {
            me.x = seed;
          } else {
            strseed += seed;
          }
          for (var k = 0; k < strseed.length + 64; k++) {
            me.x ^= strseed.charCodeAt(k) | 0;
            me.next();
          }
        }
        function copy(f, t) {
          t.x = f.x;
          t.y = f.y;
          t.z = f.z;
          t.w = f.w;
          return t;
        }
        function impl(seed, opts) {
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (typeof state == "object")
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xor128 = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xor128$1);
    var xor128Exports = xor128$1.exports;
    var xorwow$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this, strseed = "";
          me.next = function() {
            var t = me.x ^ me.x >>> 2;
            me.x = me.y;
            me.y = me.z;
            me.z = me.w;
            me.w = me.v;
            return (me.d = me.d + 362437 | 0) + (me.v = me.v ^ me.v << 4 ^ (t ^ t << 1)) | 0;
          };
          me.x = 0;
          me.y = 0;
          me.z = 0;
          me.w = 0;
          me.v = 0;
          if (seed === (seed | 0)) {
            me.x = seed;
          } else {
            strseed += seed;
          }
          for (var k = 0; k < strseed.length + 64; k++) {
            me.x ^= strseed.charCodeAt(k) | 0;
            if (k == strseed.length) {
              me.d = me.x << 10 ^ me.x >>> 4;
            }
            me.next();
          }
        }
        function copy(f, t) {
          t.x = f.x;
          t.y = f.y;
          t.z = f.z;
          t.w = f.w;
          t.v = f.v;
          t.d = f.d;
          return t;
        }
        function impl(seed, opts) {
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (typeof state == "object")
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xorwow = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xorwow$1);
    var xorwowExports = xorwow$1.exports;
    var xorshift7$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this;
          me.next = function() {
            var X = me.x, i = me.i, t, v;
            t = X[i];
            t ^= t >>> 7;
            v = t ^ t << 24;
            t = X[i + 1 & 7];
            v ^= t ^ t >>> 10;
            t = X[i + 3 & 7];
            v ^= t ^ t >>> 3;
            t = X[i + 4 & 7];
            v ^= t ^ t << 7;
            t = X[i + 7 & 7];
            t = t ^ t << 13;
            v ^= t ^ t << 9;
            X[i] = v;
            me.i = i + 1 & 7;
            return v;
          };
          function init(me2, seed2) {
            var j, X = [];
            if (seed2 === (seed2 | 0)) {
              X[0] = seed2;
            } else {
              seed2 = "" + seed2;
              for (j = 0; j < seed2.length; ++j) {
                X[j & 7] = X[j & 7] << 15 ^ seed2.charCodeAt(j) + X[j + 1 & 7] << 13;
              }
            }
            while (X.length < 8)
              X.push(0);
            for (j = 0; j < 8 && X[j] === 0; ++j)
              ;
            if (j == 8)
              X[7] = -1;
            else
              X[j];
            me2.x = X;
            me2.i = 0;
            for (j = 256; j > 0; --j) {
              me2.next();
            }
          }
          init(me, seed);
        }
        function copy(f, t) {
          t.x = f.x.slice();
          t.i = f.i;
          return t;
        }
        function impl(seed, opts) {
          if (seed == null)
            seed = +/* @__PURE__ */ new Date();
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (state.x)
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xorshift7 = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xorshift7$1);
    var xorshift7Exports = xorshift7$1.exports;
    var xor4096$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this;
          me.next = function() {
            var w = me.w, X = me.X, i = me.i, t, v;
            me.w = w = w + 1640531527 | 0;
            v = X[i + 34 & 127];
            t = X[i = i + 1 & 127];
            v ^= v << 13;
            t ^= t << 17;
            v ^= v >>> 15;
            t ^= t >>> 12;
            v = X[i] = v ^ t;
            me.i = i;
            return v + (w ^ w >>> 16) | 0;
          };
          function init(me2, seed2) {
            var t, v, i, j, w, X = [], limit = 128;
            if (seed2 === (seed2 | 0)) {
              v = seed2;
              seed2 = null;
            } else {
              seed2 = seed2 + "\0";
              v = 0;
              limit = Math.max(limit, seed2.length);
            }
            for (i = 0, j = -32; j < limit; ++j) {
              if (seed2)
                v ^= seed2.charCodeAt((j + 32) % seed2.length);
              if (j === 0)
                w = v;
              v ^= v << 10;
              v ^= v >>> 15;
              v ^= v << 4;
              v ^= v >>> 13;
              if (j >= 0) {
                w = w + 1640531527 | 0;
                t = X[j & 127] ^= v + w;
                i = 0 == t ? i + 1 : 0;
              }
            }
            if (i >= 128) {
              X[(seed2 && seed2.length || 0) & 127] = -1;
            }
            i = 127;
            for (j = 4 * 128; j > 0; --j) {
              v = X[i + 34 & 127];
              t = X[i = i + 1 & 127];
              v ^= v << 13;
              t ^= t << 17;
              v ^= v >>> 15;
              t ^= t >>> 12;
              X[i] = v ^ t;
            }
            me2.w = w;
            me2.X = X;
            me2.i = i;
          }
          init(me, seed);
        }
        function copy(f, t) {
          t.i = f.i;
          t.w = f.w;
          t.X = f.X.slice();
          return t;
        }
        function impl(seed, opts) {
          if (seed == null)
            seed = +/* @__PURE__ */ new Date();
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (state.X)
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xor4096 = impl;
        }
      })(
        commonjsGlobal,
        // window object or global
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xor4096$1);
    var xor4096Exports = xor4096$1.exports;
    var tychei$1 = { exports: {} };
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this, strseed = "";
          me.next = function() {
            var b = me.b, c = me.c, d = me.d, a = me.a;
            b = b << 25 ^ b >>> 7 ^ c;
            c = c - d | 0;
            d = d << 24 ^ d >>> 8 ^ a;
            a = a - b | 0;
            me.b = b = b << 20 ^ b >>> 12 ^ c;
            me.c = c = c - d | 0;
            me.d = d << 16 ^ c >>> 16 ^ a;
            return me.a = a - b | 0;
          };
          me.a = 0;
          me.b = 0;
          me.c = 2654435769 | 0;
          me.d = 1367130551;
          if (seed === Math.floor(seed)) {
            me.a = seed / 4294967296 | 0;
            me.b = seed | 0;
          } else {
            strseed += seed;
          }
          for (var k = 0; k < strseed.length + 20; k++) {
            me.b ^= strseed.charCodeAt(k) | 0;
            me.next();
          }
        }
        function copy(f, t) {
          t.a = f.a;
          t.b = f.b;
          t.c = f.c;
          t.d = f.d;
          return t;
        }
        function impl(seed, opts) {
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (typeof state == "object")
              copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.tychei = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(tychei$1);
    var tycheiExports = tychei$1.exports;
    var seedrandom$1 = { exports: {} };
    var _nodeResolve_empty = {};
    var _nodeResolve_empty$1 = {
      __proto__: null,
      default: _nodeResolve_empty
    };
    var require$$0 = /* @__PURE__ */ getAugmentedNamespace(_nodeResolve_empty$1);
    (function(module3) {
      (function(global2, pool, math) {
        var width = 256, chunks = 6, digits = 52, rngname = "random", startdenom = math.pow(width, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask = width - 1, nodecrypto;
        function seedrandom2(seed, options, callback) {
          var key = [];
          options = options == true ? { entropy: true } : options || {};
          var shortseed = mixkey(flatten(options.entropy ? [seed, tostring(pool)] : seed == null ? autoseed() : seed, 3), key);
          var arc4 = new ARC4(key);
          var prng = function() {
            var n = arc4.g(chunks), d = startdenom, x = 0;
            while (n < significance) {
              n = (n + x) * width;
              d *= width;
              x = arc4.g(1);
            }
            while (n >= overflow) {
              n /= 2;
              d /= 2;
              x >>>= 1;
            }
            return (n + x) / d;
          };
          prng.int32 = function() {
            return arc4.g(4) | 0;
          };
          prng.quick = function() {
            return arc4.g(4) / 4294967296;
          };
          prng.double = prng;
          mixkey(tostring(arc4.S), pool);
          return (options.pass || callback || function(prng2, seed2, is_math_call, state) {
            if (state) {
              if (state.S) {
                copy(state, arc4);
              }
              prng2.state = function() {
                return copy(arc4, {});
              };
            }
            if (is_math_call) {
              math[rngname] = prng2;
              return seed2;
            } else
              return prng2;
          })(prng, shortseed, "global" in options ? options.global : this == math, options.state);
        }
        function ARC4(key) {
          var t, keylen = key.length, me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
          if (!keylen) {
            key = [keylen++];
          }
          while (i < width) {
            s[i] = i++;
          }
          for (i = 0; i < width; i++) {
            s[i] = s[j = mask & j + key[i % keylen] + (t = s[i])];
            s[j] = t;
          }
          (me.g = function(count) {
            var t2, r = 0, i2 = me.i, j2 = me.j, s2 = me.S;
            while (count--) {
              t2 = s2[i2 = mask & i2 + 1];
              r = r * width + s2[mask & (s2[i2] = s2[j2 = mask & j2 + t2]) + (s2[j2] = t2)];
            }
            me.i = i2;
            me.j = j2;
            return r;
          })(width);
        }
        function copy(f, t) {
          t.i = f.i;
          t.j = f.j;
          t.S = f.S.slice();
          return t;
        }
        function flatten(obj, depth) {
          var result = [], typ = typeof obj, prop;
          if (depth && typ == "object") {
            for (prop in obj) {
              try {
                result.push(flatten(obj[prop], depth - 1));
              } catch (e) {
              }
            }
          }
          return result.length ? result : typ == "string" ? obj : obj + "\0";
        }
        function mixkey(seed, key) {
          var stringseed = seed + "", smear, j = 0;
          while (j < stringseed.length) {
            key[mask & j] = mask & (smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++);
          }
          return tostring(key);
        }
        function autoseed() {
          try {
            var out;
            if (nodecrypto && (out = nodecrypto.randomBytes)) {
              out = out(width);
            } else {
              out = new Uint8Array(width);
              (global2.crypto || global2.msCrypto).getRandomValues(out);
            }
            return tostring(out);
          } catch (e) {
            var browser = global2.navigator, plugins = browser && browser.plugins;
            return [+/* @__PURE__ */ new Date(), global2, plugins, global2.screen, tostring(pool)];
          }
        }
        function tostring(a) {
          return String.fromCharCode.apply(0, a);
        }
        mixkey(math.random(), pool);
        if (module3.exports) {
          module3.exports = seedrandom2;
          try {
            nodecrypto = require$$0;
          } catch (ex) {
          }
        } else {
          math["seed" + rngname] = seedrandom2;
        }
      })(
        // global: `self` in browsers (including strict mode and web workers),
        // otherwise `this` in Node and other environments
        typeof self !== "undefined" ? self : commonjsGlobal,
        [],
        // pool: entropy pool starts empty
        Math
        // math: package containing random, pow, and seedrandom
      );
    })(seedrandom$1);
    var seedrandomExports = seedrandom$1.exports;
    var alea = aleaExports;
    var xor128 = xor128Exports;
    var xorwow = xorwowExports;
    var xorshift7 = xorshift7Exports;
    var xor4096 = xor4096Exports;
    var tychei = tycheiExports;
    var sr = seedrandomExports;
    sr.alea = alea;
    sr.xor128 = xor128;
    sr.xorwow = xorwow;
    sr.xorshift7 = xorshift7;
    sr.xor4096 = xor4096;
    sr.tychei = tychei;
    var seedrandom = sr;
    function deepMap(input, mapFn) {
      return deepMapInternal(input, mapFn);
    }
    function deepMapInternal(input, mapFn, seen, containedIn) {
      if (seen === void 0) {
        seen = /* @__PURE__ */ new Map();
      }
      if (containedIn === void 0) {
        containedIn = /* @__PURE__ */ new Set();
      }
      if (input == null) {
        return null;
      }
      if (typeof Blob === "function" && input instanceof Blob) {
        return input.slice();
      }
      if (containedIn.has(input)) {
        throw new Error("Circular references are not supported.");
      }
      if (seen.has(input)) {
        return seen.get(input);
      }
      var result = mapFn(input);
      if (result.recurse && result.value !== null) {
        throw new Error("A deep map function may not return both a value and recurse=true.");
      }
      if (!result.recurse) {
        seen.set(input, result.value);
        return result.value;
      } else if (isIterable(input)) {
        var mappedIterable = Array.isArray(input) ? [] : {};
        containedIn.add(input);
        for (var k in input) {
          var child = input[k];
          var childResult = deepMapInternal(child, mapFn, seen, containedIn);
          mappedIterable[k] = childResult;
        }
        containedIn.delete(input);
        if (input.__proto__) {
          mappedIterable.__proto__ = input.__proto__;
        }
        return mappedIterable;
      } else {
        throw new Error("Can't recurse into non-iterable type: ".concat(input));
      }
    }
    function deepZip(inputs, zipFn) {
      if (zipFn === void 0) {
        zipFn = zipToList;
      }
      return deepZipInternal(inputs, zipFn);
    }
    function deepZipInternal(inputs, zipFn, containedIn) {
      if (containedIn === void 0) {
        containedIn = /* @__PURE__ */ new Set();
      }
      var input = inputs[0];
      if (containedIn.has(input)) {
        throw new Error("Circular references are not supported.");
      }
      var result = zipFn(inputs);
      if (result.recurse && result.value !== null) {
        throw new Error("A deep zip function may not return both a value and recurse=true.");
      }
      if (!result.recurse) {
        return result.value;
      } else if (isIterable(input)) {
        var mappedIterable = Array.isArray(input) ? [] : {};
        containedIn.add(input);
        var _loop_1 = function(k2) {
          var children = inputs.map(function(x) {
            return x[k2];
          });
          var childResult = deepZipInternal(children, zipFn, containedIn);
          mappedIterable[k2] = childResult;
        };
        for (var k in input) {
          _loop_1(k);
        }
        containedIn.delete(input);
        return mappedIterable;
      } else {
        throw new Error("Can't recurse into non-iterable type: ".concat(input));
      }
    }
    function zipToList(x) {
      if (x === null) {
        return null;
      }
      if (isIterable(x[0])) {
        return { value: null, recurse: true };
      } else {
        return { value: x, recurse: false };
      }
    }
    function deepMapAndAwaitAll(input, mapFn) {
      return __awaiter(this, void 0, void 0, function() {
        var seen, _a, _b, key, value, mappedValue, e_1_1, result;
        var e_1, _c;
        return __generator(this, function(_d) {
          switch (_d.label) {
            case 0:
              seen = /* @__PURE__ */ new Map();
              deepMapInternal(input, mapFn, seen);
              _d.label = 1;
            case 1:
              _d.trys.push([1, 6, 7, 8]);
              _a = __values(Array.from(seen.keys())), _b = _a.next();
              _d.label = 2;
            case 2:
              if (!!_b.done) return [3, 5];
              key = _b.value;
              value = seen.get(key);
              if (!tf__namespace.util.isPromise(value)) return [3, 4];
              return [4, value];
            case 3:
              mappedValue = _d.sent();
              seen.set(key, mappedValue);
              _d.label = 4;
            case 4:
              _b = _a.next();
              return [3, 2];
            case 5:
              return [3, 8];
            case 6:
              e_1_1 = _d.sent();
              e_1 = { error: e_1_1 };
              return [3, 8];
            case 7:
              try {
                if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
              } finally {
                if (e_1) throw e_1.error;
              }
              return [
                7
                /*endfinally*/
              ];
            case 8:
              result = deepMapInternal(input, mapFn, seen);
              return [2, result];
          }
        });
      });
    }
    function isIterable(obj) {
      var isTextDecoder = false;
      if (tf__namespace.env().get("IS_BROWSER")) {
        isTextDecoder = obj instanceof TextDecoder;
      } else {
        var StringDecoder = require("string_decoder").StringDecoder;
        isTextDecoder = obj instanceof StringDecoder;
      }
      return obj != null && !ArrayBuffer.isView(obj) && (Array.isArray(obj) || typeof obj === "object" && !(obj instanceof tf__namespace.Tensor) && !(obj instanceof Promise) && !isTextDecoder);
    }
    function canTensorify(obj) {
      return obj == null || isPrimitive(obj) || Array.isArray(obj) || typeof obj === "object" && obj instanceof tf__namespace.Tensor || tf__namespace.util.isTypedArray(obj);
    }
    function isPrimitive(value) {
      return value === null || typeof value !== "object" && typeof value !== "function";
    }
    function deepClone(container) {
      return deepMap(container, cloneIfTensor);
    }
    function cloneIfTensor(item) {
      if (item instanceof tf__namespace.Tensor) {
        return { value: item.clone(), recurse: false };
      } else if (isIterable(item)) {
        return { value: null, recurse: true };
      } else {
        return { value: item, recurse: false };
      }
    }
    var RingBuffer = (
      /** @class */
      function() {
        function RingBuffer2(capacity) {
          this.capacity = capacity;
          this.begin = 0;
          this.end = 0;
          if (capacity == null) {
            throw new RangeError("Can't create a ring buffer of unknown capacity.");
          }
          if (capacity < 1) {
            throw new RangeError("Can't create ring buffer of capacity < 1.");
          }
          this.data = new Array(capacity);
          this.doubledCapacity = 2 * capacity;
        }
        RingBuffer2.prototype.wrap = function(index) {
          while (index < 0) {
            index += this.doubledCapacity;
          }
          return index % this.doubledCapacity;
        };
        RingBuffer2.prototype.get = function(index) {
          if (index < 0) {
            throw new RangeError("Can't get item at a negative index.");
          }
          return this.data[index % this.capacity];
        };
        RingBuffer2.prototype.set = function(index, value) {
          if (index < 0) {
            throw new RangeError("Can't set item at a negative index.");
          }
          this.data[index % this.capacity] = value;
        };
        RingBuffer2.prototype.length = function() {
          var length = this.end - this.begin;
          if (length < 0) {
            length = this.doubledCapacity + length;
          }
          return length;
        };
        RingBuffer2.prototype.isFull = function() {
          return this.length() === this.capacity;
        };
        RingBuffer2.prototype.isEmpty = function() {
          return this.length() === 0;
        };
        RingBuffer2.prototype.push = function(value) {
          if (this.isFull()) {
            throw new RangeError("Ring buffer is full.");
          }
          this.set(this.end, value);
          this.end = this.wrap(this.end + 1);
        };
        RingBuffer2.prototype.pushAll = function(values) {
          var e_1, _a;
          try {
            for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {
              var value = values_1_1.value;
              this.push(value);
            }
          } catch (e_1_1) {
            e_1 = { error: e_1_1 };
          } finally {
            try {
              if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1);
            } finally {
              if (e_1) throw e_1.error;
            }
          }
        };
        RingBuffer2.prototype.pop = function() {
          if (this.isEmpty()) {
            throw new RangeError("Ring buffer is empty.");
          }
          this.end = this.wrap(this.end - 1);
          var result = this.get(this.end);
          this.set(this.end, void 0);
          return result;
        };
        RingBuffer2.prototype.unshift = function(value) {
          if (this.isFull()) {
            throw new RangeError("Ring buffer is full.");
          }
          this.begin = this.wrap(this.begin - 1);
          this.set(this.begin, value);
        };
        RingBuffer2.prototype.shift = function() {
          if (this.isEmpty()) {
            throw new RangeError("Ring buffer is empty.");
          }
          var result = this.get(this.begin);
          this.set(this.begin, void 0);
          this.begin = this.wrap(this.begin + 1);
          return result;
        };
        RingBuffer2.prototype.shuffleExcise = function(relativeIndex) {
          if (this.isEmpty()) {
            throw new RangeError("Ring buffer is empty.");
          }
          var index = this.wrap(this.begin + relativeIndex);
          var result = this.get(index);
          this.set(index, this.pop());
          return result;
        };
        return RingBuffer2;
      }()
    );
    var GrowingRingBuffer = (
      /** @class */
      function(_super) {
        __extends(GrowingRingBuffer2, _super);
        function GrowingRingBuffer2() {
          return _super.call(this, GrowingRingBuffer2.INITIAL_CAPACITY) || this;
        }
        GrowingRingBuffer2.prototype.isFull = function() {
          return false;
        };
        GrowingRingBuffer2.prototype.push = function(value) {
          if (_super.prototype.isFull.call(this)) {
            this.expand();
          }
          _super.prototype.push.call(this, value);
        };
        GrowingRingBuffer2.prototype.unshift = function(value) {
          if (_super.prototype.isFull.call(this)) {
            this.expand();
          }
          _super.prototype.unshift.call(this, value);
        };
        GrowingRingBuffer2.prototype.expand = function() {
          var newCapacity = this.capacity * 2;
          var newData = new Array(newCapacity);
          var len = this.length();
          for (var i = 0; i < len; i++) {
            newData[i] = this.get(this.wrap(this.begin + i));
          }
          this.data = newData;
          this.capacity = newCapacity;
          this.doubledCapacity = 2 * this.capacity;
          this.begin = 0;
          this.end = len;
        };
        return GrowingRingBuffer2;
      }(RingBuffer)
    );
    GrowingRingBuffer.INITIAL_CAPACITY = 32;
    function iteratorFromItems(items) {
      return new ArrayIterator(items);
    }
    function iteratorFromFunction(func2) {
      return new FunctionCallIterator(func2);
    }
    function iteratorFromConcatenated(baseIterators, baseErrorHandler) {
      return new ChainedIterator(baseIterators, baseErrorHandler);
    }
    function iteratorFromZipped(iterators, mismatchMode) {
      if (mismatchMode === void 0) {
        mismatchMode = ZipMismatchMode.FAIL;
      }
      return new ZipIterator(iterators, mismatchMode);
    }
    var LazyIterator = (
      /** @class */
      function() {
        function LazyIterator2() {
        }
        LazyIterator2.prototype.toArray = function() {
          return __awaiter(this, void 0, void 0, function() {
            var result, x;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  result = [];
                  return [4, this.next()];
                case 1:
                  x = _a.sent();
                  _a.label = 2;
                case 2:
                  if (!!x.done) return [3, 4];
                  result.push(x.value);
                  return [4, this.next()];
                case 3:
                  x = _a.sent();
                  return [3, 2];
                case 4:
                  return [2, result];
              }
            });
          });
        };
        LazyIterator2.prototype.toArrayForTest = function() {
          return __awaiter(this, void 0, void 0, function() {
            var stream, result, x;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  stream = this.prefetch(100);
                  result = [];
                  return [4, stream.next()];
                case 1:
                  x = _a.sent();
                  _a.label = 2;
                case 2:
                  if (!!x.done) return [3, 4];
                  result.push(x.value);
                  return [4, stream.next()];
                case 3:
                  x = _a.sent();
                  return [3, 2];
                case 4:
                  return [2, result];
              }
            });
          });
        };
        LazyIterator2.prototype.resolveFully = function() {
          return __awaiter(this, void 0, void 0, function() {
            var x;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.next()];
                case 1:
                  x = _a.sent();
                  _a.label = 2;
                case 2:
                  if (!!x.done) return [3, 4];
                  return [4, this.next()];
                case 3:
                  x = _a.sent();
                  return [3, 2];
                case 4:
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        LazyIterator2.prototype.resolveWhile = function(predicate) {
          return __awaiter(this, void 0, void 0, function() {
            var x, shouldContinue;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.next()];
                case 1:
                  x = _a.sent();
                  shouldContinue = predicate(x.value);
                  _a.label = 2;
                case 2:
                  if (!(!x.done && shouldContinue)) return [3, 4];
                  return [4, this.next()];
                case 3:
                  x = _a.sent();
                  shouldContinue = predicate(x.value);
                  return [3, 2];
                case 4:
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        LazyIterator2.prototype.handleErrors = function(handler) {
          return new ErrorHandlingLazyIterator(this, handler);
        };
        LazyIterator2.prototype.filter = function(predicate) {
          return new FilterIterator(this, predicate);
        };
        LazyIterator2.prototype.map = function(transform) {
          return new MapIterator(this, transform);
        };
        LazyIterator2.prototype.mapAsync = function(transform) {
          return new AsyncMapIterator(this, transform);
        };
        LazyIterator2.prototype.serialMapAsync = function(transform) {
          return new AsyncMapIterator(this, transform).serial();
        };
        LazyIterator2.prototype.flatmap = function(transform) {
          return new FlatmapIterator(this, transform);
        };
        LazyIterator2.prototype.forEachAsync = function(f) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              return [2, this.map(f).resolveFully()];
            });
          });
        };
        LazyIterator2.prototype.serialForEach = function(f) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              return [2, this.serialMapAsync(f).resolveWhile(function(x) {
                return x === true;
              })];
            });
          });
        };
        LazyIterator2.prototype.rowMajorBatch = function(batchSize, smallLastBatch) {
          if (smallLastBatch === void 0) {
            smallLastBatch = true;
          }
          return new RowMajorBatchIterator(this, batchSize, smallLastBatch);
        };
        LazyIterator2.prototype.columnMajorBatch = function(batchSize, smallLastBatch, zipFn) {
          if (smallLastBatch === void 0) {
            smallLastBatch = true;
          }
          if (zipFn === void 0) {
            zipFn = zipToList;
          }
          var rowBatches = this.rowMajorBatch(batchSize, smallLastBatch);
          return rowBatches.map(function(x) {
            return deepZip(x, zipFn);
          });
        };
        LazyIterator2.prototype.concatenate = function(iterator, baseErrorHandler) {
          return new ChainedIterator(iteratorFromItems([this, iterator]), baseErrorHandler);
        };
        LazyIterator2.prototype.take = function(count) {
          if (count < 0 || count == null) {
            return this;
          }
          return new TakeIterator(this, count);
        };
        LazyIterator2.prototype.skip = function(count) {
          if (count < 0 || count == null) {
            return this;
          }
          return new SkipIterator(this, count);
        };
        LazyIterator2.prototype.prefetch = function(bufferSize) {
          return new PrefetchIterator(this, bufferSize);
        };
        LazyIterator2.prototype.shuffle = function(windowSize, seed) {
          return new ShuffleIterator(this, windowSize, seed);
        };
        LazyIterator2.prototype.serial = function() {
          return new SerialIterator(this);
        };
        return LazyIterator2;
      }()
    );
    var ArrayIterator = (
      /** @class */
      function(_super) {
        __extends(ArrayIterator2, _super);
        function ArrayIterator2(items) {
          var _this = _super.call(this) || this;
          _this.items = items;
          _this.trav = 0;
          return _this;
        }
        ArrayIterator2.prototype.summary = function() {
          return "Array of ".concat(this.items.length, " items");
        };
        ArrayIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            var item;
            return __generator(this, function(_a) {
              if (this.trav >= this.items.length) {
                return [2, { value: null, done: true }];
              }
              item = this.items[this.trav];
              this.trav++;
              return [2, { value: deepClone(item), done: false }];
            });
          });
        };
        return ArrayIterator2;
      }(LazyIterator)
    );
    var FunctionCallIterator = (
      /** @class */
      function(_super) {
        __extends(FunctionCallIterator2, _super);
        function FunctionCallIterator2(nextFn) {
          var _this = _super.call(this) || this;
          _this.nextFn = nextFn;
          return _this;
        }
        FunctionCallIterator2.prototype.summary = function() {
          return "Function call";
        };
        FunctionCallIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              try {
                return [2, this.nextFn()];
              } catch (e) {
                e.message = "Error thrown while iterating through a dataset: ".concat(e.message);
                throw e;
              }
              return [
                2
                /*return*/
              ];
            });
          });
        };
        return FunctionCallIterator2;
      }(LazyIterator)
    );
    var SerialIterator = (
      /** @class */
      function(_super) {
        __extends(SerialIterator2, _super);
        function SerialIterator2(upstream) {
          var _this = _super.call(this) || this;
          _this.upstream = upstream;
          _this.lastRead = Promise.resolve({ value: null, done: false });
          return _this;
        }
        SerialIterator2.prototype.summary = function() {
          return "".concat(this.upstream.summary(), " -> Serial");
        };
        SerialIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            var _this = this;
            return __generator(this, function(_a) {
              this.lastRead = this.lastRead.then(function() {
                return _this.serialNext();
              });
              return [2, this.lastRead];
            });
          });
        };
        SerialIterator2.prototype.serialNext = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              return [2, this.upstream.next()];
            });
          });
        };
        return SerialIterator2;
      }(LazyIterator)
    );
    var SkipIterator = (
      /** @class */
      function(_super) {
        __extends(SkipIterator2, _super);
        function SkipIterator2(upstream, maxCount) {
          var _this = _super.call(this) || this;
          _this.upstream = upstream;
          _this.maxCount = maxCount;
          _this.count = 0;
          _this.lastRead = Promise.resolve({ value: null, done: false });
          return _this;
        }
        SkipIterator2.prototype.summary = function() {
          return "".concat(this.upstream.summary(), " -> Skip");
        };
        SkipIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            var _this = this;
            return __generator(this, function(_a) {
              this.lastRead = this.lastRead.then(function() {
                return _this.serialNext();
              });
              return [2, this.lastRead];
            });
          });
        };
        SkipIterator2.prototype.serialNext = function() {
          return __awaiter(this, void 0, void 0, function() {
            var skipped;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  if (!(this.count++ < this.maxCount)) return [3, 2];
                  return [4, this.upstream.next()];
                case 1:
                  skipped = _a.sent();
                  if (skipped.done) {
                    return [2, skipped];
                  }
                  tf__namespace.dispose(skipped.value);
                  return [3, 0];
                case 2:
                  return [2, this.upstream.next()];
              }
            });
          });
        };
        return SkipIterator2;
      }(LazyIterator)
    );
    var TakeIterator = (
      /** @class */
      function(_super) {
        __extends(TakeIterator2, _super);
        function TakeIterator2(upstream, maxCount) {
          var _this = _super.call(this) || this;
          _this.upstream = upstream;
          _this.maxCount = maxCount;
          _this.count = 0;
          return _this;
        }
        TakeIterator2.prototype.summary = function() {
          return "".concat(this.upstream.summary(), " -> Take");
        };
        TakeIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              if (this.count++ >= this.maxCount) {
                return [2, { value: null, done: true }];
              }
              return [2, this.upstream.next()];
            });
          });
        };
        return TakeIterator2;
      }(LazyIterator)
    );
    var RowMajorBatchIterator = (
      /** @class */
      function(_super) {
        __extends(RowMajorBatchIterator2, _super);
        function RowMajorBatchIterator2(upstream, batchSize, enableSmallLastBatch) {
          if (enableSmallLastBatch === void 0) {
            enableSmallLastBatch = true;
          }
          var _this = _super.call(this) || this;
          _this.upstream = upstream;
          _this.batchSize = batchSize;
          _this.enableSmallLastBatch = enableSmallLastBatch;
          _this.lastRead = Promise.resolve({ value: null, done: false });
          return _this;
        }
        RowMajorBatchIterator2.prototype.summary = function() {
          return "".concat(this.upstream.summary(), " -> RowMajorBatch");
        };
        RowMajorBatchIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            var _this = this;
            return __generator(this, function(_a) {
              this.lastRead = this.lastRead.then(function() {
                return _this.serialNext();
              });
              return [2, this.lastRead];
            });
          });
        };
        RowMajorBatchIterator2.prototype.serialNext = function() {
          return __awaiter(this, void 0, void 0, function() {
            var batch, item;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  batch = [];
                  _a.label = 1;
                case 1:
                  if (!(batch.length < this.batchSize)) return [3, 3];
                  return [4, this.upstream.next()];
                case 2:
                  item = _a.sent();
                  if (item.done) {
                    if (this.enableSmallLastBatch && batch.length > 0) {
                      return [2, { value: batch, done: false }];
                    }
                    return [2, { value: null, done: true }];
                  }
                  batch.push(item.value);
                  return [3, 1];
                case 3:
                  return [2, { value: batch, done: false }];
              }
            });
          });
        };
        return RowMajorBatchIterator2;
      }(LazyIterator)
    );
    var FilterIterator = (
      /** @class */
      function(_super) {
        __extends(FilterIterator2, _super);
        function FilterIterator2(upstream, predicate) {
          var _this = _super.call(this) || this;
          _this.upstream = upstream;
          _this.predicate = predicate;
          _this.lastRead = Promise.resolve({ value: null, done: false });
          return _this;
        }
        FilterIterator2.prototype.summary = function() {
          return "".concat(this.upstream.summary(), " -> Filter");
        };
        FilterIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            var _this = this;
            return __generator(this, function(_a) {
              this.lastRead = this.lastRead.then(function() {
                return _this.serialNext();
              });
              return [2, this.lastRead];
            });
          });
        };
        FilterIterator2.prototype.serialNext = function() {
          return __awaiter(this, void 0, void 0, function() {
            var item;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.upstream.next()];
                case 1:
                  item = _a.sent();
                  if (item.done || this.predicate(item.value)) {
                    return [2, item];
                  }
                  tf__namespace.dispose(item.value);
                  return [3, 0];
                case 2:
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        return FilterIterator2;
      }(LazyIterator)
    );
    var MapIterator = (
      /** @class */
      function(_super) {
        __extends(MapIterator2, _super);
        function MapIterator2(upstream, transform) {
          var _this = _super.call(this) || this;
          _this.upstream = upstream;
          _this.transform = transform;
          return _this;
        }
        MapIterator2.prototype.summary = function() {
          return "".concat(this.upstream.summary(), " -> Map");
        };
        MapIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            var item, inputTensors, mapped, outputTensors, inputTensors_1, inputTensors_1_1, t;
            var e_1, _a;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  return [4, this.upstream.next()];
                case 1:
                  item = _b.sent();
                  if (item.done) {
                    return [2, { value: null, done: true }];
                  }
                  inputTensors = tf__namespace.tensor_util.getTensorsInContainer(item.value);
                  mapped = this.transform(item.value);
                  outputTensors = tf__namespace.tensor_util.getTensorsInContainer(mapped);
                  try {
                    for (inputTensors_1 = __values(inputTensors), inputTensors_1_1 = inputTensors_1.next(); !inputTensors_1_1.done; inputTensors_1_1 = inputTensors_1.next()) {
                      t = inputTensors_1_1.value;
                      if (!tf__namespace.tensor_util.isTensorInList(t, outputTensors)) {
                        t.dispose();
                      }
                    }
                  } catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                  } finally {
                    try {
                      if (inputTensors_1_1 && !inputTensors_1_1.done && (_a = inputTensors_1.return)) _a.call(inputTensors_1);
                    } finally {
                      if (e_1) throw e_1.error;
                    }
                  }
                  return [2, { value: mapped, done: false }];
              }
            });
          });
        };
        return MapIterator2;
      }(LazyIterator)
    );
    var ErrorHandlingLazyIterator = (
      /** @class */
      function(_super) {
        __extends(ErrorHandlingLazyIterator2, _super);
        function ErrorHandlingLazyIterator2(upstream, handler) {
          var _this = _super.call(this) || this;
          _this.upstream = upstream;
          _this.handler = handler;
          _this.count = 0;
          _this.lastRead = Promise.resolve({ value: null, done: false });
          return _this;
        }
        ErrorHandlingLazyIterator2.prototype.summary = function() {
          return "".concat(this.upstream.summary(), " -> handleErrors");
        };
        ErrorHandlingLazyIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            var _this = this;
            return __generator(this, function(_a) {
              this.lastRead = this.lastRead.then(function() {
                return _this.serialNext();
              });
              return [2, this.lastRead];
            });
          });
        };
        ErrorHandlingLazyIterator2.prototype.serialNext = function() {
          return __awaiter(this, void 0, void 0, function() {
            var e_2;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  _a.label = 1;
                case 1:
                  _a.trys.push([1, 3, , 4]);
                  return [4, this.upstream.next()];
                case 2:
                  return [2, _a.sent()];
                case 3:
                  e_2 = _a.sent();
                  if (!this.handler(e_2)) {
                    return [2, { value: null, done: true }];
                  }
                  return [3, 4];
                case 4:
                  return [3, 0];
                case 5:
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        return ErrorHandlingLazyIterator2;
      }(LazyIterator)
    );
    var AsyncMapIterator = (
      /** @class */
      function(_super) {
        __extends(AsyncMapIterator2, _super);
        function AsyncMapIterator2(upstream, transform) {
          var _this = _super.call(this) || this;
          _this.upstream = upstream;
          _this.transform = transform;
          return _this;
        }
        AsyncMapIterator2.prototype.summary = function() {
          return "".concat(this.upstream.summary(), " -> AsyncMap");
        };
        AsyncMapIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            var item, inputTensors, mapped, outputTensors, inputTensors_2, inputTensors_2_1, t;
            var e_3, _a;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  return [4, this.upstream.next()];
                case 1:
                  item = _b.sent();
                  if (item.done) {
                    return [2, { value: null, done: true }];
                  }
                  inputTensors = tf__namespace.tensor_util.getTensorsInContainer(item.value);
                  return [4, this.transform(item.value)];
                case 2:
                  mapped = _b.sent();
                  outputTensors = tf__namespace.tensor_util.getTensorsInContainer(mapped);
                  try {
                    for (inputTensors_2 = __values(inputTensors), inputTensors_2_1 = inputTensors_2.next(); !inputTensors_2_1.done; inputTensors_2_1 = inputTensors_2.next()) {
                      t = inputTensors_2_1.value;
                      if (!tf__namespace.tensor_util.isTensorInList(t, outputTensors)) {
                        t.dispose();
                      }
                    }
                  } catch (e_3_1) {
                    e_3 = { error: e_3_1 };
                  } finally {
                    try {
                      if (inputTensors_2_1 && !inputTensors_2_1.done && (_a = inputTensors_2.return)) _a.call(inputTensors_2);
                    } finally {
                      if (e_3) throw e_3.error;
                    }
                  }
                  return [2, { value: mapped, done: false }];
              }
            });
          });
        };
        return AsyncMapIterator2;
      }(LazyIterator)
    );
    var OneToManyIterator = (
      /** @class */
      function(_super) {
        __extends(OneToManyIterator2, _super);
        function OneToManyIterator2() {
          var _this = _super.call(this) || this;
          _this.outputQueue = new GrowingRingBuffer();
          _this.lastRead = Promise.resolve({ value: null, done: false });
          return _this;
        }
        OneToManyIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            var _this = this;
            return __generator(this, function(_a) {
              this.lastRead = this.lastRead.then(function() {
                return _this.serialNext();
              });
              return [2, this.lastRead];
            });
          });
        };
        OneToManyIterator2.prototype.serialNext = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  if (!(this.outputQueue.length() === 0)) return [3, 2];
                  return [4, this.pump()];
                case 1:
                  if (!_a.sent()) {
                    return [2, { value: null, done: true }];
                  }
                  return [3, 0];
                case 2:
                  return [2, { value: this.outputQueue.shift(), done: false }];
              }
            });
          });
        };
        return OneToManyIterator2;
      }(LazyIterator)
    );
    var FlatmapIterator = (
      /** @class */
      function(_super) {
        __extends(FlatmapIterator2, _super);
        function FlatmapIterator2(upstream, transform) {
          var _this = _super.call(this) || this;
          _this.upstream = upstream;
          _this.transform = transform;
          return _this;
        }
        FlatmapIterator2.prototype.summary = function() {
          return "".concat(this.upstream.summary(), " -> Flatmap");
        };
        FlatmapIterator2.prototype.pump = function() {
          return __awaiter(this, void 0, void 0, function() {
            var item, inputTensors, mappedArray, outputTensors, inputTensors_3, inputTensors_3_1, t;
            var e_4, _a;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  return [4, this.upstream.next()];
                case 1:
                  item = _b.sent();
                  if (item.done) {
                    return [2, false];
                  }
                  inputTensors = tf__namespace.tensor_util.getTensorsInContainer(item.value);
                  mappedArray = this.transform(item.value);
                  outputTensors = tf__namespace.tensor_util.getTensorsInContainer(mappedArray);
                  this.outputQueue.pushAll(mappedArray);
                  try {
                    for (inputTensors_3 = __values(inputTensors), inputTensors_3_1 = inputTensors_3.next(); !inputTensors_3_1.done; inputTensors_3_1 = inputTensors_3.next()) {
                      t = inputTensors_3_1.value;
                      if (!tf__namespace.tensor_util.isTensorInList(t, outputTensors)) {
                        t.dispose();
                      }
                    }
                  } catch (e_4_1) {
                    e_4 = { error: e_4_1 };
                  } finally {
                    try {
                      if (inputTensors_3_1 && !inputTensors_3_1.done && (_a = inputTensors_3.return)) _a.call(inputTensors_3);
                    } finally {
                      if (e_4) throw e_4.error;
                    }
                  }
                  return [2, true];
              }
            });
          });
        };
        return FlatmapIterator2;
      }(OneToManyIterator)
    );
    var ChainedIterator = (
      /** @class */
      function(_super) {
        __extends(ChainedIterator2, _super);
        function ChainedIterator2(iterators, baseErrorHandler) {
          var _this = _super.call(this) || this;
          _this.baseErrorHandler = baseErrorHandler;
          _this.lastRead = null;
          _this.iterator = null;
          _this.moreIterators = iterators;
          return _this;
        }
        ChainedIterator2.prototype.summary = function() {
          var upstreamSummaries = "TODO: fill in upstream of chained summaries";
          return "".concat(upstreamSummaries, " -> Chained");
        };
        ChainedIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              this.lastRead = this.readFromChain(this.lastRead);
              return [2, this.lastRead];
            });
          });
        };
        ChainedIterator2.prototype.readFromChain = function(lastRead) {
          return __awaiter(this, void 0, void 0, function() {
            var iteratorResult, itemResult;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, lastRead];
                case 1:
                  _a.sent();
                  if (!(this.iterator == null)) return [3, 3];
                  return [4, this.moreIterators.next()];
                case 2:
                  iteratorResult = _a.sent();
                  if (iteratorResult.done) {
                    return [2, { value: null, done: true }];
                  }
                  this.iterator = iteratorResult.value;
                  if (this.baseErrorHandler != null) {
                    this.iterator = this.iterator.handleErrors(this.baseErrorHandler);
                  }
                  _a.label = 3;
                case 3:
                  return [4, this.iterator.next()];
                case 4:
                  itemResult = _a.sent();
                  if (itemResult.done) {
                    this.iterator = null;
                    return [2, this.readFromChain(lastRead)];
                  }
                  return [2, itemResult];
              }
            });
          });
        };
        return ChainedIterator2;
      }(LazyIterator)
    );
    var ZipMismatchMode;
    (function(ZipMismatchMode2) {
      ZipMismatchMode2[ZipMismatchMode2["FAIL"] = 0] = "FAIL";
      ZipMismatchMode2[ZipMismatchMode2["SHORTEST"] = 1] = "SHORTEST";
      ZipMismatchMode2[ZipMismatchMode2["LONGEST"] = 2] = "LONGEST";
    })(ZipMismatchMode || (ZipMismatchMode = {}));
    var ZipIterator = (
      /** @class */
      function(_super) {
        __extends(ZipIterator2, _super);
        function ZipIterator2(iterators, mismatchMode) {
          if (mismatchMode === void 0) {
            mismatchMode = ZipMismatchMode.FAIL;
          }
          var _this = _super.call(this) || this;
          _this.iterators = iterators;
          _this.mismatchMode = mismatchMode;
          _this.count = 0;
          _this.currentPromise = null;
          return _this;
        }
        ZipIterator2.prototype.summary = function() {
          var upstreamSummaries = "TODO: fill in upstream of zip summaries";
          return "{".concat(upstreamSummaries, "} -> Zip");
        };
        ZipIterator2.prototype.nextState = function(afterState) {
          return __awaiter(this, void 0, void 0, function() {
            function getNext(container) {
              if (container instanceof LazyIterator) {
                var result = container.next();
                return {
                  value: result.then(function(x) {
                    numIterators++;
                    if (x.done) {
                      iteratorsDone++;
                    }
                    return x.value;
                  }),
                  recurse: false
                };
              } else {
                return { value: null, recurse: true };
              }
            }
            var numIterators, iteratorsDone, mapped;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, afterState];
                case 1:
                  _a.sent();
                  numIterators = 0;
                  iteratorsDone = 0;
                  return [4, deepMapAndAwaitAll(this.iterators, getNext)];
                case 2:
                  mapped = _a.sent();
                  if (numIterators === iteratorsDone) {
                    return [2, { value: null, done: true }];
                  }
                  if (iteratorsDone > 0) {
                    switch (this.mismatchMode) {
                      case ZipMismatchMode.FAIL:
                        throw new Error("Zipped streams should have the same length. " + "Mismatched at element ".concat(this.count, "."));
                      case ZipMismatchMode.SHORTEST:
                        return [2, { value: null, done: true }];
                      case ZipMismatchMode.LONGEST:
                    }
                  }
                  this.count++;
                  return [2, { value: mapped, done: false }];
              }
            });
          });
        };
        ZipIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              this.currentPromise = this.nextState(this.currentPromise);
              return [2, this.currentPromise];
            });
          });
        };
        return ZipIterator2;
      }(LazyIterator)
    );
    var PrefetchIterator = (
      /** @class */
      function(_super) {
        __extends(PrefetchIterator2, _super);
        function PrefetchIterator2(upstream, bufferSize) {
          var _this = _super.call(this) || this;
          _this.upstream = upstream;
          _this.bufferSize = bufferSize;
          _this.buffer = new RingBuffer(bufferSize);
          return _this;
        }
        PrefetchIterator2.prototype.summary = function() {
          return "".concat(this.upstream.summary(), " -> Prefetch");
        };
        PrefetchIterator2.prototype.refill = function() {
          while (!this.buffer.isFull()) {
            var v = this.upstream.next();
            this.buffer.push(v);
          }
        };
        PrefetchIterator2.prototype.next = function() {
          this.refill();
          return this.buffer.shift();
        };
        return PrefetchIterator2;
      }(LazyIterator)
    );
    var ShuffleIterator = (
      /** @class */
      function(_super) {
        __extends(ShuffleIterator2, _super);
        function ShuffleIterator2(upstream, windowSize, seed) {
          var _this = _super.call(this, upstream, windowSize) || this;
          _this.upstream = upstream;
          _this.windowSize = windowSize;
          _this.upstreamExhausted = false;
          _this.random = seedrandom.alea(seed || tf__namespace.util.now().toString());
          _this.lastRead = Promise.resolve({ value: null, done: false });
          return _this;
        }
        ShuffleIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            var _this = this;
            return __generator(this, function(_a) {
              this.lastRead = this.lastRead.then(function() {
                return _this.serialNext();
              });
              return [2, this.lastRead];
            });
          });
        };
        ShuffleIterator2.prototype.randomInt = function(max) {
          return Math.floor(this.random() * max);
        };
        ShuffleIterator2.prototype.chooseIndex = function() {
          return this.randomInt(this.buffer.length());
        };
        ShuffleIterator2.prototype.serialNext = function() {
          return __awaiter(this, void 0, void 0, function() {
            var chosenIndex, result;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  if (!this.upstreamExhausted) {
                    this.refill();
                  }
                  _a.label = 1;
                case 1:
                  if (!!this.buffer.isEmpty()) return [3, 3];
                  chosenIndex = this.chooseIndex();
                  return [4, this.buffer.shuffleExcise(chosenIndex)];
                case 2:
                  result = _a.sent();
                  if (result.done) {
                    this.upstreamExhausted = true;
                  } else {
                    this.refill();
                    return [2, result];
                  }
                  return [3, 1];
                case 3:
                  return [2, { value: null, done: true }];
              }
            });
          });
        };
        return ShuffleIterator2;
      }(PrefetchIterator)
    );
    var Dataset = (
      /** @class */
      function() {
        function Dataset2() {
          this.size = null;
        }
        Dataset2.prototype.batch = function(batchSize, smallLastBatch) {
          var _this = this;
          if (smallLastBatch === void 0) {
            smallLastBatch = true;
          }
          var base = this;
          tf__namespace.util.assert(batchSize > 0, function() {
            return "batchSize needs to be positive, but it is\n      ".concat(batchSize);
          });
          var size;
          if (this.size === Infinity || this.size == null) {
            size = this.size;
          } else if (smallLastBatch) {
            size = Math.ceil(this.size / batchSize);
          } else {
            size = Math.floor(this.size / batchSize);
          }
          return datasetFromIteratorFn(function() {
            return __awaiter(_this, void 0, void 0, function() {
              return __generator(this, function(_a) {
                switch (_a.label) {
                  case 0:
                    return [4, base.iterator()];
                  case 1:
                    return [2, _a.sent().columnMajorBatch(batchSize, smallLastBatch, deepBatchConcat)];
                }
              });
            });
          }, size);
        };
        Dataset2.prototype.concatenate = function(dataset) {
          var _this = this;
          var base = this;
          var size;
          if (this.size === Infinity || dataset.size === Infinity) {
            size = Infinity;
          } else if (this.size != null && dataset.size != null) {
            size = this.size + dataset.size;
          } else {
            size = null;
          }
          return datasetFromIteratorFn(function() {
            return __awaiter(_this, void 0, void 0, function() {
              var _a, _b;
              return __generator(this, function(_c) {
                switch (_c.label) {
                  case 0:
                    return [4, base.iterator()];
                  case 1:
                    _b = (_a = _c.sent()).concatenate;
                    return [4, dataset.iterator()];
                  case 2:
                    return [2, _b.apply(_a, [_c.sent()])];
                }
              });
            });
          }, size);
        };
        Dataset2.prototype.filter = function(predicate) {
          var _this = this;
          var base = this;
          var size;
          if (this.size === Infinity) {
            size = Infinity;
          } else {
            size = null;
          }
          return datasetFromIteratorFn(function() {
            return __awaiter(_this, void 0, void 0, function() {
              return __generator(this, function(_a) {
                switch (_a.label) {
                  case 0:
                    return [4, base.iterator()];
                  case 1:
                    return [2, _a.sent().filter(function(x) {
                      return tf__namespace.tidy(function() {
                        return predicate(x);
                      });
                    })];
                }
              });
            });
          }, size);
        };
        Dataset2.prototype.forEachAsync = function(f) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.iterator()];
                case 1:
                  return [2, _a.sent().forEachAsync(f)];
              }
            });
          });
        };
        Dataset2.prototype.map = function(transform) {
          var _this = this;
          var base = this;
          return datasetFromIteratorFn(function() {
            return __awaiter(_this, void 0, void 0, function() {
              return __generator(this, function(_a) {
                switch (_a.label) {
                  case 0:
                    return [4, base.iterator()];
                  case 1:
                    return [2, _a.sent().map(function(x) {
                      return tf__namespace.tidy(function() {
                        return transform(x);
                      });
                    })];
                }
              });
            });
          }, this.size);
        };
        Dataset2.prototype.mapAsync = function(transform) {
          var _this = this;
          var base = this;
          return datasetFromIteratorFn(function() {
            return __awaiter(_this, void 0, void 0, function() {
              return __generator(this, function(_a) {
                switch (_a.label) {
                  case 0:
                    return [4, base.iterator()];
                  case 1:
                    return [2, _a.sent().mapAsync(transform)];
                }
              });
            });
          }, this.size);
        };
        Dataset2.prototype.prefetch = function(bufferSize) {
          var _this = this;
          if (bufferSize == null) {
            throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");
          }
          var base = this;
          return datasetFromIteratorFn(function() {
            return __awaiter(_this, void 0, void 0, function() {
              return __generator(this, function(_a) {
                switch (_a.label) {
                  case 0:
                    return [4, base.iterator()];
                  case 1:
                    return [2, _a.sent().prefetch(bufferSize)];
                }
              });
            });
          }, this.size);
        };
        Dataset2.prototype.repeat = function(count) {
          var _this = this;
          var base = this;
          var size;
          if (this.size != null && count > 0) {
            size = this.size * count;
          } else if (count === 0) {
            size = 0;
          } else if (this.size != null && (count === void 0 || count < 0)) {
            size = Infinity;
          } else {
            size = null;
          }
          return datasetFromIteratorFn(function() {
            return __awaiter(_this, void 0, void 0, function() {
              var iteratorIterator;
              var _this2 = this;
              return __generator(this, function(_a) {
                iteratorIterator = iteratorFromFunction(function() {
                  return __awaiter(_this2, void 0, void 0, function() {
                    var _a2;
                    return __generator(this, function(_b) {
                      switch (_b.label) {
                        case 0:
                          _a2 = {};
                          return [4, base.iterator()];
                        case 1:
                          return [2, (_a2.value = _b.sent(), _a2.done = false, _a2)];
                      }
                    });
                  });
                });
                return [2, iteratorFromConcatenated(iteratorIterator.take(count))];
              });
            });
          }, size);
        };
        Dataset2.prototype.skip = function(count) {
          var _this = this;
          var base = this;
          var size;
          if (this.size != null && count >= 0 && this.size >= count) {
            size = this.size - count;
          } else if (this.size != null && (this.size < count || count === void 0 || count < 0)) {
            size = 0;
          } else {
            size = null;
          }
          return datasetFromIteratorFn(function() {
            return __awaiter(_this, void 0, void 0, function() {
              return __generator(this, function(_a) {
                switch (_a.label) {
                  case 0:
                    return [4, base.iterator()];
                  case 1:
                    return [2, _a.sent().skip(count)];
                }
              });
            });
          }, size);
        };
        Dataset2.prototype.shuffle = function(bufferSize, seed, reshuffleEachIteration) {
          var _this = this;
          if (reshuffleEachIteration === void 0) {
            reshuffleEachIteration = true;
          }
          if (bufferSize == null || bufferSize < 0) {
            if (this.size == null) {
              throw new RangeError("`Dataset.shuffle()` requires bufferSize to be specified.");
            } else {
              throw 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 (".concat(this.size, " elements)"));
            }
          }
          var base = this;
          var random = seedrandom.alea(seed || tf__namespace.util.now().toString());
          return datasetFromIteratorFn(function() {
            return __awaiter(_this, void 0, void 0, function() {
              var seed2;
              return __generator(this, function(_a) {
                switch (_a.label) {
                  case 0:
                    seed2 = random.int32();
                    if (reshuffleEachIteration) {
                      seed2 += random.int32();
                    }
                    return [4, base.iterator()];
                  case 1:
                    return [2, _a.sent().shuffle(bufferSize, seed2.toString())];
                }
              });
            });
          }, this.size);
        };
        Dataset2.prototype.take = function(count) {
          var _this = this;
          var base = this;
          var size;
          if (this.size != null && this.size > count) {
            size = count;
          } else if (this.size != null && this.size <= count) {
            size = this.size;
          } else {
            size = null;
          }
          return datasetFromIteratorFn(function() {
            return __awaiter(_this, void 0, void 0, function() {
              return __generator(this, function(_a) {
                switch (_a.label) {
                  case 0:
                    return [4, base.iterator()];
                  case 1:
                    return [2, _a.sent().take(count)];
                }
              });
            });
          }, size);
        };
        Dataset2.prototype.toArray = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  if (this.size === Infinity) {
                    throw new Error("Can not convert infinite data stream to array.");
                  }
                  return [4, this.iterator()];
                case 1:
                  return [2, _a.sent().toArray()];
              }
            });
          });
        };
        Dataset2.prototype.toArrayForTest = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  if (this.size === Infinity) {
                    throw new Error("Can not convert infinite data stream to array.");
                  }
                  return [4, this.iterator()];
                case 1:
                  return [2, _a.sent().toArrayForTest()];
              }
            });
          });
        };
        return Dataset2;
      }()
    );
    Dataset.MAX_BUFFER_SIZE = 1e4;
    function datasetFromIteratorFn(iteratorFn, size) {
      if (size === void 0) {
        size = null;
      }
      return new /** @class */
      (function(_super) {
        __extends(class_1, _super);
        function class_1() {
          var _this = _super.apply(this, __spreadArray([], __read(arguments), false)) || this;
          _this.size = size;
          return _this;
        }
        class_1.prototype.iterator = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              return [2, iteratorFn()];
            });
          });
        };
        return class_1;
      }(Dataset))();
    }
    function array(items) {
      var _this = this;
      return datasetFromIteratorFn(function() {
        return __awaiter(_this, void 0, void 0, function() {
          return __generator(this, function(_a) {
            return [2, iteratorFromItems(items)];
          });
        });
      }, items.length);
    }
    function zip(datasets) {
      var _this = this;
      if (!isIterable(datasets)) {
        throw new Error("The argument to zip() must be an object or array.");
      }
      var size;
      if (Array.isArray(datasets)) {
        for (var i = 0; i < datasets.length; i++) {
          size = size == null ? datasets[i].size : Math.min(size, datasets[i].size);
        }
      } else if (datasets instanceof Object) {
        for (var ds in datasets) {
          size = size == null ? datasets[ds].size : Math.min(size, datasets[ds].size);
        }
      }
      return datasetFromIteratorFn(function() {
        return __awaiter(_this, void 0, void 0, function() {
          var streams;
          return __generator(this, function(_a) {
            switch (_a.label) {
              case 0:
                return [4, deepMapAndAwaitAll(datasets, function(d) {
                  if (d instanceof Dataset) {
                    return { value: d.iterator(), recurse: false };
                  } else if (isIterable(d)) {
                    return { value: null, recurse: true };
                  } else {
                    throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.");
                  }
                })];
              case 1:
                streams = _a.sent();
                return [2, iteratorFromZipped(streams, ZipMismatchMode.SHORTEST)];
            }
          });
        });
      }, size);
    }
    function deepBatchConcat(rows) {
      if (rows === null) {
        return null;
      }
      var exampleRow = rows[0];
      if (canTensorify(exampleRow)) {
        var value = batchConcat(rows);
        return { value, recurse: false };
      }
      return { value: null, recurse: true };
    }
    function batchConcat(arrays) {
      if (arrays.length === 0) {
        throw new Error("Can't make a batch of zero elements.");
      }
      if (arrays[0] instanceof tf__namespace.Tensor) {
        return tf__namespace.stack(arrays);
      } else {
        return tf__namespace.tensor(arrays);
      }
    }
    var TextLineDataset = (
      /** @class */
      function(_super) {
        __extends(TextLineDataset2, _super);
        function TextLineDataset2(input) {
          var _this = _super.call(this) || this;
          _this.input = input;
          return _this;
        }
        TextLineDataset2.prototype.iterator = function() {
          return __awaiter(this, void 0, void 0, function() {
            var inputIterator, utf8Iterator, lineIterator;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.input.iterator()];
                case 1:
                  inputIterator = _a.sent();
                  utf8Iterator = inputIterator.decodeUTF8();
                  lineIterator = utf8Iterator.split("\n").map(function(line) {
                    if (line.endsWith("\r")) {
                      line = line.slice(0, -1);
                    }
                    return line;
                  });
                  return [2, lineIterator];
              }
            });
          });
        };
        return TextLineDataset2;
      }(Dataset)
    );
    var CODE_QUOTE = '"';
    var STATE_OUT = Symbol("out");
    var STATE_FIELD = Symbol("field");
    var STATE_QUOTE = Symbol("quote");
    var STATE_QUOTE_AFTER_QUOTE = Symbol("quoteafterquote");
    var STATE_WITHIN_QUOTE_IN_QUOTE = Symbol("quoteinquote");
    var CSVDataset = (
      /** @class */
      function(_super) {
        __extends(CSVDataset2, _super);
        function CSVDataset2(input, csvConfig) {
          var _this = _super.call(this) || this;
          _this.input = input;
          _this.hasHeader = true;
          _this.fullColumnNames = null;
          _this.columnNamesValidated = false;
          _this.columnConfigs = null;
          _this.configuredColumnsOnly = false;
          _this.delimiter = ",";
          _this.delimWhitespace = false;
          _this.base = new TextLineDataset(input);
          if (!csvConfig) {
            csvConfig = {};
          }
          _this.hasHeader = csvConfig.hasHeader === false ? false : true;
          _this.fullColumnNames = csvConfig.columnNames;
          _this.columnConfigs = csvConfig.columnConfigs;
          _this.configuredColumnsOnly = csvConfig.configuredColumnsOnly;
          if (csvConfig.delimWhitespace) {
            tf.util.assert(csvConfig.delimiter == null, function() {
              return "Delimiter should not be provided when delimWhitespace is true.";
            });
            _this.delimWhitespace = true;
            _this.delimiter = " ";
          } else {
            _this.delimiter = csvConfig.delimiter ? csvConfig.delimiter : ",";
          }
          return _this;
        }
        CSVDataset2.prototype.columnNames = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  if (!!this.columnNamesValidated) return [3, 2];
                  return [4, this.setColumnNames()];
                case 1:
                  _a.sent();
                  _a.label = 2;
                case 2:
                  return [2, this.configuredColumnsOnly ? Object.keys(this.columnConfigs) : this.fullColumnNames];
              }
            });
          });
        };
        CSVDataset2.prototype.setColumnNames = function() {
          return __awaiter(this, void 0, void 0, function() {
            var columnNamesFromFile, counts, duplicateNames, _a, _b, key, index;
            var e_1, _c;
            var _this = this;
            return __generator(this, function(_d) {
              switch (_d.label) {
                case 0:
                  return [4, this.maybeReadHeaderLine()];
                case 1:
                  columnNamesFromFile = _d.sent();
                  if (!this.fullColumnNames && !columnNamesFromFile) {
                    throw new Error("Column names must be provided if there is no header line.");
                  } else if (this.fullColumnNames && columnNamesFromFile) {
                    tf.util.assert(columnNamesFromFile.length === this.fullColumnNames.length, function() {
                      return "The length of provided columnNames (" + _this.fullColumnNames.length.toString() + ") does not match the length of the header line read from file (" + columnNamesFromFile.length.toString() + ").";
                    });
                  }
                  if (!this.fullColumnNames) {
                    this.fullColumnNames = columnNamesFromFile;
                  }
                  counts = this.fullColumnNames.reduce(function(countAcc, name) {
                    countAcc[name] = countAcc[name] + 1 || 1;
                    return countAcc;
                  }, {});
                  duplicateNames = Object.keys(counts).filter(function(name) {
                    return counts[name] > 1;
                  });
                  tf.util.assert(duplicateNames.length === 0, function() {
                    return "Duplicate column names found: " + duplicateNames.toString();
                  });
                  if (this.columnConfigs) {
                    try {
                      for (_a = __values(Object.keys(this.columnConfigs)), _b = _a.next(); !_b.done; _b = _a.next()) {
                        key = _b.value;
                        index = this.fullColumnNames.indexOf(key);
                        if (index === -1) {
                          throw new Error('The key "' + key + '" provided in columnConfigs does not match any of the column names (' + this.fullColumnNames.toString() + ").");
                        }
                      }
                    } catch (e_1_1) {
                      e_1 = { error: e_1_1 };
                    } finally {
                      try {
                        if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
                      } finally {
                        if (e_1) throw e_1.error;
                      }
                    }
                  }
                  this.columnNamesValidated = true;
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        CSVDataset2.prototype.maybeReadHeaderLine = function() {
          return __awaiter(this, void 0, void 0, function() {
            var iter, firstElement, firstLine, headers;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  if (!this.hasHeader) return [3, 3];
                  return [4, this.base.iterator()];
                case 1:
                  iter = _a.sent();
                  return [4, iter.next()];
                case 2:
                  firstElement = _a.sent();
                  if (firstElement.done) {
                    throw new Error("No data was found for CSV parsing.");
                  }
                  firstLine = firstElement.value;
                  headers = this.parseRow(firstLine, false);
                  return [2, headers];
                case 3:
                  return [2, null];
              }
            });
          });
        };
        CSVDataset2.prototype.iterator = function() {
          return __awaiter(this, void 0, void 0, function() {
            var lines;
            var _this = this;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  if (!!this.columnNamesValidated) return [3, 2];
                  return [4, this.setColumnNames()];
                case 1:
                  _a.sent();
                  _a.label = 2;
                case 2:
                  return [4, this.base.iterator()];
                case 3:
                  lines = _a.sent();
                  if (this.hasHeader) {
                    lines = lines.skip(1);
                  }
                  return [2, lines.map(function(x) {
                    return _this.makeDataElement(x);
                  })];
              }
            });
          });
        };
        CSVDataset2.prototype.makeDataElement = function(line) {
          var values = this.parseRow(line);
          var features = {};
          var labels = {};
          for (var i = 0; i < this.fullColumnNames.length; i++) {
            var key = this.fullColumnNames[i];
            var config = this.columnConfigs ? this.columnConfigs[key] : null;
            if (this.configuredColumnsOnly && !config) {
              continue;
            } else {
              var value = values[i];
              var parsedValue = null;
              if (value === "") {
                if (config && config.default !== void 0) {
                  parsedValue = config.default;
                } else if (config && (config.required || config.isLabel)) {
                  throw new Error("Required column ".concat(key, " is empty in this line: ").concat(line));
                } else {
                  parsedValue = void 0;
                }
              } else {
                var valueAsNum = Number(value);
                if (isNaN(valueAsNum)) {
                  if (config && config.dtype === "bool") {
                    parsedValue = this.getBoolean(value);
                  } else {
                    parsedValue = value;
                  }
                } else if (!config || !config.dtype) {
                  parsedValue = valueAsNum;
                } else {
                  switch (config.dtype) {
                    case "float32":
                      parsedValue = valueAsNum;
                      break;
                    case "int32":
                      parsedValue = Math.floor(valueAsNum);
                      break;
                    case "bool":
                      parsedValue = this.getBoolean(value);
                      break;
                    default:
                      parsedValue = valueAsNum;
                  }
                }
              }
              config && config.isLabel ? labels[key] = parsedValue : features[key] = parsedValue;
            }
          }
          if (Object.keys(labels).length === 0) {
            return features;
          } else {
            return { xs: features, ys: labels };
          }
        };
        CSVDataset2.prototype.getBoolean = function(value) {
          if (value === "1" || value.toLowerCase() === "true") {
            return 1;
          } else {
            return 0;
          }
        };
        CSVDataset2.prototype.parseRow = function(line, validateElementCount) {
          if (validateElementCount === void 0) {
            validateElementCount = true;
          }
          var result = [];
          var readOffset = 0;
          var readLength = line.length;
          var currentState = STATE_OUT;
          for (var i = 0; i < readLength; i++) {
            switch (currentState) {
              // Before enter a new field
              case STATE_OUT:
                switch (line.charAt(i)) {
                  // Enter a quoted field
                  case CODE_QUOTE:
                    readOffset = i + 1;
                    currentState = STATE_QUOTE;
                    break;
                  // Read an empty field
                  case this.delimiter:
                    readOffset = i + 1;
                    if (this.delimiter === " " && this.delimWhitespace) {
                      break;
                    }
                    result.push("");
                    currentState = STATE_OUT;
                    break;
                  // Enter an unquoted field
                  default:
                    currentState = STATE_FIELD;
                    readOffset = i;
                    break;
                }
                break;
              // In an unquoted field
              case STATE_FIELD:
                switch (line.charAt(i)) {
                  // Exit an unquoted field, add it to result
                  case this.delimiter:
                    result.push(line.substring(readOffset, i));
                    currentState = STATE_OUT;
                    readOffset = i + 1;
                    break;
                }
                break;
              // In a quoted field
              case STATE_QUOTE:
                switch (line.charAt(i)) {
                  // Read a quote after a quote
                  case CODE_QUOTE:
                    currentState = STATE_QUOTE_AFTER_QUOTE;
                    break;
                }
                break;
              // This state means it's right after a second quote in a field
              case STATE_QUOTE_AFTER_QUOTE:
                switch (line.charAt(i)) {
                  // Finished a quoted field
                  case this.delimiter:
                    result.push(line.substring(readOffset, i - 1));
                    currentState = STATE_OUT;
                    readOffset = i + 1;
                    break;
                  // Finished a quoted part in a quoted field
                  case CODE_QUOTE:
                    currentState = STATE_QUOTE;
                    break;
                  // In a quoted part in a quoted field
                  default:
                    currentState = STATE_WITHIN_QUOTE_IN_QUOTE;
                    break;
                }
                break;
              case STATE_WITHIN_QUOTE_IN_QUOTE:
                switch (line.charAt(i)) {
                  // Exit a quoted part in a quoted field
                  case CODE_QUOTE:
                    currentState = STATE_QUOTE;
                    break;
                }
                break;
            }
          }
          if (currentState === STATE_QUOTE_AFTER_QUOTE) {
            result.push(line.substring(readOffset, readLength - 1));
          } else {
            result.push(line.substring(readOffset));
          }
          if (validateElementCount && result.length !== this.fullColumnNames.length) {
            throw new Error("Invalid row in csv file. Should have ".concat(this.fullColumnNames.length, " elements in a row, but got ").concat(result));
          }
          return result;
        };
        return CSVDataset2;
      }(Dataset)
    );
    var MicrophoneIterator = (
      /** @class */
      function(_super) {
        __extends(MicrophoneIterator2, _super);
        function MicrophoneIterator2(microphoneConfig) {
          var _this = _super.call(this) || this;
          _this.microphoneConfig = microphoneConfig;
          _this.isClosed = false;
          _this.fftSize = microphoneConfig.fftSize || 1024;
          var fftSizeLog2 = Math.log2(_this.fftSize);
          if (_this.fftSize < 0 || fftSizeLog2 < 4 || fftSizeLog2 > 14 || !Number.isInteger(fftSizeLog2)) {
            throw new Error("Invalid fftSize: it must be a power of 2 between " + "2 to 4 and 2 to 14, but got ".concat(_this.fftSize));
          }
          _this.numFrames = microphoneConfig.numFramesPerSpectrogram || 43;
          _this.sampleRateHz = microphoneConfig.sampleRateHz;
          _this.columnTruncateLength = microphoneConfig.columnTruncateLength || _this.fftSize;
          _this.audioTrackConstraints = microphoneConfig.audioTrackConstraints;
          _this.smoothingTimeConstant = microphoneConfig.smoothingTimeConstant || 0;
          _this.includeSpectrogram = microphoneConfig.includeSpectrogram === false ? false : true;
          _this.includeWaveform = microphoneConfig.includeWaveform === true ? true : false;
          if (!_this.includeSpectrogram && !_this.includeWaveform) {
            throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.");
          }
          return _this;
        }
        MicrophoneIterator2.prototype.summary = function() {
          return "microphone";
        };
        MicrophoneIterator2.create = function(microphoneConfig) {
          if (microphoneConfig === void 0) {
            microphoneConfig = {};
          }
          return __awaiter(this, void 0, void 0, function() {
            var microphoneIterator;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  if (!tf.env().get("IS_BROWSER")) {
                    throw new Error("microphone API is only supported in browser environment.");
                  }
                  microphoneIterator = new MicrophoneIterator2(microphoneConfig);
                  return [4, microphoneIterator.start()];
                case 1:
                  _a.sent();
                  return [2, microphoneIterator];
              }
            });
          });
        };
        MicrophoneIterator2.prototype.start = function() {
          return __awaiter(this, void 0, void 0, function() {
            var _a, e_1, ctxConstructor, streamSource;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  _b.trys.push([0, 2, , 3]);
                  _a = this;
                  return [4, navigator.mediaDevices.getUserMedia({
                    audio: this.audioTrackConstraints == null ? true : this.audioTrackConstraints,
                    video: false
                  })];
                case 1:
                  _a.stream = _b.sent();
                  return [3, 3];
                case 2:
                  e_1 = _b.sent();
                  throw new Error("Error thrown while initializing video stream: ".concat(e_1.message));
                case 3:
                  if (!this.stream) {
                    throw new Error("Could not obtain audio from microphone.");
                  }
                  ctxConstructor = // tslint:disable-next-line:no-any
                  window.AudioContext || window.webkitAudioContext;
                  this.audioContext = new ctxConstructor();
                  if (!this.sampleRateHz) {
                    this.sampleRateHz = this.audioContext.sampleRate;
                  } else if (this.audioContext.sampleRate !== this.sampleRateHz) {
                    throw new Error("Mismatch in sampling rate: " + "Expected: ".concat(this.sampleRateHz, "; ") + "Actual: ".concat(this.audioContext.sampleRate));
                  }
                  streamSource = this.audioContext.createMediaStreamSource(this.stream);
                  this.analyser = this.audioContext.createAnalyser();
                  this.analyser.fftSize = this.fftSize * 2;
                  this.analyser.smoothingTimeConstant = this.smoothingTimeConstant;
                  streamSource.connect(this.analyser);
                  this.freqData = new Float32Array(this.fftSize);
                  this.timeData = new Float32Array(this.fftSize);
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        };
        MicrophoneIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            var spectrogramTensor, waveformTensor, audioDataQueue, freqData, timeData;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  if (this.isClosed) {
                    return [2, { value: null, done: true }];
                  }
                  return [4, this.getAudioData()];
                case 1:
                  audioDataQueue = _a.sent();
                  if (this.includeSpectrogram) {
                    freqData = this.flattenQueue(audioDataQueue.freqDataQueue);
                    spectrogramTensor = this.getTensorFromAudioDataArray(freqData, [this.numFrames, this.columnTruncateLength, 1]);
                  }
                  if (this.includeWaveform) {
                    timeData = this.flattenQueue(audioDataQueue.timeDataQueue);
                    waveformTensor = this.getTensorFromAudioDataArray(timeData, [this.numFrames * this.fftSize, 1]);
                  }
                  return [2, {
                    value: { "spectrogram": spectrogramTensor, "waveform": waveformTensor },
                    done: false
                  }];
              }
            });
          });
        };
        MicrophoneIterator2.prototype.capture = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.next()];
                case 1:
                  return [2, _a.sent().value];
              }
            });
          });
        };
        MicrophoneIterator2.prototype.getAudioData = function() {
          return __awaiter(this, void 0, void 0, function() {
            var freqDataQueue, timeDataQueue, currentFrames;
            var _this = this;
            return __generator(this, function(_a) {
              freqDataQueue = [];
              timeDataQueue = [];
              currentFrames = 0;
              return [2, new Promise(function(resolve) {
                var intervalID = setInterval(function() {
                  if (_this.includeSpectrogram) {
                    _this.analyser.getFloatFrequencyData(_this.freqData);
                    if (_this.freqData[0] === -Infinity) {
                      resolve({ freqDataQueue, timeDataQueue });
                    }
                    freqDataQueue.push(_this.freqData.slice(0, _this.columnTruncateLength));
                  }
                  if (_this.includeWaveform) {
                    _this.analyser.getFloatTimeDomainData(_this.timeData);
                    timeDataQueue.push(_this.timeData.slice());
                  }
                  if (++currentFrames === _this.numFrames) {
                    clearInterval(intervalID);
                    resolve({ freqDataQueue, timeDataQueue });
                  }
                }, _this.fftSize / _this.sampleRateHz * 1e3);
              })];
            });
          });
        };
        MicrophoneIterator2.prototype.stop = function() {
          if (!this.isClosed) {
            this.isClosed = true;
            this.analyser.disconnect();
            this.audioContext.close();
            if (this.stream != null && this.stream.getTracks().length > 0) {
              this.stream.getTracks()[0].stop();
            }
          }
        };
        MicrophoneIterator2.prototype.toArray = function() {
          throw new Error("Can not convert infinite audio stream to array.");
        };
        MicrophoneIterator2.prototype.getSampleRate = function() {
          return this.sampleRateHz;
        };
        MicrophoneIterator2.prototype.flattenQueue = function(queue) {
          var frameSize = queue[0].length;
          var freqData = new Float32Array(queue.length * frameSize);
          queue.forEach(function(data, i) {
            return freqData.set(data, i * frameSize);
          });
          return freqData;
        };
        MicrophoneIterator2.prototype.getTensorFromAudioDataArray = function(freqData, shape) {
          var vals = new Float32Array(tf.util.sizeFromShape(shape));
          vals.set(freqData, vals.length - freqData.length);
          return tf.tensor(vals, shape);
        };
        return MicrophoneIterator2;
      }(LazyIterator)
    );
    var WebcamIterator = (
      /** @class */
      function(_super) {
        __extends(WebcamIterator2, _super);
        function WebcamIterator2(webcamVideoElement, webcamConfig) {
          var _this = _super.call(this) || this;
          _this.webcamVideoElement = webcamVideoElement;
          _this.webcamConfig = webcamConfig;
          _this.isClosed = true;
          _this.resize = false;
          if (_this.needToResize()) {
            _this.resize = true;
            _this.cropSize = [_this.webcamConfig.resizeHeight, _this.webcamConfig.resizeWidth];
            _this.cropBoxInd = tf.tensor1d([0], "int32");
            if (_this.webcamConfig.centerCrop) {
              var widthCroppingRatio = _this.webcamConfig.resizeWidth * 1 / _this.webcamVideoElement.width;
              var heightCroppingRatio = _this.webcamConfig.resizeHeight * 1 / _this.webcamVideoElement.height;
              var widthCropStart = (1 - widthCroppingRatio) / 2;
              var heightCropStart = (1 - heightCroppingRatio) / 2;
              var widthCropEnd = widthCropStart + widthCroppingRatio;
              var heightCropEnd = heightCroppingRatio + heightCropStart;
              _this.cropBox = tf.tensor2d([heightCropStart, widthCropStart, heightCropEnd, widthCropEnd], [1, 4]);
            } else {
              _this.cropBox = tf.tensor2d([0, 0, 1, 1], [1, 4]);
            }
          }
          return _this;
        }
        WebcamIterator2.prototype.summary = function() {
          return "webcam";
        };
        WebcamIterator2.create = function(webcamVideoElement, webcamConfig) {
          if (webcamConfig === void 0) {
            webcamConfig = {};
          }
          return __awaiter(this, void 0, void 0, function() {
            var webcamIterator;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  if (!tf.env().get("IS_BROWSER")) {
                    throw new Error("tf.data.webcam is only supported in browser environment.");
                  }
                  if (!webcamVideoElement) {
                    webcamVideoElement = document.createElement("video");
                    if (!webcamConfig.resizeWidth || !webcamConfig.resizeHeight) {
                      throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");
                    }
                    webcamVideoElement.width = webcamConfig.resizeWidth;
                    webcamVideoElement.height = webcamConfig.resizeHeight;
                  }
                  webcamIterator = new WebcamIterator2(webcamVideoElement, webcamConfig);
                  return [4, webcamIterator.start()];
                case 1:
                  _a.sent();
                  return [2, webcamIterator];
              }
            });
          });
        };
        WebcamIterator2.prototype.start = function() {
          return __awaiter(this, void 0, void 0, function() {
            var _a, e_1;
            var _this = this;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  if (this.webcamConfig.facingMode) {
                    tf.util.assert(this.webcamConfig.facingMode === "user" || this.webcamConfig.facingMode === "environment", function() {
                      return "Invalid webcam facing mode: ".concat(_this.webcamConfig.facingMode, ". ") + "Please provide 'user' or 'environment'";
                    });
                  }
                  _b.label = 1;
                case 1:
                  _b.trys.push([1, 3, , 4]);
                  _a = this;
                  return [4, navigator.mediaDevices.getUserMedia({
                    video: {
                      deviceId: this.webcamConfig.deviceId,
                      facingMode: this.webcamConfig.facingMode ? this.webcamConfig.facingMode : "user",
                      width: this.webcamVideoElement.width,
                      height: this.webcamVideoElement.height
                    }
                  })];
                case 2:
                  _a.stream = _b.sent();
                  return [3, 4];
                case 3:
                  e_1 = _b.sent();
                  e_1.message = "Error thrown while initializing video stream: ".concat(e_1.message);
                  throw e_1;
                case 4:
                  if (!this.stream) {
                    throw new Error("Could not obtain video from webcam.");
                  }
                  try {
                    this.webcamVideoElement.srcObject = this.stream;
                  } catch (error) {
                    console.log(error);
                    this.webcamVideoElement.src = window.URL.createObjectURL(this.stream);
                  }
                  this.webcamVideoElement.play();
                  this.isClosed = false;
                  return [2, new Promise(function(resolve) {
                    _this.webcamVideoElement.onloadedmetadata = function() {
                      resolve();
                    };
                  })];
              }
            });
          });
        };
        WebcamIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            var img;
            return __generator(this, function(_a) {
              if (this.isClosed) {
                return [2, { value: null, done: true }];
              }
              try {
                img = tf.browser.fromPixels(this.webcamVideoElement);
              } catch (e) {
                throw new Error("Error thrown converting video to pixels: ".concat(JSON.stringify(e)));
              }
              if (this.resize) {
                try {
                  return [2, { value: this.cropAndResizeFrame(img), done: false }];
                } catch (e) {
                  throw new Error("Error thrown cropping the video: ".concat(e.message));
                } finally {
                  img.dispose();
                }
              } else {
                return [2, { value: img, done: false }];
              }
              return [
                2
                /*return*/
              ];
            });
          });
        };
        WebcamIterator2.prototype.needToResize = function() {
          if (this.webcamConfig.resizeWidth && this.webcamConfig.resizeHeight && (this.webcamVideoElement.width !== this.webcamConfig.resizeWidth || this.webcamVideoElement.height !== this.webcamConfig.resizeHeight)) {
            return true;
          }
          return false;
        };
        WebcamIterator2.prototype.cropAndResizeFrame = function(img) {
          var _this = this;
          return tf.tidy(function() {
            var expandedImage = tf.expandDims(tf.cast(img, "float32"), 0);
            var resizedImage;
            resizedImage = tf.image.cropAndResize(expandedImage, _this.cropBox, _this.cropBoxInd, _this.cropSize, "bilinear");
            var shape = resizedImage.shape;
            return tf.reshape(resizedImage, shape.slice(1));
          });
        };
        WebcamIterator2.prototype.capture = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.next()];
                case 1:
                  return [2, _a.sent().value];
              }
            });
          });
        };
        WebcamIterator2.prototype.stop = function() {
          var tracks = this.stream.getTracks();
          tracks.forEach(function(track) {
            return track.stop();
          });
          try {
            this.webcamVideoElement.srcObject = null;
          } catch (error) {
            console.log(error);
            this.webcamVideoElement.src = null;
          }
          this.isClosed = true;
        };
        WebcamIterator2.prototype.toArray = function() {
          throw new Error("Can not convert infinite video stream to array.");
        };
        return WebcamIterator2;
      }(LazyIterator)
    );
    var DataSource = (
      /** @class */
      /* @__PURE__ */ function() {
        function DataSource2() {
        }
        return DataSource2;
      }()
    );
    var StringIterator = (
      /** @class */
      function(_super) {
        __extends(StringIterator2, _super);
        function StringIterator2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        StringIterator2.prototype.split = function(separator) {
          return new SplitIterator(this, separator);
        };
        return StringIterator2;
      }(LazyIterator)
    );
    var SplitIterator = (
      /** @class */
      function(_super) {
        __extends(SplitIterator2, _super);
        function SplitIterator2(upstream, separator) {
          var _this = _super.call(this) || this;
          _this.upstream = upstream;
          _this.impl = new SplitIteratorImpl(upstream, separator);
          return _this;
        }
        SplitIterator2.prototype.summary = function() {
          return this.impl.summary();
        };
        SplitIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              return [2, this.impl.next()];
            });
          });
        };
        return SplitIterator2;
      }(StringIterator)
    );
    var SplitIteratorImpl = (
      /** @class */
      function(_super) {
        __extends(SplitIteratorImpl2, _super);
        function SplitIteratorImpl2(upstream, separator) {
          var _this = _super.call(this) || this;
          _this.upstream = upstream;
          _this.separator = separator;
          _this.carryover = "";
          return _this;
        }
        SplitIteratorImpl2.prototype.summary = function() {
          return "".concat(this.upstream.summary(), " -> Split('").concat(this.separator, "')");
        };
        SplitIteratorImpl2.prototype.pump = function() {
          return __awaiter(this, void 0, void 0, function() {
            var chunkResult, lines, _a, _b, line;
            var e_1, _c;
            return __generator(this, function(_d) {
              switch (_d.label) {
                case 0:
                  return [4, this.upstream.next()];
                case 1:
                  chunkResult = _d.sent();
                  if (chunkResult.done) {
                    if (this.carryover === "") {
                      return [2, false];
                    }
                    this.outputQueue.push(this.carryover);
                    this.carryover = "";
                    return [2, true];
                  }
                  lines = chunkResult.value.split(this.separator);
                  lines[0] = this.carryover + lines[0];
                  try {
                    for (_a = __values(lines.slice(0, -1)), _b = _a.next(); !_b.done; _b = _a.next()) {
                      line = _b.value;
                      this.outputQueue.push(line);
                    }
                  } catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                  } finally {
                    try {
                      if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
                    } finally {
                      if (e_1) throw e_1.error;
                    }
                  }
                  this.carryover = lines[lines.length - 1];
                  return [2, true];
              }
            });
          });
        };
        return SplitIteratorImpl2;
      }(OneToManyIterator)
    );
    var ByteChunkIterator = (
      /** @class */
      function(_super) {
        __extends(ByteChunkIterator2, _super);
        function ByteChunkIterator2() {
          return _super !== null && _super.apply(this, arguments) || this;
        }
        ByteChunkIterator2.prototype.decodeUTF8 = function() {
          return new Utf8Iterator(this);
        };
        return ByteChunkIterator2;
      }(LazyIterator)
    );
    var Utf8Iterator = (
      /** @class */
      function(_super) {
        __extends(Utf8Iterator2, _super);
        function Utf8Iterator2(upstream) {
          var _this = _super.call(this) || this;
          _this.upstream = upstream;
          _this.impl = new Utf8IteratorImpl(upstream);
          return _this;
        }
        Utf8Iterator2.prototype.summary = function() {
          return this.impl.summary();
        };
        Utf8Iterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              return [2, this.impl.next()];
            });
          });
        };
        return Utf8Iterator2;
      }(StringIterator)
    );
    var Utf8IteratorImpl = (
      /** @class */
      function(_super) {
        __extends(Utf8IteratorImpl2, _super);
        function Utf8IteratorImpl2(upstream) {
          var _this = _super.call(this) || this;
          _this.upstream = upstream;
          if (tf.env().get("IS_BROWSER")) {
            _this.decoder = new TextDecoder("utf-8");
          } else {
            var StringDecoder = require("string_decoder").StringDecoder;
            _this.decoder = new StringDecoder("utf8");
          }
          return _this;
        }
        Utf8IteratorImpl2.prototype.summary = function() {
          return "".concat(this.upstream.summary(), " -> Utf8");
        };
        Utf8IteratorImpl2.prototype.pump = function() {
          return __awaiter(this, void 0, void 0, function() {
            var chunkResult, chunk, text;
            return __generator(this, function(_a) {
              switch (_a.label) {
                case 0:
                  return [4, this.upstream.next()];
                case 1:
                  chunkResult = _a.sent();
                  if (chunkResult.done) {
                    return [2, false];
                  } else {
                    chunk = chunkResult.value;
                  }
                  if (tf.env().get("IS_BROWSER")) {
                    text = this.decoder.decode(chunk, { stream: true });
                  } else {
                    text = this.decoder.write(Buffer.from(chunk.buffer));
                  }
                  this.outputQueue.push(text);
                  return [2, true];
              }
            });
          });
        };
        return Utf8IteratorImpl2;
      }(OneToManyIterator)
    );
    var FileChunkIterator = (
      /** @class */
      function(_super) {
        __extends(FileChunkIterator2, _super);
        function FileChunkIterator2(file, options) {
          if (options === void 0) {
            options = {};
          }
          var _this = _super.call(this) || this;
          _this.file = file;
          _this.options = options;
          tf.util.assert(file instanceof Uint8Array || (tf.env().get("IS_BROWSER") ? file instanceof File || file instanceof Blob : false), function() {
            return "FileChunkIterator only supports File, Blob and Uint8Array right now.";
          });
          _this.offset = options.offset || 0;
          _this.chunkSize = options.chunkSize || 1024 * 1024;
          return _this;
        }
        FileChunkIterator2.prototype.summary = function() {
          return "FileChunks ".concat(this.file);
        };
        FileChunkIterator2.prototype.next = function() {
          return __awaiter(this, void 0, void 0, function() {
            var chunk;
            var _a;
            var _this = this;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  if (this.offset >= (this.file instanceof Uint8Array ? this.file.byteLength : this.file.size)) {
                    return [2, { value: null, done: true }];
                  }
                  chunk = new Promise(function(resolve, reject) {
                    var end = _this.offset + _this.chunkSize;
                    if (_this.file instanceof Uint8Array) {
                      resolve(new Uint8Array(_this.file.slice(_this.offset, end)));
                    } else {
                      var fileReader_1 = new FileReader();
                      fileReader_1.onload = function(event) {
                        var data = fileReader_1.result;
                        if (data instanceof ArrayBuffer) {
                          data = new Uint8Array(data);
                        }
                        if (!(data instanceof Uint8Array)) {
                          return reject(new TypeError("FileReader returned unknown type."));
                        }
                        resolve(data);
                      };
                      fileReader_1.onabort = function(event) {
                        return reject(new Error("Aborted"));
                      };
                      fileReader_1.onerror = function(event) {
                        return reject(new Error(event.type));
                      };
                      var slice = _this.file.slice(_this.offset, end);
                      fileReader_1.readAsArrayBuffer(slice);
                    }
                    _this.offset = end;
                  });
                  _a = {};
                  return [4, chunk];
                case 1:
                  return [2, (_a.value = _b.sent(), _a.done = false, _a)];
              }
            });
          });
        };
        return FileChunkIterator2;
      }(ByteChunkIterator)
    );
    function urlChunkIterator(url, options, fetchFunc) {
      if (options === void 0) {
        options = {};
      }
      return __awaiter(this, void 0, void 0, function() {
        var urlString, requestInit, response, uint8Array, _a;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              if (typeof url === "string") {
                urlString = url;
              } else {
                urlString = url.url;
                requestInit = getRequestInitFromRequest(url);
              }
              return [4, (fetchFunc || tf.util.fetch)(urlString, requestInit)];
            case 1:
              response = _b.sent();
              if (!response.ok) return [3, 3];
              _a = Uint8Array.bind;
              return [4, response.arrayBuffer()];
            case 2:
              uint8Array = new (_a.apply(Uint8Array, [void 0, _b.sent()]))();
              return [2, new FileChunkIterator(uint8Array, options)];
            case 3:
              throw new Error(response.statusText);
          }
        });
      });
    }
    var getRequestInitFromRequest = function(request) {
      var init = {
        method: request.method,
        headers: request.headers,
        body: request.body,
        mode: request.mode,
        credentials: request.credentials,
        cache: request.cache,
        redirect: request.redirect,
        referrer: request.referrer,
        integrity: request.integrity
      };
      return init;
    };
    function isLocalPath(source) {
      return typeof source === "string" && source.slice(0, 7) === "file://";
    }
    var FileDataSource = (
      /** @class */
      function(_super) {
        __extends(FileDataSource2, _super);
        function FileDataSource2(input, options) {
          if (options === void 0) {
            options = {};
          }
          var _this = _super.call(this) || this;
          _this.input = input;
          _this.options = options;
          return _this;
        }
        FileDataSource2.prototype.iterator = function() {
          return __awaiter(this, void 0, void 0, function() {
            var fs;
            return __generator(this, function(_a) {
              if (isLocalPath(this.input) && tf.env().get("IS_NODE")) {
                fs = require("fs");
                this.input = fs.readFileSync(this.input.slice(7));
              }
              return [2, new FileChunkIterator(this.input, this.options)];
            });
          });
        };
        return FileDataSource2;
      }(DataSource)
    );
    var URLDataSource = (
      /** @class */
      function(_super) {
        __extends(URLDataSource2, _super);
        function URLDataSource2(url, fileOptions) {
          if (fileOptions === void 0) {
            fileOptions = {};
          }
          var _this = _super.call(this) || this;
          _this.url = url;
          _this.fileOptions = fileOptions;
          return _this;
        }
        URLDataSource2.prototype.iterator = function() {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
              if (isLocalPath(this.url)) {
                return [2, new FileDataSource(this.url, this.fileOptions).iterator()];
              } else {
                return [2, urlChunkIterator(this.url, this.fileOptions)];
              }
            });
          });
        };
        return URLDataSource2;
      }(DataSource)
    );
    function csv(source, csvConfig) {
      if (csvConfig === void 0) {
        csvConfig = {};
      }
      return new CSVDataset(new URLDataSource(source), csvConfig);
    }
    function func(f) {
      var _this = this;
      var iter = iteratorFromFunction(f);
      return datasetFromIteratorFn(function() {
        return __awaiter(_this, void 0, void 0, function() {
          return __generator(this, function(_a) {
            return [2, iter];
          });
        });
      });
    }
    function generator(generator2) {
      var _this = this;
      return datasetFromIteratorFn(function() {
        return __awaiter(_this, void 0, void 0, function() {
          var gen;
          return __generator(this, function(_a) {
            switch (_a.label) {
              case 0:
                return [4, generator2()];
              case 1:
                gen = _a.sent();
                return [2, iteratorFromFunction(function() {
                  return gen.next();
                })];
            }
          });
        });
      });
    }
    function webcam(webcamVideoElement, webcamConfig) {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a) {
          return [2, WebcamIterator.create(webcamVideoElement, webcamConfig)];
        });
      });
    }
    function microphone(microphoneConfig) {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a) {
          return [2, MicrophoneIterator.create(microphoneConfig)];
        });
      });
    }
    var version = "4.22.0";
    exports2.CSVDataset = CSVDataset;
    exports2.Dataset = Dataset;
    exports2.FileDataSource = FileDataSource;
    exports2.TextLineDataset = TextLineDataset;
    exports2.URLDataSource = URLDataSource;
    exports2.array = array;
    exports2.csv = csv;
    exports2.func = func;
    exports2.generator = generator;
    exports2.microphone = microphone;
    exports2.version_data = version;
    exports2.webcam = webcam;
    exports2.zip = zip;
  }
});

// node_modules/seedrandom/lib/alea.js
var require_alea = __commonJS({
  "node_modules/seedrandom/lib/alea.js"(exports2, module2) {
    (function(global2, module3, define2) {
      function Alea(seed) {
        var me = this, mash = Mash();
        me.next = function() {
          var t = 2091639 * me.s0 + me.c * 23283064365386963e-26;
          me.s0 = me.s1;
          me.s1 = me.s2;
          return me.s2 = t - (me.c = t | 0);
        };
        me.c = 1;
        me.s0 = mash(" ");
        me.s1 = mash(" ");
        me.s2 = mash(" ");
        me.s0 -= mash(seed);
        if (me.s0 < 0) {
          me.s0 += 1;
        }
        me.s1 -= mash(seed);
        if (me.s1 < 0) {
          me.s1 += 1;
        }
        me.s2 -= mash(seed);
        if (me.s2 < 0) {
          me.s2 += 1;
        }
        mash = null;
      }
      function copy(f, t) {
        t.c = f.c;
        t.s0 = f.s0;
        t.s1 = f.s1;
        t.s2 = f.s2;
        return t;
      }
      function impl(seed, opts) {
        var xg = new Alea(seed), state = opts && opts.state, prng = xg.next;
        prng.int32 = function() {
          return xg.next() * 4294967296 | 0;
        };
        prng.double = function() {
          return prng() + (prng() * 2097152 | 0) * 11102230246251565e-32;
        };
        prng.quick = prng;
        if (state) {
          if (typeof state == "object") copy(state, xg);
          prng.state = function() {
            return copy(xg, {});
          };
        }
        return prng;
      }
      function Mash() {
        var n = 4022871197;
        var mash = function(data) {
          data = String(data);
          for (var i = 0; i < data.length; i++) {
            n += data.charCodeAt(i);
            var h = 0.02519603282416938 * n;
            n = h >>> 0;
            h -= n;
            h *= n;
            n = h >>> 0;
            h -= n;
            n += h * 4294967296;
          }
          return (n >>> 0) * 23283064365386963e-26;
        };
        return mash;
      }
      if (module3 && module3.exports) {
        module3.exports = impl;
      } else if (define2 && define2.amd) {
        define2(function() {
          return impl;
        });
      } else {
        this.alea = impl;
      }
    })(
      exports2,
      typeof module2 == "object" && module2,
      // present in node.js
      typeof define == "function" && define
      // present with an AMD loader
    );
  }
});

// node_modules/seedrandom/lib/xor128.js
var require_xor128 = __commonJS({
  "node_modules/seedrandom/lib/xor128.js"(exports2, module2) {
    (function(global2, module3, define2) {
      function XorGen(seed) {
        var me = this, strseed = "";
        me.x = 0;
        me.y = 0;
        me.z = 0;
        me.w = 0;
        me.next = function() {
          var t = me.x ^ me.x << 11;
          me.x = me.y;
          me.y = me.z;
          me.z = me.w;
          return me.w ^= me.w >>> 19 ^ t ^ t >>> 8;
        };
        if (seed === (seed | 0)) {
          me.x = seed;
        } else {
          strseed += seed;
        }
        for (var k = 0; k < strseed.length + 64; k++) {
          me.x ^= strseed.charCodeAt(k) | 0;
          me.next();
        }
      }
      function copy(f, t) {
        t.x = f.x;
        t.y = f.y;
        t.z = f.z;
        t.w = f.w;
        return t;
      }
      function impl(seed, opts) {
        var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
          return (xg.next() >>> 0) / 4294967296;
        };
        prng.double = function() {
          do {
            var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
          } while (result === 0);
          return result;
        };
        prng.int32 = xg.next;
        prng.quick = prng;
        if (state) {
          if (typeof state == "object") copy(state, xg);
          prng.state = function() {
            return copy(xg, {});
          };
        }
        return prng;
      }
      if (module3 && module3.exports) {
        module3.exports = impl;
      } else if (define2 && define2.amd) {
        define2(function() {
          return impl;
        });
      } else {
        this.xor128 = impl;
      }
    })(
      exports2,
      typeof module2 == "object" && module2,
      // present in node.js
      typeof define == "function" && define
      // present with an AMD loader
    );
  }
});

// node_modules/seedrandom/lib/xorwow.js
var require_xorwow = __commonJS({
  "node_modules/seedrandom/lib/xorwow.js"(exports2, module2) {
    (function(global2, module3, define2) {
      function XorGen(seed) {
        var me = this, strseed = "";
        me.next = function() {
          var t = me.x ^ me.x >>> 2;
          me.x = me.y;
          me.y = me.z;
          me.z = me.w;
          me.w = me.v;
          return (me.d = me.d + 362437 | 0) + (me.v = me.v ^ me.v << 4 ^ (t ^ t << 1)) | 0;
        };
        me.x = 0;
        me.y = 0;
        me.z = 0;
        me.w = 0;
        me.v = 0;
        if (seed === (seed | 0)) {
          me.x = seed;
        } else {
          strseed += seed;
        }
        for (var k = 0; k < strseed.length + 64; k++) {
          me.x ^= strseed.charCodeAt(k) | 0;
          if (k == strseed.length) {
            me.d = me.x << 10 ^ me.x >>> 4;
          }
          me.next();
        }
      }
      function copy(f, t) {
        t.x = f.x;
        t.y = f.y;
        t.z = f.z;
        t.w = f.w;
        t.v = f.v;
        t.d = f.d;
        return t;
      }
      function impl(seed, opts) {
        var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
          return (xg.next() >>> 0) / 4294967296;
        };
        prng.double = function() {
          do {
            var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
          } while (result === 0);
          return result;
        };
        prng.int32 = xg.next;
        prng.quick = prng;
        if (state) {
          if (typeof state == "object") copy(state, xg);
          prng.state = function() {
            return copy(xg, {});
          };
        }
        return prng;
      }
      if (module3 && module3.exports) {
        module3.exports = impl;
      } else if (define2 && define2.amd) {
        define2(function() {
          return impl;
        });
      } else {
        this.xorwow = impl;
      }
    })(
      exports2,
      typeof module2 == "object" && module2,
      // present in node.js
      typeof define == "function" && define
      // present with an AMD loader
    );
  }
});

// node_modules/seedrandom/lib/xorshift7.js
var require_xorshift7 = __commonJS({
  "node_modules/seedrandom/lib/xorshift7.js"(exports2, module2) {
    (function(global2, module3, define2) {
      function XorGen(seed) {
        var me = this;
        me.next = function() {
          var X = me.x, i = me.i, t, v, w;
          t = X[i];
          t ^= t >>> 7;
          v = t ^ t << 24;
          t = X[i + 1 & 7];
          v ^= t ^ t >>> 10;
          t = X[i + 3 & 7];
          v ^= t ^ t >>> 3;
          t = X[i + 4 & 7];
          v ^= t ^ t << 7;
          t = X[i + 7 & 7];
          t = t ^ t << 13;
          v ^= t ^ t << 9;
          X[i] = v;
          me.i = i + 1 & 7;
          return v;
        };
        function init(me2, seed2) {
          var j, w, X = [];
          if (seed2 === (seed2 | 0)) {
            w = X[0] = seed2;
          } else {
            seed2 = "" + seed2;
            for (j = 0; j < seed2.length; ++j) {
              X[j & 7] = X[j & 7] << 15 ^ seed2.charCodeAt(j) + X[j + 1 & 7] << 13;
            }
          }
          while (X.length < 8) X.push(0);
          for (j = 0; j < 8 && X[j] === 0; ++j) ;
          if (j == 8) w = X[7] = -1;
          else w = X[j];
          me2.x = X;
          me2.i = 0;
          for (j = 256; j > 0; --j) {
            me2.next();
          }
        }
        init(me, seed);
      }
      function copy(f, t) {
        t.x = f.x.slice();
        t.i = f.i;
        return t;
      }
      function impl(seed, opts) {
        if (seed == null) seed = +/* @__PURE__ */ new Date();
        var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
          return (xg.next() >>> 0) / 4294967296;
        };
        prng.double = function() {
          do {
            var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
          } while (result === 0);
          return result;
        };
        prng.int32 = xg.next;
        prng.quick = prng;
        if (state) {
          if (state.x) copy(state, xg);
          prng.state = function() {
            return copy(xg, {});
          };
        }
        return prng;
      }
      if (module3 && module3.exports) {
        module3.exports = impl;
      } else if (define2 && define2.amd) {
        define2(function() {
          return impl;
        });
      } else {
        this.xorshift7 = impl;
      }
    })(
      exports2,
      typeof module2 == "object" && module2,
      // present in node.js
      typeof define == "function" && define
      // present with an AMD loader
    );
  }
});

// node_modules/seedrandom/lib/xor4096.js
var require_xor4096 = __commonJS({
  "node_modules/seedrandom/lib/xor4096.js"(exports2, module2) {
    (function(global2, module3, define2) {
      function XorGen(seed) {
        var me = this;
        me.next = function() {
          var w = me.w, X = me.X, i = me.i, t, v;
          me.w = w = w + 1640531527 | 0;
          v = X[i + 34 & 127];
          t = X[i = i + 1 & 127];
          v ^= v << 13;
          t ^= t << 17;
          v ^= v >>> 15;
          t ^= t >>> 12;
          v = X[i] = v ^ t;
          me.i = i;
          return v + (w ^ w >>> 16) | 0;
        };
        function init(me2, seed2) {
          var t, v, i, j, w, X = [], limit = 128;
          if (seed2 === (seed2 | 0)) {
            v = seed2;
            seed2 = null;
          } else {
            seed2 = seed2 + "\0";
            v = 0;
            limit = Math.max(limit, seed2.length);
          }
          for (i = 0, j = -32; j < limit; ++j) {
            if (seed2) v ^= seed2.charCodeAt((j + 32) % seed2.length);
            if (j === 0) w = v;
            v ^= v << 10;
            v ^= v >>> 15;
            v ^= v << 4;
            v ^= v >>> 13;
            if (j >= 0) {
              w = w + 1640531527 | 0;
              t = X[j & 127] ^= v + w;
              i = 0 == t ? i + 1 : 0;
            }
          }
          if (i >= 128) {
            X[(seed2 && seed2.length || 0) & 127] = -1;
          }
          i = 127;
          for (j = 4 * 128; j > 0; --j) {
            v = X[i + 34 & 127];
            t = X[i = i + 1 & 127];
            v ^= v << 13;
            t ^= t << 17;
            v ^= v >>> 15;
            t ^= t >>> 12;
            X[i] = v ^ t;
          }
          me2.w = w;
          me2.X = X;
          me2.i = i;
        }
        init(me, seed);
      }
      function copy(f, t) {
        t.i = f.i;
        t.w = f.w;
        t.X = f.X.slice();
        return t;
      }
      ;
      function impl(seed, opts) {
        if (seed == null) seed = +/* @__PURE__ */ new Date();
        var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
          return (xg.next() >>> 0) / 4294967296;
        };
        prng.double = function() {
          do {
            var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
          } while (result === 0);
          return result;
        };
        prng.int32 = xg.next;
        prng.quick = prng;
        if (state) {
          if (state.X) copy(state, xg);
          prng.state = function() {
            return copy(xg, {});
          };
        }
        return prng;
      }
      if (module3 && module3.exports) {
        module3.exports = impl;
      } else if (define2 && define2.amd) {
        define2(function() {
          return impl;
        });
      } else {
        this.xor4096 = impl;
      }
    })(
      exports2,
      // window object or global
      typeof module2 == "object" && module2,
      // present in node.js
      typeof define == "function" && define
      // present with an AMD loader
    );
  }
});

// node_modules/seedrandom/lib/tychei.js
var require_tychei = __commonJS({
  "node_modules/seedrandom/lib/tychei.js"(exports2, module2) {
    (function(global2, module3, define2) {
      function XorGen(seed) {
        var me = this, strseed = "";
        me.next = function() {
          var b = me.b, c = me.c, d = me.d, a = me.a;
          b = b << 25 ^ b >>> 7 ^ c;
          c = c - d | 0;
          d = d << 24 ^ d >>> 8 ^ a;
          a = a - b | 0;
          me.b = b = b << 20 ^ b >>> 12 ^ c;
          me.c = c = c - d | 0;
          me.d = d << 16 ^ c >>> 16 ^ a;
          return me.a = a - b | 0;
        };
        me.a = 0;
        me.b = 0;
        me.c = 2654435769 | 0;
        me.d = 1367130551;
        if (seed === Math.floor(seed)) {
          me.a = seed / 4294967296 | 0;
          me.b = seed | 0;
        } else {
          strseed += seed;
        }
        for (var k = 0; k < strseed.length + 20; k++) {
          me.b ^= strseed.charCodeAt(k) | 0;
          me.next();
        }
      }
      function copy(f, t) {
        t.a = f.a;
        t.b = f.b;
        t.c = f.c;
        t.d = f.d;
        return t;
      }
      ;
      function impl(seed, opts) {
        var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
          return (xg.next() >>> 0) / 4294967296;
        };
        prng.double = function() {
          do {
            var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
          } while (result === 0);
          return result;
        };
        prng.int32 = xg.next;
        prng.quick = prng;
        if (state) {
          if (typeof state == "object") copy(state, xg);
          prng.state = function() {
            return copy(xg, {});
          };
        }
        return prng;
      }
      if (module3 && module3.exports) {
        module3.exports = impl;
      } else if (define2 && define2.amd) {
        define2(function() {
          return impl;
        });
      } else {
        this.tychei = impl;
      }
    })(
      exports2,
      typeof module2 == "object" && module2,
      // present in node.js
      typeof define == "function" && define
      // present with an AMD loader
    );
  }
});

// node_modules/seedrandom/seedrandom.js
var require_seedrandom = __commonJS({
  "node_modules/seedrandom/seedrandom.js"(exports2, module2) {
    (function(global2, pool, math) {
      var width = 256, chunks = 6, digits = 52, rngname = "random", startdenom = math.pow(width, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask = width - 1, nodecrypto;
      function seedrandom(seed, options, callback) {
        var key = [];
        options = options == true ? { entropy: true } : options || {};
        var shortseed = mixkey(flatten(
          options.entropy ? [seed, tostring(pool)] : seed == null ? autoseed() : seed,
          3
        ), key);
        var arc4 = new ARC4(key);
        var prng = function() {
          var n = arc4.g(chunks), d = startdenom, x = 0;
          while (n < significance) {
            n = (n + x) * width;
            d *= width;
            x = arc4.g(1);
          }
          while (n >= overflow) {
            n /= 2;
            d /= 2;
            x >>>= 1;
          }
          return (n + x) / d;
        };
        prng.int32 = function() {
          return arc4.g(4) | 0;
        };
        prng.quick = function() {
          return arc4.g(4) / 4294967296;
        };
        prng.double = prng;
        mixkey(tostring(arc4.S), pool);
        return (options.pass || callback || function(prng2, seed2, is_math_call, state) {
          if (state) {
            if (state.S) {
              copy(state, arc4);
            }
            prng2.state = function() {
              return copy(arc4, {});
            };
          }
          if (is_math_call) {
            math[rngname] = prng2;
            return seed2;
          } else return prng2;
        })(
          prng,
          shortseed,
          "global" in options ? options.global : this == math,
          options.state
        );
      }
      function ARC4(key) {
        var t, keylen = key.length, me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
        if (!keylen) {
          key = [keylen++];
        }
        while (i < width) {
          s[i] = i++;
        }
        for (i = 0; i < width; i++) {
          s[i] = s[j = mask & j + key[i % keylen] + (t = s[i])];
          s[j] = t;
        }
        (me.g = function(count) {
          var t2, r = 0, i2 = me.i, j2 = me.j, s2 = me.S;
          while (count--) {
            t2 = s2[i2 = mask & i2 + 1];
            r = r * width + s2[mask & (s2[i2] = s2[j2 = mask & j2 + t2]) + (s2[j2] = t2)];
          }
          me.i = i2;
          me.j = j2;
          return r;
        })(width);
      }
      function copy(f, t) {
        t.i = f.i;
        t.j = f.j;
        t.S = f.S.slice();
        return t;
      }
      ;
      function flatten(obj, depth) {
        var result = [], typ = typeof obj, prop;
        if (depth && typ == "object") {
          for (prop in obj) {
            try {
              result.push(flatten(obj[prop], depth - 1));
            } catch (e) {
            }
          }
        }
        return result.length ? result : typ == "string" ? obj : obj + "\0";
      }
      function mixkey(seed, key) {
        var stringseed = seed + "", smear, j = 0;
        while (j < stringseed.length) {
          key[mask & j] = mask & (smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++);
        }
        return tostring(key);
      }
      function autoseed() {
        try {
          var out;
          if (nodecrypto && (out = nodecrypto.randomBytes)) {
            out = out(width);
          } else {
            out = new Uint8Array(width);
            (global2.crypto || global2.msCrypto).getRandomValues(out);
          }
          return tostring(out);
        } catch (e) {
          var browser = global2.navigator, plugins = browser && browser.plugins;
          return [+/* @__PURE__ */ new Date(), global2, plugins, global2.screen, tostring(pool)];
        }
      }
      function tostring(a) {
        return String.fromCharCode.apply(0, a);
      }
      mixkey(math.random(), pool);
      if (typeof module2 == "object" && module2.exports) {
        module2.exports = seedrandom;
        try {
          nodecrypto = require("crypto");
        } catch (ex) {
        }
      } else if (typeof define == "function" && define.amd) {
        define(function() {
          return seedrandom;
        });
      } else {
        math["seed" + rngname] = seedrandom;
      }
    })(
      // global: `self` in browsers (including strict mode and web workers),
      // otherwise `this` in Node and other environments
      typeof self !== "undefined" ? self : exports2,
      [],
      // pool: entropy pool starts empty
      Math
      // math: package containing random, pow, and seedrandom
    );
  }
});

// node_modules/seedrandom/index.js
var require_seedrandom2 = __commonJS({
  "node_modules/seedrandom/index.js"(exports2, module2) {
    var alea = require_alea();
    var xor128 = require_xor128();
    var xorwow = require_xorwow();
    var xorshift7 = require_xorshift7();
    var xor4096 = require_xor4096();
    var tychei = require_tychei();
    var sr = require_seedrandom();
    sr.alea = alea;
    sr.xor128 = xor128;
    sr.xorwow = xorwow;
    sr.xorshift7 = xorshift7;
    sr.xor4096 = xor4096;
    sr.tychei = tychei;
    module2.exports = sr;
  }
});

// node_modules/@tensorflow/tfjs-backend-cpu/dist/tf-backend-cpu.node.js
var require_tf_backend_cpu_node = __commonJS({
  "node_modules/@tensorflow/tfjs-backend-cpu/dist/tf-backend-cpu.node.js"(exports2) {
    "use strict";
    var tfjsCore = require_tf_core_node();
    var seedrandom = require_seedrandom2();
    function _interopNamespaceDefault(e) {
      var n = /* @__PURE__ */ Object.create(null);
      if (e) {
        Object.keys(e).forEach(function(k) {
          if (k !== "default") {
            var d = Object.getOwnPropertyDescriptor(e, k);
            Object.defineProperty(n, k, d.get ? d : {
              enumerable: true,
              get: function() {
                return e[k];
              }
            });
          }
        });
      }
      n.default = e;
      return n;
    }
    var seedrandom__namespace = /* @__PURE__ */ _interopNamespaceDefault(seedrandom);
    var extendStatics = function(d, b) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
        d2.__proto__ = b2;
      } || function(d2, b2) {
        for (var p2 in b2)
          if (Object.prototype.hasOwnProperty.call(b2, p2))
            d2[p2] = b2[p2];
      };
      return extendStatics(d, b);
    };
    function __extends(d, b) {
      if (typeof b !== "function" && b !== null)
        throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
      extendStatics(d, b);
      function __() {
        this.constructor = d;
      }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }
    function __awaiter(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step2(generator.next(value));
          } catch (e) {
            reject(e);
          }
        }
        function rejected(value) {
          try {
            step2(generator["throw"](value));
          } catch (e) {
            reject(e);
          }
        }
        function step2(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step2((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    }
    function __generator(thisArg, body) {
      var _ = { label: 0, sent: function() {
        if (t[0] & 1)
          throw t[1];
        return t[1];
      }, trys: [], ops: [] }, f, y, t, g;
      return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
        return this;
      }), g;
      function verb(n) {
        return function(v) {
          return step2([n, v]);
        };
      }
      function step2(op) {
        if (f)
          throw new TypeError("Generator is already executing.");
        while (_)
          try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
              return t;
            if (y = 0, t)
              op = [op[0] & 2, t.value];
            switch (op[0]) {
              case 0:
              case 1:
                t = op;
                break;
              case 4:
                _.label++;
                return { value: op[1], done: false };
              case 5:
                _.label++;
                y = op[1];
                op = [0];
                continue;
              case 7:
                op = _.ops.pop();
                _.trys.pop();
                continue;
              default:
                if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                  _ = 0;
                  continue;
                }
                if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                  _.label = op[1];
                  break;
                }
                if (op[0] === 6 && _.label < t[1]) {
                  _.label = t[1];
                  t = op;
                  break;
                }
                if (t && _.label < t[2]) {
                  _.label = t[2];
                  _.ops.push(op);
                  break;
                }
                if (t[2])
                  _.ops.pop();
                _.trys.pop();
                continue;
            }
            op = body.call(thisArg, _);
          } catch (e) {
            op = [6, e];
            y = 0;
          } finally {
            f = t = 0;
          }
        if (op[0] & 5)
          throw op[1];
        return { value: op[0] ? op[1] : void 0, done: true };
      }
    }
    function __values(o) {
      var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
      if (m)
        return m.call(o);
      if (o && typeof o.length === "number")
        return {
          next: function() {
            if (o && i >= o.length)
              o = void 0;
            return { value: o && o[i++], done: !o };
          }
        };
      throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    }
    function __read(o, n) {
      var m = typeof Symbol === "function" && o[Symbol.iterator];
      if (!m)
        return o;
      var i = m.call(o), r, ar = [], e;
      try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
          ar.push(r.value);
      } catch (error) {
        e = { error };
      } finally {
        try {
          if (r && !r.done && (m = i["return"]))
            m.call(i);
        } finally {
          if (e)
            throw e.error;
        }
      }
      return ar;
    }
    function __spreadArray(to, from, pack2) {
      if (pack2 || arguments.length === 2)
        for (var i = 0, l = from.length, ar; i < l; i++) {
          if (ar || !(i in from)) {
            if (!ar)
              ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
          }
        }
      return to.concat(ar || Array.prototype.slice.call(from));
    }
    function assertNotComplex(tensor, opName) {
      if (!Array.isArray(tensor)) {
        tensor = [tensor];
      }
      tensor.forEach(function(t) {
        if (t != null) {
          tfjsCore.util.assert(t.dtype !== "complex64", function() {
            return "".concat(opName, " does not support complex64 tensors in the CPU backend.");
          });
        }
      });
    }
    var whereImpl = tfjsCore.kernel_impls.whereImpl;
    var MathBackendCPU = (
      /** @class */
      function(_super) {
        __extends(MathBackendCPU2, _super);
        function MathBackendCPU2() {
          var _this = _super.call(this) || this;
          _this.blockSize = 48;
          _this.firstUse = true;
          _this.data = new tfjsCore.DataStorage(_this, tfjsCore.engine());
          return _this;
        }
        MathBackendCPU2.prototype.nextDataId = function() {
          return MathBackendCPU2.nextDataId++;
        };
        MathBackendCPU2.prototype.write = function(values, shape, dtype) {
          if (this.firstUse) {
            this.firstUse = false;
            if (tfjsCore.env().get("IS_NODE")) {
              tfjsCore.backend_util.warn("\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============================");
            }
          }
          var dataId = { id: this.nextDataId() };
          this.data.set(dataId, { values, dtype, refCount: 1 });
          return dataId;
        };
        MathBackendCPU2.prototype.makeTensorInfo = function(shape, dtype, values) {
          var outId;
          if (dtype === "string" && values != null && values.length > 0 && tfjsCore.util.isString(values[0])) {
            var encodedValues = values.map(function(d) {
              return tfjsCore.util.encodeString(d);
            });
            outId = this.write(encodedValues, shape, dtype);
          } else {
            outId = this.write(values, shape, dtype);
          }
          return { dataId: outId, shape, dtype };
        };
        MathBackendCPU2.prototype.refCount = function(dataId) {
          if (this.data.has(dataId)) {
            var tensorData = this.data.get(dataId);
            return tensorData.refCount;
          }
          return 0;
        };
        MathBackendCPU2.prototype.incRef = function(dataId) {
          var tensorData = this.data.get(dataId);
          tensorData.refCount++;
        };
        MathBackendCPU2.prototype.decRef = function(dataId) {
          if (this.data.has(dataId)) {
            var tensorData = this.data.get(dataId);
            tensorData.refCount--;
          }
        };
        MathBackendCPU2.prototype.move = function(dataId, values, shape, dtype, refCount) {
          this.data.set(dataId, { values, dtype, refCount });
        };
        MathBackendCPU2.prototype.numDataIds = function() {
          return this.data.numDataIds();
        };
        MathBackendCPU2.prototype.read = function(dataId) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_b) {
              return [2, this.readSync(dataId)];
            });
          });
        };
        MathBackendCPU2.prototype.readSync = function(dataId) {
          var _b = this.data.get(dataId), dtype = _b.dtype, complexTensorInfos = _b.complexTensorInfos;
          if (dtype === "complex64") {
            var realValues = this.readSync(complexTensorInfos.real.dataId);
            var imagValues = this.readSync(complexTensorInfos.imag.dataId);
            return tfjsCore.backend_util.mergeRealAndImagArrays(realValues, imagValues);
          }
          return tfjsCore.util.convertBackendValuesAndArrayBuffer(this.data.get(dataId).values, dtype);
        };
        MathBackendCPU2.prototype.bufferSync = function(t) {
          var data = this.readSync(t.dataId);
          if (t.dtype === "string") {
            try {
              var strings = data.map(function(d) {
                return tfjsCore.util.decodeString(d);
              });
              return tfjsCore.buffer(t.shape, t.dtype, strings);
            } catch (_a2) {
              throw new Error("Failed to decode encoded string bytes into utf-8");
            }
          }
          return tfjsCore.buffer(t.shape, t.dtype, data);
        };
        MathBackendCPU2.prototype.makeOutput = function(values, shape, dtype) {
          return tfjsCore.engine().makeTensorFromTensorInfo(this.makeTensorInfo(shape, dtype, values), this);
        };
        MathBackendCPU2.prototype.disposeData = function(dataId, force) {
          if (force === void 0) {
            force = false;
          }
          if (this.data.has(dataId)) {
            this.data.get(dataId).refCount--;
            if (!force && this.data.get(dataId).refCount > 0) {
              return false;
            }
            var complexTensorInfos = this.data.get(dataId).complexTensorInfos;
            if (complexTensorInfos != null) {
              this.disposeData(complexTensorInfos.real.dataId, true);
              this.disposeData(complexTensorInfos.imag.dataId, true);
            }
            this.data.delete(dataId);
          }
          return true;
        };
        MathBackendCPU2.prototype.disposeIntermediateTensorInfo = function(tensorInfo) {
          this.disposeData(tensorInfo.dataId);
        };
        MathBackendCPU2.prototype.time = function(f) {
          return __awaiter(this, void 0, void 0, function() {
            var start, kernelMs;
            return __generator(this, function(_b) {
              start = tfjsCore.util.now();
              f();
              kernelMs = tfjsCore.util.now() - start;
              return [2, { kernelMs }];
            });
          });
        };
        MathBackendCPU2.prototype.memory = function() {
          return {
            // Unreliable due to automatic gc. The numbers above are cumulative.
            unreliable: true,
            reasons: ["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]
          };
        };
        MathBackendCPU2.prototype.where = function(condition) {
          assertNotComplex([condition], "where");
          var condVals = this.readSync(condition.dataId);
          return whereImpl(condition.shape, condVals);
        };
        MathBackendCPU2.prototype.dispose = function() {
        };
        MathBackendCPU2.prototype.floatPrecision = function() {
          return 32;
        };
        MathBackendCPU2.prototype.epsilon = function() {
          return _super.prototype.epsilon.call(this);
        };
        return MathBackendCPU2;
      }(tfjsCore.KernelBackend)
    );
    MathBackendCPU.nextDataId = 0;
    function simpleAbsImpl(vals) {
      var resultValues = new Float32Array(vals.length);
      for (var i = 0; i < vals.length; ++i) {
        resultValues[i] = Math.abs(vals[i]);
      }
      return resultValues;
    }
    var abs = function(args) {
      var x = args.inputs.x;
      var cpuBackend = args.backend;
      assertNotComplex(x, "abs");
      var resultValues = new Float32Array(tfjsCore.util.sizeFromShape(x.shape));
      var values = cpuBackend.data.get(x.dataId).values;
      resultValues = simpleAbsImpl(values);
      return cpuBackend.makeOutput(resultValues, x.shape, x.dtype);
    };
    var absConfig = {
      kernelName: tfjsCore.Abs,
      backendName: "cpu",
      kernelFunc: abs
    };
    function createSimpleBinaryKernelImpl(op) {
      return function(aShape, bShape, aVals, bVals, dtype) {
        var newShape = tfjsCore.backend_util.assertAndGetBroadcastShape(aShape, bShape);
        var resultRank = newShape.length;
        var resultStrides = tfjsCore.util.computeStrides(newShape);
        var resultSize = tfjsCore.util.sizeFromShape(newShape);
        var result = tfjsCore.util.getTypedArrayFromDType(dtype, resultSize);
        var aRank = aShape.length;
        var bRank = bShape.length;
        var aStrides = tfjsCore.util.computeStrides(aShape);
        var bStrides = tfjsCore.util.computeStrides(bShape);
        var aBroadcastDims = tfjsCore.backend_util.getBroadcastDims(aShape, newShape);
        var bBroadcastDims = tfjsCore.backend_util.getBroadcastDims(bShape, newShape);
        if (aBroadcastDims.length + bBroadcastDims.length === 0) {
          for (var i = 0; i < result.length; ++i) {
            result[i] = op(aVals[i % aVals.length], bVals[i % bVals.length]);
          }
        } else {
          var _loop_1 = function(i2) {
            var loc = tfjsCore.util.indexToLoc(i2, resultRank, resultStrides);
            var aLoc = loc.slice(-aRank);
            aBroadcastDims.forEach(function(d) {
              return aLoc[d] = 0;
            });
            var aIndex = tfjsCore.util.locToIndex(aLoc, aRank, aStrides);
            var bLoc = loc.slice(-bRank);
            bBroadcastDims.forEach(function(d) {
              return bLoc[d] = 0;
            });
            var bIndex = tfjsCore.util.locToIndex(bLoc, bRank, bStrides);
            result[i2] = op(aVals[aIndex], bVals[bIndex]);
          };
          for (var i = 0; i < result.length; ++i) {
            _loop_1(i);
          }
        }
        return [result, newShape];
      };
    }
    function complex(args) {
      var inputs = args.inputs, backend = args.backend;
      var real2 = inputs.real, imag2 = inputs.imag;
      var realVals = backend.data.get(real2.dataId).values;
      var imagVals = backend.data.get(imag2.dataId).values;
      var complexInfo = backend.makeTensorInfo(real2.shape, "complex64");
      var complex2 = backend.data.get(complexInfo.dataId);
      complex2.complexTensorInfos = {
        real: backend.makeTensorInfo(real2.shape, "float32", realVals),
        imag: backend.makeTensorInfo(imag2.shape, "float32", imagVals)
      };
      return complexInfo;
    }
    var complexConfig = {
      kernelName: tfjsCore.Complex,
      backendName: "cpu",
      kernelFunc: complex
    };
    function zeros(backend, shape, dtype) {
      if (dtype === void 0) {
        dtype = "float32";
      }
      if (dtype === "complex64") {
        var real2 = zeros(backend, shape, "float32");
        var imag2 = zeros(backend, shape, "float32");
        return complex({ inputs: { real: real2, imag: imag2 }, backend });
      }
      var values = tfjsCore.util.makeZerosTypedArray(tfjsCore.util.sizeFromShape(shape), dtype);
      return backend.makeTensorInfo(shape, dtype, values);
    }
    function identity(args) {
      var inputs = args.inputs, backend = args.backend;
      var x = inputs.x;
      backend.incRef(x.dataId);
      return { dataId: x.dataId, shape: x.shape, dtype: x.dtype };
    }
    var identityConfig = {
      kernelName: tfjsCore.Identity,
      backendName: "cpu",
      kernelFunc: identity
    };
    function real(args) {
      var inputs = args.inputs, backend = args.backend;
      var input = inputs.input;
      var real2 = backend.data.get(input.dataId).complexTensorInfos.real;
      var realVal = backend.data.get(real2.dataId).values;
      return backend.makeTensorInfo(real2.shape, real2.dtype, realVal);
    }
    var realConfig = {
      kernelName: tfjsCore.Real,
      backendName: "cpu",
      kernelFunc: real
    };
    function castImpl(values, shape, inputType, dtype) {
      if (dtype === "int32") {
        var resultValues = Int32Array.from(values);
        return [shape, "int32", resultValues];
      }
      if (dtype === "bool") {
        var zero = tfjsCore.util.toTypedArray([0], inputType);
        var _a2 = __read(createSimpleBinaryKernelImpl(function(a, b) {
          return a !== b ? 1 : 0;
        })(shape, [], values, zero, "bool"), 2), resultData = _a2[0], resultShape = _a2[1];
        return [resultShape, "bool", resultData];
      }
      throw new Error("Error in Cast: failed to cast ".concat(inputType, " to ").concat(dtype));
    }
    function cast(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var dtype = attrs.dtype;
      if (dtype === "complex64") {
        if (x.dtype === "complex64") {
          return identity({ inputs: { x }, backend });
        }
        var zerosTensorInfo = zeros(backend, x.shape, x.dtype);
        var floatX = cast({ inputs: { x }, backend, attrs: { dtype: "float32" } });
        var result = complex({ inputs: { real: floatX, imag: zerosTensorInfo }, backend });
        backend.disposeIntermediateTensorInfo(zerosTensorInfo);
        backend.disposeIntermediateTensorInfo(floatX);
        return result;
      }
      if (x.dtype === "complex64") {
        var realPart = real({ inputs: { input: x }, backend });
        var result = cast({ inputs: { x: realPart }, backend, attrs: { dtype } });
        backend.disposeIntermediateTensorInfo(realPart);
        return result;
      }
      if (!tfjsCore.util.hasEncodingLoss(x.dtype, dtype)) {
        var result = identity({ inputs: { x }, backend });
        return { dataId: result.dataId, shape: result.shape, dtype };
      }
      var values = backend.data.get(x.dataId).values;
      var _a2 = __read(castImpl(values, x.shape, x.dtype, dtype), 3), resultShape = _a2[0], resultType = _a2[1], resultData = _a2[2];
      return backend.makeTensorInfo(resultShape, resultType, resultData);
    }
    var castConfig = {
      kernelName: tfjsCore.Cast,
      backendName: "cpu",
      kernelFunc: cast
    };
    function binaryKernelFunc(name, simpleImpl, complexImpl, dtype) {
      if (complexImpl == null) {
        return function(_a2) {
          var inputs = _a2.inputs, backend = _a2.backend;
          var a = inputs.a, b = inputs.b;
          var cpuBackend = backend;
          assertNotComplex([a, b], name);
          var aVals = cpuBackend.data.get(a.dataId).values;
          var bVals = cpuBackend.data.get(b.dataId).values;
          var decodedAVals = a.dtype === "string" ? (
            // tslint:disable-next-line: no-any
            tfjsCore.backend_util.fromUint8ToStringArray(aVals)
          ) : aVals;
          var decodedBVals = a.dtype === "string" ? (
            // tslint:disable-next-line: no-any
            tfjsCore.backend_util.fromUint8ToStringArray(bVals)
          ) : bVals;
          var $dtype = dtype || a.dtype;
          var _b = __read(simpleImpl(a.shape, b.shape, decodedAVals, decodedBVals, $dtype), 2), resultData = _b[0], resultShape = _b[1];
          return cpuBackend.makeTensorInfo(resultShape, $dtype, resultData);
        };
      }
      return function(_a2) {
        var inputs = _a2.inputs, backend = _a2.backend;
        var a = inputs.a, b = inputs.b;
        var cpuBackend = backend;
        if (a.dtype === "complex64" || b.dtype === "complex64") {
          var $aComplex = cast({ inputs: { x: a }, backend: cpuBackend, attrs: { dtype: "complex64" } });
          var $aComplexVals = cpuBackend.data.get($aComplex.dataId);
          var aReal = $aComplexVals.complexTensorInfos.real;
          var aImag = $aComplexVals.complexTensorInfos.imag;
          var aRealVals = cpuBackend.data.get(aReal.dataId).values;
          var aImagVals = cpuBackend.data.get(aImag.dataId).values;
          var $bComplex = cast({ inputs: { x: b }, backend: cpuBackend, attrs: { dtype: "complex64" } });
          var $bComplexVals = cpuBackend.data.get($bComplex.dataId);
          var bReal = $bComplexVals.complexTensorInfos.real;
          var bImag = $bComplexVals.complexTensorInfos.imag;
          var bRealVals = cpuBackend.data.get(bReal.dataId).values;
          var bImagVals = cpuBackend.data.get(bImag.dataId).values;
          var _b = __read(complexImpl(a.shape, b.shape, aRealVals, aImagVals, bRealVals, bImagVals), 3), resultRealData = _b[0], resultImagData = _b[1], resultShape = _b[2];
          var resultReal = cpuBackend.makeTensorInfo(resultShape, "float32", resultRealData);
          var resultImag = cpuBackend.makeTensorInfo(resultShape, "float32", resultImagData);
          var result = complex({ inputs: { real: resultReal, imag: resultImag }, backend: cpuBackend });
          cpuBackend.disposeIntermediateTensorInfo($aComplex);
          cpuBackend.disposeIntermediateTensorInfo($bComplex);
          cpuBackend.disposeIntermediateTensorInfo(resultReal);
          cpuBackend.disposeIntermediateTensorInfo(resultImag);
          return result;
        } else {
          var aVals = cpuBackend.data.get(a.dataId).values;
          var bVals = cpuBackend.data.get(b.dataId).values;
          var $dtype = dtype || a.dtype;
          var _c = __read(simpleImpl(a.shape, b.shape, aVals, bVals, $dtype), 2), resultData = _c[0], resultShape = _c[1];
          return cpuBackend.makeTensorInfo(resultShape, $dtype, resultData);
        }
      };
    }
    function createComplexBinaryKernelImpl(op) {
      return function(aShape, bShape, aRealVals, aImagVals, bRealVals, bImagVals) {
        var resultShape = tfjsCore.backend_util.assertAndGetBroadcastShape(aShape, bShape);
        var resultSize = tfjsCore.util.sizeFromShape(resultShape);
        var resultRank = resultShape.length;
        var resultStrides = tfjsCore.util.computeStrides(resultShape);
        var resultRealVals = tfjsCore.util.getTypedArrayFromDType("float32", resultSize);
        var resultImagVals = tfjsCore.util.getTypedArrayFromDType("float32", resultSize);
        var aBroadcastDims = tfjsCore.backend_util.getBroadcastDims(aShape, resultShape);
        var bBroadcastDims = tfjsCore.backend_util.getBroadcastDims(bShape, resultShape);
        var aVals = tfjsCore.backend_util.mergeRealAndImagArrays(aRealVals, aImagVals);
        var bVals = tfjsCore.backend_util.mergeRealAndImagArrays(bRealVals, bImagVals);
        var aRank = aShape.length;
        var aStrides = tfjsCore.util.computeStrides(aShape);
        var bRank = bShape.length;
        var bStrides = tfjsCore.util.computeStrides(bShape);
        if (aBroadcastDims.length + bBroadcastDims.length === 0) {
          for (var i = 0; i < resultRealVals.length; i++) {
            var aIdx = i % aVals.length;
            var bIdx = i % bVals.length;
            var result = op(aVals[aIdx * 2], aVals[aIdx * 2 + 1], bVals[bIdx * 2], bVals[bIdx * 2 + 1]);
            resultRealVals[i] = result.real;
            resultImagVals[i] = result.imag;
          }
        } else {
          var _loop_1 = function(i2) {
            var loc = tfjsCore.util.indexToLoc(i2, resultRank, resultStrides);
            var aLoc = loc.slice(-aRank);
            aBroadcastDims.forEach(function(d) {
              return aLoc[d] = 0;
            });
            var aIndex = tfjsCore.util.locToIndex(aLoc, aRank, aStrides);
            var bLoc = loc.slice(-bRank);
            bBroadcastDims.forEach(function(d) {
              return bLoc[d] = 0;
            });
            var bIndex = tfjsCore.util.locToIndex(bLoc, bRank, bStrides);
            var opResult = op(aVals[aIndex * 2], aVals[aIndex * 2 + 1], bVals[bIndex * 2], bVals[bIndex * 2 + 1]);
            resultRealVals[i2] = opResult.real;
            resultImagVals[i2] = opResult.imag;
          };
          for (var i = 0; i < resultRealVals.length; i++) {
            _loop_1(i);
          }
        }
        return [resultRealVals, resultImagVals, resultShape];
      };
    }
    var addImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a + b;
    });
    var addComplexImpl = createComplexBinaryKernelImpl(function(aReal, aImag, bReal, bImag) {
      return { real: aReal + bReal, imag: aImag + bImag };
    });
    var add = binaryKernelFunc(tfjsCore.Add, addImpl, addComplexImpl);
    var addConfig = {
      kernelName: tfjsCore.Add,
      backendName: "cpu",
      kernelFunc: add
    };
    function bincountImpl(xVals, weightsVals, weightsDtype, weightsShape, size) {
      var weightsSize = tfjsCore.util.sizeFromShape(weightsShape);
      var outVals = tfjsCore.util.makeZerosTypedArray(size, weightsDtype);
      for (var i = 0; i < xVals.length; i++) {
        var value = xVals[i];
        if (value < 0) {
          throw new Error("Input x must be non-negative!");
        }
        if (value >= size) {
          continue;
        }
        if (weightsSize > 0) {
          outVals[value] += weightsVals[i];
        } else {
          outVals[value] += 1;
        }
      }
      return outVals;
    }
    function bincountReduceImpl(xBuf, weightsBuf, size, binaryOutput) {
      if (binaryOutput === void 0) {
        binaryOutput = false;
      }
      var numRows = xBuf.shape[0];
      var numCols = xBuf.shape[1];
      var outBuf = tfjsCore.buffer([numRows, size], weightsBuf.dtype);
      for (var i = 0; i < numRows; i++) {
        for (var j = 0; j < numCols; j++) {
          var value = xBuf.get(i, j);
          if (value < 0) {
            throw new Error("Input x must be non-negative!");
          }
          if (value >= size) {
            continue;
          }
          if (binaryOutput) {
            outBuf.set(1, i, value);
          } else {
            if (weightsBuf.size > 0) {
              outBuf.set(outBuf.get(i, value) + weightsBuf.get(i, j), i, value);
            } else {
              outBuf.set(outBuf.get(i, value) + 1, i, value);
            }
          }
        }
      }
      return outBuf;
    }
    var bitwiseAndImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a & b;
    });
    var bitwiseAnd = binaryKernelFunc(tfjsCore.BitwiseAnd, bitwiseAndImpl);
    var bitwiseAndConfig = {
      kernelName: tfjsCore.BitwiseAnd,
      backendName: "cpu",
      kernelFunc: bitwiseAnd
    };
    function createSimpleUnaryImpl(op) {
      return function(values, dtype, attrs) {
        var newValues = tfjsCore.util.getArrayFromDType(dtype, values.length);
        for (var i = 0; i < values.length; ++i) {
          newValues[i] = op(values[i], attrs);
        }
        return newValues;
      };
    }
    function unaryKernelFunc(name, op, dtype) {
      var impl = createSimpleUnaryImpl(op);
      return unaryKernelFuncFromImpl(name, impl, dtype);
    }
    function unaryKernelFuncFromImpl(name, unaryImpl, dtype) {
      return function(_a2) {
        var inputs = _a2.inputs, attrs = _a2.attrs, backend = _a2.backend;
        var x = inputs.x;
        assertNotComplex(x, name);
        var cpuBackend = backend;
        var values = cpuBackend.data.get(x.dataId).values;
        var decoded;
        if (x.dtype === "string") {
          if (!Array.isArray(values)) {
            throw new Error("String tensor's value was not an instance of Array");
          }
          decoded = tfjsCore.backend_util.fromUint8ToStringArray(values);
        } else {
          decoded = values;
        }
        var $dtype = dtype || x.dtype;
        var newValues = unaryImpl(decoded, $dtype, attrs);
        return cpuBackend.makeTensorInfo(x.shape, $dtype, newValues);
      };
    }
    var ceilImpl = createSimpleUnaryImpl(function(xi) {
      return Math.ceil(xi);
    });
    var ceil = unaryKernelFuncFromImpl(tfjsCore.Ceil, ceilImpl);
    var ceilConfig = {
      kernelName: tfjsCore.Ceil,
      backendName: "cpu",
      kernelFunc: ceil
    };
    function concatImpl(inputs, outShape, dtype, simplyConcat) {
      var outVals = tfjsCore.util.getArrayFromDType(dtype, tfjsCore.util.sizeFromShape(outShape));
      if (simplyConcat && dtype !== "string") {
        var offset_1 = 0;
        inputs.forEach(function(input) {
          var size = tfjsCore.util.sizeFromShape(input.shape);
          outVals.set(input.vals, offset_1);
          offset_1 += size;
        });
      } else {
        var colOffset_1 = 0;
        inputs.forEach(function(input) {
          var decodedData = dtype === "string" ? tfjsCore.backend_util.fromUint8ToStringArray(input.vals) : input.vals;
          var tIdx = 0;
          for (var row = 0; row < input.shape[0]; ++row) {
            var resIdx = row * outShape[1] + colOffset_1;
            for (var col = 0; col < input.shape[1]; ++col) {
              outVals[resIdx + col] = decodedData[tIdx++];
            }
          }
          colOffset_1 += input.shape[1];
        });
      }
      return outVals;
    }
    var equalImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a === b ? 1 : 0;
    });
    var equal = binaryKernelFunc(tfjsCore.Equal, equalImpl, null, "bool");
    var equalConfig = {
      kernelName: tfjsCore.Equal,
      backendName: "cpu",
      kernelFunc: equal
    };
    var expImpl = createSimpleUnaryImpl(function(xi) {
      return Math.exp(xi);
    });
    var exp = unaryKernelFuncFromImpl(tfjsCore.Exp, expImpl, "float32");
    var expConfig = {
      kernelName: tfjsCore.Exp,
      backendName: "cpu",
      kernelFunc: exp
    };
    var expm1Impl = createSimpleUnaryImpl(function(xi) {
      return Math.expm1(xi);
    });
    var expm1 = unaryKernelFuncFromImpl(tfjsCore.Expm1, expm1Impl);
    var expm1Config = {
      kernelName: tfjsCore.Expm1,
      backendName: "cpu",
      kernelFunc: expm1
    };
    var floorImpl = createSimpleUnaryImpl(function(xi) {
      return Math.floor(xi);
    });
    var floor = unaryKernelFuncFromImpl(tfjsCore.Floor, floorImpl);
    var floorConfig = {
      kernelName: tfjsCore.Floor,
      backendName: "cpu",
      kernelFunc: floor
    };
    var floorDivImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return Math.floor(a / b);
    });
    var floorDiv = binaryKernelFunc(tfjsCore.FloorDiv, floorDivImpl, null, "int32");
    var floorDivConfig = {
      kernelName: tfjsCore.FloorDiv,
      backendName: "cpu",
      kernelFunc: floorDiv
    };
    function gatherNdImpl(indicesData, paramsBuf, dtype, numSlices, sliceRank, sliceSize, strides, paramsShape, paramsSize) {
      var outBuf = tfjsCore.buffer([numSlices, sliceSize], dtype);
      for (var i = 0; i < numSlices; i++) {
        var index = [];
        var flattenIndex = 0;
        for (var j = 0; j < sliceRank; j++) {
          var dim = indicesData[i * sliceRank + j];
          flattenIndex += dim * strides[j];
          index.push(dim);
        }
        if (flattenIndex < 0 || flattenIndex >= paramsSize / sliceSize) {
          throw new Error("Invalid indices: ".concat(index, " does not index into ").concat(paramsShape));
        }
        for (var k = 0; k < sliceSize; k++) {
          outBuf.values[i * sliceSize + k] = paramsBuf.get.apply(paramsBuf, __spreadArray([], __read(paramsBuf.indexToLoc(flattenIndex * sliceSize + k)), false));
        }
      }
      return outBuf;
    }
    function gatherV2Impl(xBuf, indicesBuf, flattenOutputShape) {
      var outBuf = tfjsCore.buffer(flattenOutputShape, xBuf.dtype);
      for (var i = 0; i < outBuf.size; ++i) {
        var newLoc = outBuf.indexToLoc(i);
        var originalLoc = newLoc.slice();
        var batchIdx = originalLoc[0];
        var indicesIdx = originalLoc[2];
        var indicesIndex = indicesBuf.locToIndex([batchIdx, indicesIdx]);
        originalLoc[2] = indicesBuf.values[indicesIndex];
        var originalIndex = xBuf.locToIndex(originalLoc);
        if (0 <= originalIndex && originalIndex < xBuf.values.length) {
          outBuf.values[i] = xBuf.values[originalIndex];
        }
      }
      return outBuf;
    }
    var greaterImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a > b ? 1 : 0;
    });
    var greater = binaryKernelFunc(tfjsCore.Greater, greaterImpl, null, "bool");
    var greaterConfig = {
      kernelName: tfjsCore.Greater,
      backendName: "cpu",
      kernelFunc: greater
    };
    var greaterEqualImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a >= b ? 1 : 0;
    });
    var greaterEqual = binaryKernelFunc(tfjsCore.GreaterEqual, greaterEqualImpl, null, "bool");
    var greaterEqualConfig = {
      kernelName: tfjsCore.GreaterEqual,
      backendName: "cpu",
      kernelFunc: greaterEqual
    };
    var lessImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a < b ? 1 : 0;
    });
    var less = binaryKernelFunc(tfjsCore.Less, lessImpl, null, "bool");
    var lessConfig = {
      kernelName: tfjsCore.Less,
      backendName: "cpu",
      kernelFunc: less
    };
    var lessEqualImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a <= b ? 1 : 0;
    });
    var lessEqual = binaryKernelFunc(tfjsCore.LessEqual, lessEqualImpl, null, "bool");
    var lessEqualConfig = {
      kernelName: tfjsCore.LessEqual,
      backendName: "cpu",
      kernelFunc: lessEqual
    };
    function linSpaceImpl(start, stop, num) {
      var step2 = (stop - start) / (num - 1);
      var values = tfjsCore.util.makeZerosTypedArray(num, "float32");
      values[0] = start;
      for (var i = 1; i < values.length; i++) {
        values[i] = values[i - 1] + step2;
      }
      return values;
    }
    var logImpl = createSimpleUnaryImpl(function(xi) {
      return Math.log(xi);
    });
    var log = unaryKernelFuncFromImpl(tfjsCore.Log, logImpl);
    var logConfig = {
      kernelName: tfjsCore.Log,
      backendName: "cpu",
      kernelFunc: log
    };
    function maxImpl(aVals, reduceSize, outShape, dtype) {
      var vals = tfjsCore.util.getTypedArrayFromDType(dtype, tfjsCore.util.sizeFromShape(outShape));
      for (var i = 0; i < vals.length; ++i) {
        var offset = i * reduceSize;
        var max2 = aVals[offset];
        for (var j = 0; j < reduceSize; ++j) {
          var value = aVals[offset + j];
          if (Number.isNaN(value) || value > max2) {
            max2 = value;
          }
        }
        vals[i] = max2;
      }
      return vals;
    }
    var maximumImpl = createSimpleBinaryKernelImpl(function(aValue, bValue) {
      return Math.max(aValue, bValue);
    });
    var maximum = binaryKernelFunc(tfjsCore.Maximum, maximumImpl);
    var maximumConfig = {
      kernelName: tfjsCore.Maximum,
      backendName: "cpu",
      kernelFunc: maximum
    };
    var minimumImpl = createSimpleBinaryKernelImpl(function(aValue, bValue) {
      return Math.min(aValue, bValue);
    });
    var minimum = binaryKernelFunc(tfjsCore.Minimum, minimumImpl);
    var minimumConfig = {
      kernelName: tfjsCore.Minimum,
      backendName: "cpu",
      kernelFunc: minimum
    };
    var multiplyImpl = createSimpleBinaryKernelImpl(function(aValue, bValue) {
      return aValue * bValue;
    });
    var multiplyComplexImpl = createComplexBinaryKernelImpl(function(aReal, aImag, bReal, bImag) {
      return {
        real: aReal * bReal - aImag * bImag,
        imag: aReal * bImag + aImag * bReal
      };
    });
    var multiply = binaryKernelFunc(tfjsCore.Multiply, multiplyImpl, multiplyComplexImpl);
    var multiplyConfig = {
      kernelName: tfjsCore.Multiply,
      backendName: "cpu",
      kernelFunc: multiply
    };
    function negImpl(xVals, xShape, xDtype) {
      var minusOne = tfjsCore.util.createScalarValue(-1, xDtype);
      return multiplyImpl([], xShape, minusOne, xVals, xDtype);
    }
    function neg(args) {
      var inputs = args.inputs, backend = args.backend;
      var x = inputs.x;
      assertNotComplex(x, "neg");
      var xVals = backend.data.get(x.dataId).values;
      var _a2 = __read(negImpl(xVals, x.shape, x.dtype), 2), res = _a2[0], newShape = _a2[1];
      return backend.makeTensorInfo(newShape, x.dtype, res);
    }
    var negConfig = {
      kernelName: tfjsCore.Neg,
      backendName: "cpu",
      kernelFunc: neg
    };
    var notEqualImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a !== b ? 1 : 0;
    });
    var notEqual = binaryKernelFunc(tfjsCore.NotEqual, notEqualImpl, null, "bool");
    var notEqualConfig = {
      kernelName: tfjsCore.NotEqual,
      backendName: "cpu",
      kernelFunc: notEqual
    };
    function transposeImpl(xVals, xShape, dtype, perm, newShape) {
      var xRank = xShape.length;
      var xSize = tfjsCore.util.sizeFromShape(xShape);
      var xStrides = tfjsCore.util.computeStrides(xShape);
      var newStrides = tfjsCore.util.computeStrides(newShape);
      var result = tfjsCore.util.getTypedArrayFromDType(dtype, tfjsCore.util.sizeFromShape(newShape));
      for (var i = 0; i < xSize; ++i) {
        var loc = tfjsCore.util.indexToLoc(i, xRank, xStrides);
        var newLoc = new Array(loc.length);
        for (var i_1 = 0; i_1 < newLoc.length; i_1++) {
          newLoc[i_1] = loc[perm[i_1]];
        }
        var newIndex = tfjsCore.util.locToIndex(newLoc, xRank, newStrides);
        result[newIndex] = xVals[i];
      }
      return result;
    }
    function transpose(args) {
      var inputs = args.inputs, attrs = args.attrs, backend = args.backend;
      var x = inputs.x;
      var perm = attrs.perm;
      assertNotComplex(x, "transpose");
      var xRank = x.shape.length;
      var newShape = new Array(xRank);
      for (var i = 0; i < newShape.length; i++) {
        newShape[i] = x.shape[perm[i]];
      }
      var values = backend.data.get(x.dataId).values;
      var result = transposeImpl(values, x.shape, x.dtype, perm, newShape);
      var dataId = backend.write(result, newShape, x.dtype);
      return { dataId, shape: newShape, dtype: x.dtype };
    }
    var transposeConfig = {
      kernelName: tfjsCore.Transpose,
      backendName: "cpu",
      kernelFunc: transpose
    };
    function prodImpl(xShape, xDtype, xVals, reductionAxes) {
      var _a2 = __read(tfjsCore.backend_util.computeOutAndReduceShapes(xShape, reductionAxes), 2), outShape = _a2[0], reduceShape = _a2[1];
      var outDtype = tfjsCore.upcastType(xDtype, "int32");
      var outVals = tfjsCore.util.makeZerosTypedArray(tfjsCore.util.sizeFromShape(outShape), outDtype);
      var reduceSize = tfjsCore.util.sizeFromShape(reduceShape);
      for (var i = 0; i < outVals.length; ++i) {
        var offset = i * reduceSize;
        var prod_1 = 1;
        for (var j = 0; j < reduceSize; ++j) {
          prod_1 *= xVals[offset + j];
        }
        outVals[i] = prod_1;
      }
      return { outVals, outShape, outDtype };
    }
    function prod(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis, keepDims = attrs.keepDims;
      assertNotComplex(x, "prod");
      var xRank = x.shape.length;
      var axes = tfjsCore.util.parseAxisParam(axis, x.shape);
      var permutation = tfjsCore.backend_util.getAxesPermutation(axes, xRank);
      var reductionAxes = axes;
      var permutedX = x;
      var intermediateTensorInfos = [];
      if (permutation != null) {
        permutedX = transpose({ inputs: { x }, backend, attrs: { perm: permutation } });
        intermediateTensorInfos.push(permutedX);
        reductionAxes = tfjsCore.backend_util.getInnerMostAxes(reductionAxes.length, xRank);
      }
      var xVals = backend.data.get(permutedX.dataId).values;
      var _a2 = prodImpl(permutedX.shape, permutedX.dtype, xVals, reductionAxes), outVals = _a2.outVals, outShape = _a2.outShape, outDtype = _a2.outDtype;
      var resultShape = outShape;
      if (keepDims) {
        resultShape = tfjsCore.backend_util.expandShapeToKeepDim(outShape, axes);
      }
      intermediateTensorInfos.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return backend.makeTensorInfo(resultShape, outDtype, outVals);
    }
    var prodConfig = {
      kernelName: tfjsCore.Prod,
      backendName: "cpu",
      kernelFunc: prod
    };
    function validateIndices(indices, indicesShape, numParams) {
      indices.forEach(function(index, i) {
        if (index < 0 || index >= numParams) {
          var locString = tfjsCore.util.indexToLoc(i, indicesShape.length, tfjsCore.util.computeStrides(indicesShape)).join(",");
          throw new Error("indices[".concat(locString, "] = ").concat(index, " is not in [0, ").concat(numParams, ")"));
        }
      });
    }
    function validateSplits(paramsNestedSplits, numParamsDenseValues) {
      for (var dim = 0; dim < paramsNestedSplits.length; ++dim) {
        var splits = paramsNestedSplits[dim];
        var lastSplit = dim === paramsNestedSplits.length - 1 ? numParamsDenseValues : paramsNestedSplits[dim + 1].length;
        if (splits.length === 0) {
          throw new Error("Ragged splits may not be empty");
        }
        if (splits[0] < 0) {
          throw new Error("Ragged splits must be non-negative");
        }
        if (splits[splits.length - 1] > lastSplit) {
          throw new Error("Ragged splits must not point past values");
        }
        for (var i = 1; i < splits.length; ++i) {
          if (splits[i - 1] > splits[i]) {
            throw new Error("Ragged splits must be sorted in ascending order");
          }
        }
      }
    }
    function makeSplits(indices, indicesShape, paramsNestedSplits, numParamsDenseValues) {
      var valueSlices = [];
      var numValues = 0;
      var numSplits = indicesShape.length - 1 + paramsNestedSplits.length;
      var outSplits = new Array(numSplits).fill(null).map(function() {
        return [0];
      });
      validateSplits(paramsNestedSplits, numParamsDenseValues);
      var nrows = 1;
      for (var dim = 0; dim < indicesShape.length - 1; ++dim) {
        nrows *= indicesShape[dim];
        var rowLength = indicesShape[dim + 1];
        for (var i = 1; i < nrows + 1; ++i) {
          outSplits[dim].push(i * rowLength);
        }
      }
      for (var i = 0; i < indices.length; ++i) {
        var start = indices[i];
        var limit = indices[i] + 1;
        for (var dim = 0; dim < paramsNestedSplits.length; ++dim) {
          var splits = paramsNestedSplits[dim];
          var outDim = dim + indicesShape.length - 1;
          if (outDim >= 0) {
            var outSplitsOutDim = outSplits[outDim];
            var delta = outSplitsOutDim[outSplitsOutDim.length - 1] - splits[start];
            for (var j = start; j < limit; ++j) {
              outSplits[outDim].push(splits[j + 1] + delta);
            }
          }
          start = splits[start];
          limit = splits[limit];
        }
        if (limit !== start) {
          valueSlices.push([start, limit]);
          numValues += limit - start;
        }
      }
      return { outSplits, valueSlices, numValues };
    }
    function getSplits(outSplits) {
      var splitsOut = [];
      var _loop_1 = function(i2) {
        var numSplits = outSplits[i2].length;
        var splits = tfjsCore.util.getArrayFromDType("int32", numSplits);
        splitsOut.push(splits);
        outSplits[i2].forEach(function(value, j) {
          return splits[j] = value;
        });
      };
      for (var i = 0; i < outSplits.length; ++i) {
        _loop_1(i);
      }
      return splitsOut;
    }
    function computeFlatOuterDims(orig, numOutDims) {
      var outDims = orig.slice(0, numOutDims);
      while (outDims.length < numOutDims) {
        outDims.push(1);
      }
      for (var inDim = numOutDims; inDim < orig.length; inDim++) {
        outDims[numOutDims - 1] *= orig[inDim];
      }
      return outDims;
    }
    function writeValueSlices(paramsDenseValues, paramsDenseValuesShape, valueSlices, valueSize, values, valuesShape) {
      var e_12, _a2;
      var denseM = computeFlatOuterDims(paramsDenseValuesShape, 2)[1];
      var valuesM = computeFlatOuterDims(valuesShape, 2)[1];
      var outPos = 0;
      try {
        for (var valueSlices_1 = __values(valueSlices), valueSlices_1_1 = valueSlices_1.next(); !valueSlices_1_1.done; valueSlices_1_1 = valueSlices_1.next()) {
          var slice2 = valueSlices_1_1.value;
          for (var i = slice2[0]; i < slice2[1]; ++i) {
            for (var j = 0; j < valueSize; ++j) {
              values[outPos * valuesM + j] = paramsDenseValues[i * denseM + j];
            }
            ++outPos;
          }
        }
      } catch (e_1_1) {
        e_12 = { error: e_1_1 };
      } finally {
        try {
          if (valueSlices_1_1 && !valueSlices_1_1.done && (_a2 = valueSlices_1.return)) _a2.call(valueSlices_1);
        } finally {
          if (e_12) throw e_12.error;
        }
      }
    }
    function getValues(paramsDenseValues, paramsDenseValuesShape, paramsDenseValuesDType, valueSlices, numValues) {
      var valuesShape = paramsDenseValuesShape.slice();
      valuesShape[0] = numValues;
      var valuesOut = tfjsCore.util.getArrayFromDType(paramsDenseValuesDType, tfjsCore.util.sizeFromShape(valuesShape));
      var numElements = paramsDenseValues.length;
      var valueSize = numElements === 0 ? 0 : numElements / paramsDenseValuesShape[0];
      writeValueSlices(paramsDenseValues, paramsDenseValuesShape, valueSlices, valueSize, valuesOut, valuesShape);
      return [valuesOut, valuesShape];
    }
    function raggedGatherImpl(paramsNestedSplits, paramsNestedSplitsShapes, paramsDenseValues, paramsDenseValuesShape, paramsDenseValuesDType, indices, indicesShape, outputRaggedRank) {
      if (paramsNestedSplits.length === 0) {
        throw new Error("paramsNestedSplits must be non empty");
      }
      if (paramsNestedSplitsShapes[0].length === 0) {
        throw new Error("Split tensors must not be scalars");
      }
      var numParams = paramsNestedSplitsShapes[0][0] - 1;
      validateIndices(indices, indicesShape, numParams);
      if (paramsDenseValuesShape.length === 0) {
        throw new Error("params.rank must be nonzero");
      }
      var numParamsDenseValues = paramsDenseValuesShape[0];
      var _a2 = makeSplits(indices, indicesShape, paramsNestedSplits, numParamsDenseValues), outSplits = _a2.outSplits, valueSlices = _a2.valueSlices, numValues = _a2.numValues;
      var outputNestedSplits = getSplits(outSplits);
      var outputDenseValues = getValues(paramsDenseValues, paramsDenseValuesShape, paramsDenseValuesDType, valueSlices, numValues);
      return [outputNestedSplits, outputDenseValues[0], outputDenseValues[1]];
    }
    var INT32_MAX = 2147483647;
    function raggedRangeImpl(starts, startsShape, startsDType, limits, limitsShape, deltas, deltasShape) {
      if (startsShape.length > 1) {
        throw new Error("starts must be a scalar or vector");
      }
      if (limitsShape.length > 1) {
        throw new Error("limits must be a scalar or vector");
      }
      if (deltasShape.length > 1) {
        throw new Error("deltas must be a scalar or vector");
      }
      var broadcastStarts = startsShape.length === 0;
      var broadcastLimits = limitsShape.length === 0;
      var broadcastDeltas = deltasShape.length === 0;
      var inSizes = [];
      if (!broadcastStarts) {
        inSizes.push(startsShape[0]);
      }
      if (!broadcastLimits) {
        inSizes.push(limitsShape[0]);
      }
      if (!broadcastDeltas) {
        inSizes.push(deltasShape[0]);
      }
      for (var i = 1; i < inSizes.length; ++i) {
        if (inSizes[i] !== inSizes[i - 1]) {
          throw new Error("starts, limits, and deltas must have the same shape");
        }
      }
      var nRows = inSizes.length === 0 ? 1 : inSizes[0];
      var rtNestedSplits = tfjsCore.util.getArrayFromDType("int32", nRows + 1);
      rtNestedSplits[0] = 0;
      for (var row = 0; row < nRows; ++row) {
        var start = broadcastStarts ? starts[0] : starts[row];
        var limit = broadcastLimits ? limits[0] : limits[row];
        var delta = broadcastDeltas ? deltas[0] : deltas[row];
        if (delta === 0) {
          throw new Error("Requires delta != 0");
        }
        var size = (
          // The number of elements in the specified range.
          void 0
        );
        if (delta > 0 && limit < start || delta < 0 && limit > start) {
          size = 0;
        } else {
          size = Math.ceil(Math.abs((limit - start) / delta));
          if (size > INT32_MAX) {
            throw new Error("Requires ((limit - start) / delta) <= ".concat(INT32_MAX));
          }
        }
        rtNestedSplits[row + 1] = rtNestedSplits[row] + size;
      }
      var nVals = rtNestedSplits[nRows];
      var rtDenseValues = tfjsCore.util.getArrayFromDType(startsDType, nVals);
      var valueIndex = 0;
      for (var row = 0; row < nRows; ++row) {
        var rowSize = rtNestedSplits[row + 1] - rtNestedSplits[row];
        var value = broadcastStarts ? starts[0] : starts[row];
        var delta = broadcastDeltas ? deltas[0] : deltas[row];
        for (var i = 0; i < rowSize; ++i) {
          rtDenseValues[valueIndex++] = value;
          value += delta;
        }
      }
      return [rtNestedSplits, rtDenseValues];
    }
    var RowPartitionType = tfjsCore.backend_util.RowPartitionType;
    var RaggedTensorToTensorOp = (
      /** @class */
      function() {
        function RaggedTensorToTensorOp2(shape, shapeShape, values, valuesShape, valuesDType, defaultValue, defaultValueShape, rowPartitionValues, rowPartitionValuesShapes, rowPartitionTypeStrings) {
          this.shape = shape;
          this.shapeShape = shapeShape;
          this.values = values;
          this.valuesShape = valuesShape;
          this.valuesDType = valuesDType;
          this.defaultValue = defaultValue;
          this.defaultValueShape = defaultValueShape;
          this.rowPartitionValues = rowPartitionValues;
          this.rowPartitionValuesShapes = rowPartitionValuesShapes;
          this.rowPartitionTypes = tfjsCore.backend_util.getRowPartitionTypesHelper(rowPartitionTypeStrings);
          this.raggedRank = tfjsCore.backend_util.getRaggedRank(this.rowPartitionTypes);
        }
        RaggedTensorToTensorOp2.prototype.getRowPartitionTypeByDimension = function(dimension) {
          if (this.rowPartitionTypes[0] === RowPartitionType.FIRST_DIM_SIZE) {
            return this.rowPartitionTypes[dimension + 1];
          } else {
            return this.rowPartitionTypes[dimension];
          }
        };
        RaggedTensorToTensorOp2.prototype.getRowPartitionTensor = function(dimension) {
          if (this.rowPartitionTypes[0] === RowPartitionType.FIRST_DIM_SIZE) {
            return this.rowPartitionValues[dimension + 1];
          } else {
            return this.rowPartitionValues[dimension];
          }
        };
        RaggedTensorToTensorOp2.prototype.getMaxWidth = function(dimension) {
          var rowPartitionTensor = this.getRowPartitionTensor(dimension - 1);
          switch (this.getRowPartitionTypeByDimension(dimension - 1)) {
            case RowPartitionType.VALUE_ROWIDS:
              return RaggedTensorToTensorOp2.getMaxWidthValueRowID(rowPartitionTensor);
            case RowPartitionType.ROW_SPLITS:
              return RaggedTensorToTensorOp2.getMaxWidthRowSplit(rowPartitionTensor);
            default:
              throw new Error("Cannot handle partition type ".concat(RowPartitionType[this.getRowPartitionTypeByDimension(dimension - 1)]));
          }
        };
        RaggedTensorToTensorOp2.getMaxWidthRowSplit = function(rowSplit) {
          var tensorLength = rowSplit.length;
          if (tensorLength === 0 || tensorLength === 1) {
            return 0;
          }
          var maxWidth = 0;
          for (var i = 0; i < tensorLength - 1; ++i) {
            var currentWidth = rowSplit[i + 1] - rowSplit[i];
            if (currentWidth > maxWidth) {
              maxWidth = currentWidth;
            }
          }
          return maxWidth;
        };
        RaggedTensorToTensorOp2.getMaxWidthValueRowID = function(valueRowIds) {
          var indexLength = valueRowIds.length;
          if (indexLength === 0) {
            return 0;
          }
          var firstEqualIndex = 0;
          var firstEqualIndexValue = valueRowIds[0];
          var maxWidth = 0;
          for (var i = 1; i < indexLength; ++i) {
            var value = valueRowIds[i];
            if (value !== firstEqualIndexValue) {
              firstEqualIndexValue = value;
              maxWidth = Math.max(i - firstEqualIndex, maxWidth);
              firstEqualIndex = i;
            }
          }
          return Math.max(indexLength - firstEqualIndex, maxWidth);
        };
        RaggedTensorToTensorOp2.prototype.tensorShapeFromTensor = function(t, tShape, isPartial) {
          if (isPartial === void 0) {
            isPartial = true;
          }
          if (tShape.length === 0) {
            if (t[0] === -1) {
              return [];
            }
            throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.");
          }
          return makeShape(t, isPartial);
        };
        RaggedTensorToTensorOp2.prototype.calculateOutputSize = function(firstDim) {
          var valueShape = this.valuesShape;
          var defaultValueShape = this.defaultValueShape;
          tfjsCore.backend_util.validateDefaultValueShape(defaultValueShape, valueShape);
          var shape = this.tensorShapeFromTensor(this.shape, this.shapeShape);
          var outputShape = tfjsCore.backend_util.combineRaggedTensorToTensorShapes(this.raggedRank, shape, valueShape);
          var result = outputShape;
          if (result[0] < 0) {
            result[0] = firstDim;
          }
          for (var i = 1; i <= this.raggedRank; ++i) {
            if (result[i] < 0) {
              result[i] = this.getMaxWidth(i);
            }
          }
          return result;
        };
        RaggedTensorToTensorOp2.prototype.calculateFirstParentOutputIndex = function(firstDimension, outputIndexMultiplier, firstDimensionOutput) {
          var minDimension = Math.min(firstDimension, firstDimensionOutput);
          var result = [];
          var currentOutputIndex = 0;
          for (var i = 0; i < minDimension; ++i, currentOutputIndex += outputIndexMultiplier) {
            result.push(currentOutputIndex);
          }
          for (var i = minDimension; i < firstDimension; ++i) {
            result.push(-1);
          }
          tfjsCore.util.assert(result.length === firstDimension, function() {
            return "Final length of result must be equal to firstDimension.";
          });
          return result;
        };
        RaggedTensorToTensorOp2.prototype.calculateOutputIndexRowSplit = function(rowSplit, parentOutputIndex, outputIndexMultiplier, outputSize) {
          var rowSplitSize = rowSplit.length;
          var result = [];
          for (var i = 0; i < rowSplitSize - 1; ++i) {
            var rowLength = rowSplit[i + 1] - rowSplit[i];
            var realLength = Math.min(outputSize, rowLength);
            var parentOutputIndexCurrent = parentOutputIndex[i];
            if (parentOutputIndexCurrent === -1) {
              realLength = 0;
            }
            for (var j = 0; j < realLength; ++j) {
              result.push(parentOutputIndexCurrent);
              parentOutputIndexCurrent += outputIndexMultiplier;
            }
            for (var j = 0; j < rowLength - realLength; ++j) {
              result.push(-1);
            }
          }
          if (rowSplitSize > 0 && result.length !== rowSplit[rowSplitSize - 1]) {
            throw new Error("Invalid row split size.");
          }
          return result;
        };
        RaggedTensorToTensorOp2.prototype.calculateOutputIndexValueRowID = function(valueRowIds, parentOutputIndex, outputIndexMultiplier, outputSize) {
          var indexSize = valueRowIds.length;
          var result = [];
          if (indexSize === 0) {
            return [];
          }
          var currentOutputColumn = 0;
          var currentValueRowId = valueRowIds[0];
          if (currentValueRowId >= parentOutputIndex.length) {
            throw new Error("Got currentValueRowId=".concat(currentValueRowId, ", which is not less than ").concat(parentOutputIndex.length));
          }
          var currentOutputIndex = parentOutputIndex[currentValueRowId];
          result.push(currentOutputIndex);
          for (var i = 1; i < indexSize; ++i) {
            var nextValueRowId = valueRowIds[i];
            if (nextValueRowId === currentValueRowId) {
              if (currentOutputIndex >= 0) {
                ++currentOutputColumn;
                if (currentOutputColumn < outputSize) {
                  currentOutputIndex += outputIndexMultiplier;
                } else {
                  currentOutputIndex = -1;
                }
              }
            } else {
              currentOutputColumn = 0;
              currentValueRowId = nextValueRowId;
              if (nextValueRowId >= parentOutputIndex.length) {
                throw new Error("Got nextValueRowId=".concat(nextValueRowId, " which is not less than ").concat(parentOutputIndex.length));
              }
              currentOutputIndex = parentOutputIndex[nextValueRowId];
            }
            result.push(currentOutputIndex);
          }
          if (result.length !== valueRowIds.length) {
            throw new Error("Invalid row ids.");
          }
          return result;
        };
        RaggedTensorToTensorOp2.prototype.calculateOutputIndex = function(dimension, parentOutputIndex, outputIndexMultiplier, outputSize) {
          var rowPartitionTensor = this.getRowPartitionTensor(dimension);
          var partitionType = this.getRowPartitionTypeByDimension(dimension);
          switch (partitionType) {
            case RowPartitionType.VALUE_ROWIDS:
              return this.calculateOutputIndexValueRowID(rowPartitionTensor, parentOutputIndex, outputIndexMultiplier, outputSize);
            case RowPartitionType.ROW_SPLITS:
              if (rowPartitionTensor.length - 1 > parentOutputIndex.length) {
                throw new Error("Row partition size is greater than output size: ".concat(rowPartitionTensor.length - 1, " > ").concat(parentOutputIndex.length));
              }
              return this.calculateOutputIndexRowSplit(rowPartitionTensor, parentOutputIndex, outputIndexMultiplier, outputSize);
            default:
              throw new Error("Unsupported partition type: ".concat(RowPartitionType[partitionType]));
          }
        };
        RaggedTensorToTensorOp2.prototype.getFirstDimensionSize = function() {
          var firstPartitionTensor = this.rowPartitionValues[0];
          if (this.rowPartitionTypes.length === 0) {
            throw new Error("No row_partition_types given.");
          }
          var firstPartitionType = this.rowPartitionTypes[0];
          switch (firstPartitionType) {
            case RowPartitionType.FIRST_DIM_SIZE:
              return firstPartitionTensor[0];
            case RowPartitionType.VALUE_ROWIDS:
              throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");
            case RowPartitionType.ROW_SPLITS:
              return this.rowPartitionValuesShapes[0][0] - 1;
            default:
              throw new Error("Cannot handle type ".concat(RowPartitionType[firstPartitionType]));
          }
        };
        RaggedTensorToTensorOp2.prototype.compute = function() {
          var firstPartitionTensor = this.rowPartitionValues[0];
          if (firstPartitionTensor.length <= 0) {
            throw new Error("Invalid first partition input. Tensor requires at least one element.");
          }
          var firstDimension = this.getFirstDimensionSize();
          var outputSize = this.calculateOutputSize(firstDimension);
          var multiplier = new Array(this.raggedRank + 1);
          multiplier[multiplier.length - 1] = 1;
          for (var i = multiplier.length - 2; i >= 0; --i) {
            multiplier[i] = multiplier[i + 1] * outputSize[i + 1];
          }
          var outputShape = makeShape(outputSize, false);
          var outputTensor = tfjsCore.util.getArrayFromDType(this.valuesDType, tfjsCore.util.sizeFromShape(outputShape));
          var fullSize = multiplier[0] * outputSize[0];
          if (fullSize > 0) {
            var outputIndex = this.calculateFirstParentOutputIndex(firstDimension, multiplier[0], outputSize[0]);
            for (var i = 1; i <= this.raggedRank; ++i) {
              var newOutputIndex = this.calculateOutputIndex(i - 1, outputIndex, multiplier[i], outputSize[i]);
              outputIndex = newOutputIndex;
            }
            this.setOutput(this.raggedRank, outputIndex, outputTensor, outputShape);
          }
          return [outputShape, outputTensor];
        };
        RaggedTensorToTensorOp2.prototype.setOutput = function(raggedRank, outputIndex, outputTensor, outputShape) {
          if (outputTensor.length === 0) {
            return;
          }
          var valuesBase = this.values;
          var outputBase = outputTensor;
          var elementShape = outputShape.slice();
          elementShape = elementShape.slice(raggedRank + 1);
          var valueElementSize = tfjsCore.util.sizeFromShape(elementShape);
          var outputIndexSize = outputIndex.length;
          var defaultValue = this.defaultValue;
          if (defaultValue.length !== valueElementSize && defaultValue.length !== 1) {
            var srcShape_1 = this.defaultValueShape;
            tfjsCore.tidy(function() {
              var defaultValueTensor = tfjsCore.reshape(defaultValue, srcShape_1);
              var bCastDefault = tfjsCore.broadcastTo(defaultValueTensor, elementShape);
              defaultValue = bCastDefault.dataSync();
            });
          }
          var srcStart = 0;
          var dstStart = 0;
          var dstEnd = 0;
          for (var srcI = 0; srcI <= outputIndexSize; ++srcI) {
            var dstI = srcI < outputIndexSize ? outputIndex[srcI] : -1;
            if (dstI === dstEnd) {
              ++dstEnd;
              continue;
            }
            if (dstStart < dstEnd) {
              var src = valuesBase.subarray(srcStart * valueElementSize);
              var dst = outputBase.subarray(dstStart * valueElementSize);
              var nVals = (dstEnd - dstStart) * valueElementSize;
              copyArray(dst, src, nVals);
            }
            if (srcI >= outputIndexSize) {
              var outputSize = outputTensor.length;
              dstI = Math.floor(outputSize / valueElementSize);
            }
            if (dstI > dstEnd) {
              if (this.defaultValue.length === 1) {
                outputBase.subarray(dstEnd * valueElementSize, dstI * valueElementSize).fill(this.defaultValue[0]);
                dstEnd = dstI;
              } else {
                while (dstI > dstEnd) {
                  var dst = outputBase.slice(dstEnd * valueElementSize);
                  copyArray(dst, defaultValue, valueElementSize);
                  ++dstEnd;
                }
              }
            }
            if (dstI < 0) {
              srcStart = srcI + 1;
              dstStart = dstEnd;
            } else {
              srcStart = srcI;
              dstStart = dstEnd;
              dstEnd = dstStart + 1;
            }
          }
        };
        return RaggedTensorToTensorOp2;
      }()
    );
    function copyArray(dst, src, size) {
      for (var i = 0; i < size; i++) {
        dst[i] = src[i];
      }
    }
    function makeShape(shape, isPartial) {
      var e_12, _a2;
      var out = [];
      try {
        for (var shape_1 = __values(shape), shape_1_1 = shape_1.next(); !shape_1_1.done; shape_1_1 = shape_1.next()) {
          var dim = shape_1_1.value;
          if (dim < 0) {
            if (!isPartial) {
              throw new Error("Dimension ".concat(dim, " must be >= 0"));
            }
            if (dim < -1) {
              throw new Error("Dimension ".concat(dim, " must be >= -1"));
            }
            dim = -1;
          }
          out.push(dim);
        }
      } catch (e_1_1) {
        e_12 = { error: e_1_1 };
      } finally {
        try {
          if (shape_1_1 && !shape_1_1.done && (_a2 = shape_1.return)) _a2.call(shape_1);
        } finally {
          if (e_12) throw e_12.error;
        }
      }
      return out;
    }
    function raggedTensorToTensorImpl(shape, shapesShape, values, valuesShape, valuesDType, defaultValue, defaultValueShape, rowPartitionValues, rowPartitionValuesShapes, rowPartitionTypes) {
      return new RaggedTensorToTensorOp(shape, shapesShape, values, valuesShape, valuesDType, defaultValue, defaultValueShape, rowPartitionValues, rowPartitionValuesShapes, rowPartitionTypes).compute();
    }
    function rangeImpl(start, stop, step2, dtype) {
      var sameStartStop = start === stop;
      var increasingRangeNegativeStep = start < stop && step2 < 0;
      var decreasingRangePositiveStep = stop < start && step2 > 1;
      if (sameStartStop || increasingRangeNegativeStep || decreasingRangePositiveStep) {
        return tfjsCore.util.makeZerosTypedArray(0, dtype);
      }
      var numElements = Math.abs(Math.ceil((stop - start) / step2));
      var values = tfjsCore.util.makeZerosTypedArray(numElements, dtype);
      if (stop < start && step2 === 1) {
        step2 = -1;
      }
      values[0] = start;
      for (var i = 1; i < values.length; i++) {
        values[i] = values[i - 1] + step2;
      }
      return values;
    }
    var rsqrtImpl = createSimpleUnaryImpl(function(xi) {
      return 1 / Math.sqrt(xi);
    });
    var rsqrt = unaryKernelFuncFromImpl(tfjsCore.Rsqrt, rsqrtImpl);
    var rsqrtConfig = {
      kernelName: tfjsCore.Rsqrt,
      backendName: "cpu",
      kernelFunc: rsqrt
    };
    function scatterImpl(indices, updates, shape, outputSize, sliceSize, numUpdates, sliceRank, strides, defaultValue, sumDupeIndices) {
      var flattenShape = [outputSize / sliceSize, sliceSize];
      var indicesData = indices.values;
      var updatesData = updates.values;
      if (outputSize === 0) {
        return tfjsCore.buffer(shape, updates.dtype);
      }
      var outBuf = defaultValue instanceof tfjsCore.TensorBuffer ? defaultValue : tfjsCore.buffer(flattenShape, updates.dtype);
      if (typeof defaultValue === "string") {
        outBuf.values.fill(defaultValue);
      } else if (typeof defaultValue === "number") {
        outBuf.values.fill(defaultValue);
      } else if (typeof defaultValue === "boolean") {
        outBuf.values.fill(+defaultValue);
      }
      for (var i = 0; i < numUpdates; i++) {
        var index = [];
        var flattenIndex = 0;
        for (var j = 0; j < sliceRank; j++) {
          var dim = indicesData[i * sliceRank + j];
          index.push(dim);
          flattenIndex += dim * strides[j];
        }
        if (flattenIndex < 0 || flattenIndex >= outputSize / sliceSize) {
          throw new Error("Invalid indices: ".concat(index, " does not index into ").concat(shape));
        }
        for (var k = 0; k < sliceSize; k++) {
          if (sumDupeIndices) {
            outBuf.values[flattenIndex * sliceSize + k] += updatesData[i * sliceSize + k];
          } else {
            outBuf.values[flattenIndex * sliceSize + k] = updates.rank === 0 ? updatesData[0] : updatesData[i * sliceSize + k];
          }
        }
      }
      return outBuf;
    }
    var sigmoidImpl = createSimpleUnaryImpl(function(xi) {
      return 1 / (1 + Math.exp(-xi));
    });
    var sigmoid = unaryKernelFunc(tfjsCore.Sigmoid, function(xi) {
      return 1 / (1 + Math.exp(-xi));
    });
    var sigmoidConfig = {
      kernelName: tfjsCore.Sigmoid,
      backendName: "cpu",
      kernelFunc: sigmoid
    };
    function sliceImpl(vals, begin, size, shape, dtype) {
      var isContinous = tfjsCore.slice_util.isSliceContinous(shape, begin, size);
      var length = tfjsCore.util.sizeFromShape(size);
      var xStrides = tfjsCore.util.computeStrides(shape);
      if (isContinous) {
        var flatOffset = tfjsCore.slice_util.computeFlatOffset(begin, xStrides);
        if (dtype === "string") {
          return vals.slice(flatOffset, flatOffset + length);
        }
        return vals.subarray(flatOffset, flatOffset + length);
      }
      var decodedData = dtype === "string" ? tfjsCore.backend_util.fromUint8ToStringArray(vals) : vals;
      var inBuf = tfjsCore.buffer(shape, dtype, decodedData);
      var outBuf = tfjsCore.buffer(size, dtype);
      for (var i = 0; i < outBuf.size; ++i) {
        var outLoc = outBuf.indexToLoc(i);
        var inLoc = outLoc.map(function(idx, j) {
          return idx + begin[j];
        });
        outBuf.set.apply(outBuf, __spreadArray([inBuf.get.apply(inBuf, __spreadArray([], __read(inLoc), false))], __read(outLoc), false));
      }
      if (dtype === "string") {
        return tfjsCore.backend_util.fromStringArrayToUint8(outBuf.values);
      }
      return outBuf.values;
    }
    function slice(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var begin = attrs.begin, size = attrs.size;
      assertNotComplex(x, "slice");
      var _a2 = __read(tfjsCore.slice_util.parseSliceParams(x, begin, size), 2), $begin = _a2[0], $size = _a2[1];
      tfjsCore.slice_util.assertParamsValid(x, $begin, $size);
      var vals = backend.data.get(x.dataId).values;
      var outVals = sliceImpl(vals, $begin, $size, x.shape, x.dtype);
      return backend.makeTensorInfo($size, x.dtype, outVals);
    }
    var sliceConfig = {
      kernelName: tfjsCore.Slice,
      backendName: "cpu",
      kernelFunc: slice
    };
    function sparseFillEmptyRowsImpl(indices, indicesShape, indicesDType, values, valuesDType, denseShape, defaultValue) {
      var indicesCount = indicesShape[0];
      var denseRows = denseShape[0];
      var emptyRowIndicator = new Array(denseRows);
      var reverseIndexMap = new Array(indicesCount);
      var rank = indicesShape[1];
      if (denseRows === 0) {
        if (indicesCount !== 0) {
          throw new Error(tfjsCore.backend_util.getSparseFillEmptyRowsIndicesDenseShapeMismatch(indicesCount));
        }
        var outputIndices = tfjsCore.util.getArrayFromDType(indicesDType, 0);
        var outputValues = tfjsCore.util.getArrayFromDType(valuesDType, 0);
        return [
          outputIndices,
          [0, rank],
          outputValues,
          emptyRowIndicator,
          reverseIndexMap
        ];
      }
      var rowsAreOrdered = true;
      var lastIndicesRow = 0;
      var csrOffset = new Array(denseRows).fill(0);
      for (var i = 0; i < indicesCount; ++i) {
        var row = indices[i * rank];
        if (row < 0) {
          throw new Error(tfjsCore.backend_util.getSparseFillEmptyRowsNegativeIndexErrorMessage(i, row));
        }
        if (row >= denseRows) {
          throw new Error(tfjsCore.backend_util.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(i, row, denseRows));
        }
        ++csrOffset[row];
        rowsAreOrdered = rowsAreOrdered && row >= lastIndicesRow;
        lastIndicesRow = row;
      }
      var allRowsFull = true;
      for (var row = 0; row < denseRows; ++row) {
        var rowEmpty = csrOffset[row] === 0;
        emptyRowIndicator[row] = rowEmpty;
        allRowsFull = allRowsFull && !rowEmpty;
        csrOffset[row] = Math.max(csrOffset[row], 1);
        if (row > 0) {
          csrOffset[row] += csrOffset[row - 1];
        }
      }
      if (allRowsFull && rowsAreOrdered) {
        var outputIndices = indices;
        var outputValues = values;
        for (var i = 0; i < indicesCount; ++i) {
          reverseIndexMap[i] = i;
        }
        return [
          outputIndices,
          [indicesCount, rank],
          outputValues,
          emptyRowIndicator,
          reverseIndexMap
        ];
      } else {
        var fullIndicesCount = csrOffset[denseRows - 1];
        var outputIndices = tfjsCore.util.getArrayFromDType(indicesDType, fullIndicesCount * rank);
        var outputValues = tfjsCore.util.getArrayFromDType(valuesDType, fullIndicesCount);
        var filledCount = new Array(denseRows).fill(0);
        for (var i = 0; i < indicesCount; ++i) {
          var row = indices[i * rank];
          var offset = filledCount[row];
          var outputI = (row === 0 ? 0 : csrOffset[row - 1]) + offset;
          filledCount[row]++;
          for (var j = 0; j < rank; ++j) {
            outputIndices[outputI * rank + j] = indices[i * rank + j];
          }
          outputValues[outputI] = values[i];
          reverseIndexMap[i] = outputI;
        }
        for (var row = 0; row < denseRows; ++row) {
          var rowCount = filledCount[row];
          if (rowCount === 0) {
            var startingIndex = row === 0 ? 0 : csrOffset[row - 1];
            outputIndices[startingIndex * rank + 0] = row;
            for (var col = 1; col < rank; ++col) {
              outputIndices[startingIndex * rank + col] = 0;
            }
            outputValues[startingIndex] = defaultValue;
          }
        }
        return [
          outputIndices,
          [fullIndicesCount, rank],
          outputValues,
          emptyRowIndicator,
          reverseIndexMap
        ];
      }
    }
    function sparseReshapeImpl(inputIndices, inputIndicesShape, inputDType, inputShape, targetShape) {
      var denseSize = tfjsCore.util.sizeFromShape(inputShape);
      var nnz = inputIndicesShape[0];
      var outputRank = targetShape.length;
      var outputShape = [];
      var product = 1;
      var unknownIndex = -1;
      for (var d = 0; d < outputRank; ++d) {
        var size = targetShape[d];
        if (size === -1) {
          if (unknownIndex !== -1) {
            throw new Error(tfjsCore.backend_util.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(unknownIndex, d));
          }
          unknownIndex = d;
          outputShape.push(1);
        } else {
          if (size < 0) {
            throw new Error(tfjsCore.backend_util.getSparseReshapeNegativeOutputDimErrorMessage(d, size));
          }
          product *= size;
          outputShape.push(size);
        }
      }
      if (unknownIndex !== -1) {
        if (product <= 0) {
          throw new Error(tfjsCore.backend_util.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());
        }
        var missing = Math.trunc(denseSize / product);
        if (product * missing !== denseSize) {
          throw new Error(tfjsCore.backend_util.getSparseReshapeInputOutputMultipleErrorMessage(inputShape, outputShape));
        }
        outputShape[unknownIndex] = missing;
      }
      var outputSize = tfjsCore.util.sizeFromShape(outputShape);
      if (outputSize !== denseSize) {
        throw new Error(tfjsCore.backend_util.getSparseReshapeInputOutputMismatchErrorMessage(inputShape, outputShape));
      }
      var inputRank = inputShape.length;
      var inputStrides = [];
      if (inputRank > 0) {
        inputStrides[inputRank - 1] = 1;
        for (var d = inputRank - 2; d >= 0; --d) {
          inputStrides[d] = inputStrides[d + 1] * inputShape[d + 1];
        }
      }
      var outputStrides = [];
      if (outputRank > 0) {
        outputStrides[outputRank - 1] = 1;
        for (var d = outputRank - 2; d >= 0; --d) {
          outputStrides[d] = outputStrides[d + 1] * outputShape[d + 1];
        }
      }
      var newIndices = tfjsCore.util.getArrayFromDType(inputDType, nnz * outputRank);
      for (var i = 0; i < nnz; ++i) {
        var id = 0;
        for (var j = 0; j < inputRank; ++j) {
          id += inputIndices[i * inputRank + j] * inputStrides[j];
        }
        for (var j = 0; j < outputRank; ++j) {
          newIndices[i * outputRank + j] = Math.trunc(id / outputStrides[j]);
          id %= outputStrides[j];
        }
      }
      return [newIndices, [nnz, outputRank], outputShape];
    }
    function sparseSegmentReductionImpl(input, inputShape, inputDType, indices, segmentIds, isMean, defaultValue) {
      if (isMean === void 0) {
        isMean = false;
      }
      if (defaultValue === void 0) {
        defaultValue = 0;
      }
      var numIndices = indices.length;
      var inputFlat = [inputShape[0], input.length / inputShape[0]];
      var numCol = inputFlat[1];
      var lastSegmentIdPlusOne = numIndices > 0 ? segmentIds[numIndices - 1] + 1 : 0;
      var outputRows = lastSegmentIdPlusOne;
      if (outputRows < 0) {
        throw new Error(tfjsCore.backend_util.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());
      }
      var outputShape = inputShape.slice();
      outputShape[0] = outputRows;
      var outputLength = outputShape.reduce(function(product, value) {
        return product * value;
      }, 1);
      var output = tfjsCore.util.getArrayFromDType(inputDType, outputLength);
      if (numIndices === 0) {
        if (outputRows > 0) {
          output.fill(defaultValue);
        }
        return [output, outputShape];
      }
      if (outputRows <= 0) {
        throw new Error(tfjsCore.backend_util.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());
      }
      var start = 0, end = 1;
      var uninitializedIndex = 0;
      var outIndex = segmentIds[start];
      while (true) {
        var nextIndex = 0;
        if (end < numIndices) {
          nextIndex = segmentIds[end];
          if (outIndex === nextIndex) {
            ++end;
            continue;
          }
          if (outIndex >= nextIndex) {
            throw new Error(tfjsCore.backend_util.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage());
          }
        }
        if (outIndex < 0 || outIndex >= outputRows) {
          throw new Error(tfjsCore.backend_util.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(outIndex, outputRows));
        }
        if (outIndex > uninitializedIndex) {
          output.fill(defaultValue, uninitializedIndex * numCol, outIndex * numCol);
        }
        for (var i = start; i < end; ++i) {
          var index = indices[i];
          if (index < 0 || index >= inputFlat[0]) {
            throw new Error(tfjsCore.backend_util.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(i, indices[i], inputFlat[0]));
          }
          for (var j = 0; j < numCol; j++) {
            output[outIndex * numCol + j] += input[index * numCol + j];
          }
        }
        if (isMean) {
          for (var j = 0; j < numCol; j++) {
            output[outIndex * numCol + j] /= end - start;
          }
        }
        start = end;
        ++end;
        uninitializedIndex = outIndex + 1;
        outIndex = nextIndex;
        if (end > numIndices) {
          break;
        }
      }
      if (uninitializedIndex < outputRows) {
        output.fill(defaultValue, uninitializedIndex * numCol, outputRows * numCol);
      }
      return [output, outputShape];
    }
    var sqrtImpl = createSimpleUnaryImpl(function(xi) {
      return Math.sqrt(xi);
    });
    var sqrt = unaryKernelFunc(tfjsCore.Sqrt, function(xi) {
      return Math.sqrt(xi);
    });
    var sqrtConfig = {
      kernelName: tfjsCore.Sqrt,
      backendName: "cpu",
      kernelFunc: sqrt
    };
    var squaredDifferenceImpl = createSimpleBinaryKernelImpl(function(a, b) {
      var diff = a - b;
      return diff * diff;
    });
    var squaredDifference = binaryKernelFunc(tfjsCore.SquaredDifference, squaredDifferenceImpl);
    var squaredDifferenceConfig = {
      kernelName: tfjsCore.SquaredDifference,
      backendName: "cpu",
      kernelFunc: squaredDifference
    };
    var staticRegexReplaceImpl = createSimpleUnaryImpl(function(x, attrs) {
      var pattern = attrs.pattern, replaceGlobal = attrs.replaceGlobal, rewrite = attrs.rewrite;
      return x.replace(new RegExp(pattern, replaceGlobal ? "g" : ""), rewrite);
    });
    var staticRegexReplace = unaryKernelFuncFromImpl(tfjsCore.StaticRegexReplace, staticRegexReplaceImpl);
    var staticRegexReplaceConfig = {
      kernelName: tfjsCore.StaticRegexReplace,
      backendName: "cpu",
      kernelFunc: staticRegexReplace
    };
    function stridedSliceImpl(outShape, xBuf, strides, begin) {
      var outBuf = tfjsCore.buffer(outShape, xBuf.dtype);
      for (var i = 0; i < outBuf.size; i++) {
        var loc = outBuf.indexToLoc(i);
        var newLoc = new Array(loc.length);
        for (var j = 0; j < newLoc.length; j++) {
          newLoc[j] = loc[j] * strides[j] + begin[j];
        }
        outBuf.set.apply(outBuf, __spreadArray([xBuf.get.apply(xBuf, __spreadArray([], __read(newLoc), false))], __read(loc), false));
      }
      return outBuf;
    }
    var StringNGramsOp = (
      /** @class */
      function() {
        function StringNGramsOp2(separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences) {
          this.separator = tfjsCore.util.encodeString(separator);
          this.nGramWidths = nGramWidths;
          this.leftPad = tfjsCore.util.encodeString(leftPad);
          this.rightPad = tfjsCore.util.encodeString(rightPad);
          this.padWidth = padWidth;
          this.preserveShort = preserveShortSequences;
        }
        StringNGramsOp2.prototype.getPadWidth = function(nGramWidth) {
          return Math.min(this.padWidth < 0 ? nGramWidth - 1 : this.padWidth, nGramWidth - 1);
        };
        StringNGramsOp2.prototype.getNumNGrams = function(length, nGramWidth) {
          var padWidth = this.getPadWidth(nGramWidth);
          return Math.max(0, length + 2 * padWidth - nGramWidth + 1);
        };
        StringNGramsOp2.prototype.createNGrams = function(data, splitIndex, output, outputStartIndex, numNGrams, nGramWidth) {
          var _loop_1 = function(nGramIndex2) {
            var padWidth = this_1.getPadWidth(nGramWidth);
            var leftPadding = Math.max(0, padWidth - nGramIndex2);
            var rightPadding = Math.max(0, padWidth - (numNGrams - (nGramIndex2 + 1)));
            var numTokens = nGramWidth - (leftPadding + rightPadding);
            var dataStartIndex = splitIndex + (leftPadding > 0 ? 0 : nGramIndex2 - padWidth);
            var nGramSize = 0;
            nGramSize += leftPadding * this_1.leftPad.length;
            for (var n = 0; n < numTokens; ++n) {
              nGramSize += data[dataStartIndex + n].length;
            }
            nGramSize += rightPadding * this_1.rightPad.length;
            var numSeparators = leftPadding + rightPadding + numTokens - 1;
            nGramSize += numSeparators * this_1.separator.length;
            output[outputStartIndex + nGramIndex2] = new Uint8Array(nGramSize);
            var nGram = output[outputStartIndex + nGramIndex2];
            var nextNGramIndex = 0;
            var appendToNGram = function(str) {
              return str.forEach(function(value) {
                return nGram[nextNGramIndex++] = value;
              });
            };
            for (var n = 0; n < leftPadding; ++n) {
              appendToNGram(this_1.leftPad);
              appendToNGram(this_1.separator);
            }
            for (var n = 0; n < numTokens - 1; ++n) {
              appendToNGram(data[dataStartIndex + n]);
              appendToNGram(this_1.separator);
            }
            if (numTokens > 0) {
              appendToNGram(data[dataStartIndex + numTokens - 1]);
              for (var n = 0; n < rightPadding; ++n) {
                appendToNGram(this_1.separator);
                appendToNGram(this_1.rightPad);
              }
            } else {
              for (var n = 0; n < rightPadding - 1; ++n) {
                appendToNGram(this_1.rightPad);
                appendToNGram(this_1.separator);
              }
              appendToNGram(this_1.rightPad);
            }
          };
          var this_1 = this;
          for (var nGramIndex = 0; nGramIndex < numNGrams; ++nGramIndex) {
            _loop_1(nGramIndex);
          }
        };
        StringNGramsOp2.prototype.compute = function(data, splits) {
          var _this = this;
          var inputDataSize = data.length;
          var splitsSize = splits.length;
          if (splitsSize > 0) {
            var prevSplit = splits[0];
            if (prevSplit !== 0) {
              throw new Error("First split value must be 0, got ".concat(prevSplit));
            }
            for (var i = 1; i < splitsSize; ++i) {
              var validSplits = splits[i] >= prevSplit;
              validSplits = validSplits && splits[i] <= inputDataSize;
              if (!validSplits) {
                throw new Error("Invalid split value ".concat(splits[i], ", must be in [").concat(prevSplit, ", ").concat(inputDataSize, "]"));
              }
              prevSplit = splits[i];
            }
            if (prevSplit !== inputDataSize) {
              throw new Error("Last split value must be data size. Expected ".concat(inputDataSize, ", got ").concat(prevSplit));
            }
          }
          var numBatchItems = splitsSize - 1;
          var nGramsSplits = tfjsCore.util.getArrayFromDType("int32", splitsSize);
          if (inputDataSize === 0 || splitsSize === 0) {
            var empty = new Array(inputDataSize);
            for (var i = 0; i <= numBatchItems; ++i) {
              nGramsSplits[i] = 0;
            }
            return [empty, nGramsSplits];
          }
          nGramsSplits[0] = 0;
          var _loop_2 = function(i2) {
            var length = splits[i2] - splits[i2 - 1];
            var numNGrams = 0;
            this_2.nGramWidths.forEach(function(nGramWidth) {
              numNGrams += _this.getNumNGrams(length, nGramWidth);
            });
            if (this_2.preserveShort && length > 0 && numNGrams === 0) {
              numNGrams = 1;
            }
            nGramsSplits[i2] = nGramsSplits[i2 - 1] + numNGrams;
          };
          var this_2 = this;
          for (var i = 1; i <= numBatchItems; ++i) {
            _loop_2(i);
          }
          var nGrams = new Array(nGramsSplits[numBatchItems]);
          var _loop_3 = function(i2) {
            var splitIndex = splits[i2];
            var outputStartIdx = nGramsSplits[i2];
            this_3.nGramWidths.forEach(function(nGramWidth2) {
              var length = splits[i2 + 1] - splits[i2];
              var numNGrams2 = _this.getNumNGrams(length, nGramWidth2);
              _this.createNGrams(data, splitIndex, nGrams, outputStartIdx, numNGrams2, nGramWidth2);
              outputStartIdx += numNGrams2;
            });
            if (this_3.preserveShort && outputStartIdx === nGramsSplits[i2]) {
              var dataLength = splits[i2 + 1] - splits[i2];
              if (dataLength === 0) {
                return "continue";
              }
              var nGramWidth = dataLength + 2 * this_3.padWidth;
              var numNGrams = 1;
              this_3.createNGrams(data, splitIndex, nGrams, outputStartIdx, numNGrams, nGramWidth);
            }
          };
          var this_3 = this;
          for (var i = 0; i < numBatchItems; ++i) {
            _loop_3(i);
          }
          return [nGrams, nGramsSplits];
        };
        return StringNGramsOp2;
      }()
    );
    function stringNGramsImpl(data, dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences) {
      return new StringNGramsOp(separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences).compute(data, dataSplits);
    }
    function split(str, delimiters, skipEmpty, result) {
      if (!str.length) {
        return;
      }
      if (delimiters.length === 0) {
        for (var i = 0; i < str.length; ++i) {
          result.push(str.subarray(i, i + 1));
        }
        return;
      }
      if (delimiters.length === 1) {
        var delimiter = delimiters[0];
        var f = str.indexOf(delimiter);
        while (f !== -1) {
          var token = str.subarray(0, f);
          if (!skipEmpty || token.length !== 0) {
            result.push(token);
          }
          str = str.subarray(f + 1);
          f = str.indexOf(delimiter);
        }
        if (!skipEmpty || str.length !== 0) {
          result.push(str);
        }
        return;
      }
      var tokenStart = 0;
      for (var i = 0; i < str.length + 1; i++) {
        if (i === str.length || delimiters.indexOf(str[i]) !== -1) {
          var token = str.subarray(tokenStart, i);
          if (!skipEmpty || token.length !== 0) {
            result.push(token);
          }
          tokenStart = i + 1;
        }
      }
    }
    function stringSplitImpl(input, delimiter, skipEmpty) {
      var batchSize = input.length;
      var tokens = [];
      var outputSize = 0;
      var maxNumEntries = 0;
      var numIndices = new Array(batchSize);
      for (var i = 0; i < batchSize; ++i) {
        var prevTokensLength = tokens.length;
        split(input[i], delimiter, skipEmpty, tokens);
        var nEntries = tokens.length - prevTokensLength;
        numIndices[i] = nEntries;
        outputSize += nEntries;
        maxNumEntries = Math.max(maxNumEntries, nEntries);
      }
      var indices = tfjsCore.util.getArrayFromDType("int32", outputSize * 2);
      var values = new Array(outputSize);
      var shape = [batchSize, maxNumEntries];
      var c = 0;
      for (var i = 0; i < batchSize; ++i) {
        for (var j = 0; j < numIndices[i]; ++j) {
          indices[c * 2] = i;
          indices[c * 2 + 1] = j;
          values[c] = tokens[c];
          ++c;
        }
      }
      return [indices, values, shape];
    }
    function stringToHashBucketFastImpl(input, numBuckets) {
      var output = tfjsCore.util.getArrayFromDType("int32", input.length);
      for (var i = 0; i < input.length; ++i) {
        output[i] = tfjsCore.util.fingerPrint64(input[i]).modulo(numBuckets).getLowBitsUnsigned();
      }
      return output;
    }
    var subImpl = createSimpleBinaryKernelImpl(function(aValue, bValue) {
      return aValue - bValue;
    });
    var subComplexImpl = createComplexBinaryKernelImpl(function(aReal, aImag, bReal, bImag) {
      return { real: aReal - bReal, imag: aImag - bImag };
    });
    var sub = binaryKernelFunc(tfjsCore.Sub, subImpl, subComplexImpl);
    var subConfig = {
      kernelName: tfjsCore.Sub,
      backendName: "cpu",
      kernelFunc: sub
    };
    function tileImpl(xBuf, reps) {
      var newShape = new Array(xBuf.rank);
      for (var i = 0; i < newShape.length; i++) {
        newShape[i] = xBuf.shape[i] * reps[i];
      }
      var result = tfjsCore.buffer(newShape, xBuf.dtype);
      for (var i = 0; i < result.values.length; ++i) {
        var newLoc = result.indexToLoc(i);
        var originalLoc = new Array(xBuf.rank);
        for (var j = 0; j < originalLoc.length; j++) {
          originalLoc[j] = newLoc[j] % xBuf.shape[j];
        }
        var originalIndex = xBuf.locToIndex(originalLoc);
        result.values[i] = xBuf.values[originalIndex];
      }
      return result;
    }
    var comparePair = function(a, b) {
      var valueDiff = b.value - a.value;
      return valueDiff === 0 ? a.index - b.index : valueDiff;
    };
    function select$1(array, k, left, right) {
      if (left === void 0) {
        left = 0;
      }
      if (right === void 0) {
        right = array.length - 1;
      }
      while (right > left) {
        if (right - left > 600) {
          var n = right - left + 1;
          var i_1 = k - left + 1;
          var z = Math.log(n);
          var s = 0.5 * Math.exp(2 * z / 3);
          var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * Math.sign(i_1 - n / 2);
          var newLeft = Math.max(left, Math.floor(k - i_1 * s / n + sd));
          var newRight = Math.min(right, Math.floor(k + (n - i_1) * s / n + sd));
          select$1(array, k, newLeft, newRight);
        }
        var t = array[k];
        var i = left;
        var j = right;
        tfjsCore.util.swap(array, left, k);
        if (comparePair(array[right], t) > 0) {
          tfjsCore.util.swap(array, left, right);
        }
        while (i < j) {
          tfjsCore.util.swap(array, i, j);
          i++;
          j--;
          while (comparePair(array[i], t) < 0) {
            i = i + 1;
          }
          while (comparePair(array[j], t) > 0) {
            j = j - 1;
          }
        }
        if (comparePair(array[left], t) === 0) {
          tfjsCore.util.swap(array, left, j);
        } else {
          j = j + 1;
          tfjsCore.util.swap(array, j, right);
        }
        if (j <= k) {
          left = j + 1;
        }
        if (k <= j) {
          right = j - 1;
        }
      }
    }
    function topKImpl(x, xShape, xDtype, k, sorted) {
      var lastDim = xShape[xShape.length - 1];
      var _a2 = __read([x.length / lastDim, lastDim], 2), batch = _a2[0], size = _a2[1];
      var allTopKVals = tfjsCore.util.getTypedArrayFromDType(xDtype, batch * k);
      var allTopKIndices = tfjsCore.util.getTypedArrayFromDType("int32", batch * k);
      var _loop_1 = function(b2) {
        var offset = b2 * size;
        var vals = x.subarray(offset, offset + size);
        var valAndInd = new Array(vals.length);
        vals.forEach(function(value, index) {
          return valAndInd[index] = { value, index };
        });
        if (k < valAndInd.length) {
          select$1(valAndInd, k);
          valAndInd = valAndInd.slice(0, k);
        }
        if (sorted) {
          valAndInd.sort(comparePair);
        }
        var outOffset = b2 * k;
        var topKVals = allTopKVals.subarray(outOffset, outOffset + k);
        var topKIndices = allTopKIndices.subarray(outOffset, outOffset + k);
        for (var i = 0; i < k; i++) {
          topKVals[i] = valAndInd[i].value;
          topKIndices[i] = valAndInd[i].index;
        }
      };
      for (var b = 0; b < batch; b++) {
        _loop_1(b);
      }
      var outputShape = xShape.slice();
      outputShape[outputShape.length - 1] = k;
      return [
        tfjsCore.buffer(outputShape, xDtype, allTopKVals),
        tfjsCore.buffer(outputShape, "int32", allTopKIndices)
      ];
    }
    function uniqueImpl(values, axis, shape, dtype) {
      var $axis = tfjsCore.util.parseAxisParam(axis, shape)[0];
      var newShape = [1, shape[0], 1];
      for (var i = 0; i < $axis; i++) {
        newShape[0] *= shape[i];
      }
      newShape[1] = shape[$axis];
      for (var i = $axis + 1; i < shape.length; i++) {
        newShape[2] *= shape[i];
      }
      var uniqueElements = /* @__PURE__ */ new Map();
      var indices = new Int32Array(shape[$axis]);
      var inputBuffer = new tfjsCore.TensorBuffer(newShape, dtype, values);
      var uniqueIndices = [];
      var is1DTensor = newShape[0] === 1 && newShape[2] === 1;
      for (var i = 0; i < shape[$axis]; i++) {
        var element = void 0;
        if (is1DTensor) {
          element = values[i].toString();
        } else {
          var axisValues = [];
          for (var m = 0; m < newShape[0]; m++) {
            for (var n = 0; n < newShape[2]; n++) {
              axisValues.push(inputBuffer.get(m, i, n));
            }
          }
          element = axisValues.join(",");
        }
        var existingIndex = uniqueElements.get(element);
        if (existingIndex != null) {
          indices[i] = existingIndex;
        } else {
          var uniqueIndex = uniqueElements.size;
          uniqueElements.set(element, uniqueIndex);
          indices[i] = uniqueIndex;
          uniqueIndices.push(i);
        }
      }
      var outputTmpShape = newShape.slice();
      outputTmpShape[1] = uniqueElements.size;
      var outputBuffer = new tfjsCore.TensorBuffer(outputTmpShape, dtype);
      uniqueIndices.forEach(function(uniqueElementIndex, i2) {
        for (var m2 = 0; m2 < newShape[0]; m2++) {
          for (var n2 = 0; n2 < newShape[2]; n2++) {
            outputBuffer.set(inputBuffer.get(m2, uniqueElementIndex, n2), m2, i2, n2);
          }
        }
      });
      var outputShape = shape.slice();
      outputShape[$axis] = outputTmpShape[1];
      return {
        outputValues: outputBuffer.values,
        outputShape,
        indices
      };
    }
    var shared = {
      __proto__: null,
      addImpl,
      bincountImpl,
      bincountReduceImpl,
      bitwiseAndImpl,
      castImpl,
      ceilImpl,
      concatImpl,
      equalImpl,
      expImpl,
      expm1Impl,
      floorDivImpl,
      floorImpl,
      gatherNdImpl,
      gatherV2Impl,
      greaterEqualImpl,
      greaterImpl,
      lessEqualImpl,
      lessImpl,
      linSpaceImpl,
      logImpl,
      maxImpl,
      maximumImpl,
      minimumImpl,
      multiplyImpl,
      negImpl,
      notEqualImpl,
      prodImpl,
      raggedGatherImpl,
      raggedRangeImpl,
      raggedTensorToTensorImpl,
      rangeImpl,
      rsqrtImpl,
      scatterImpl,
      sigmoidImpl,
      simpleAbsImpl,
      sliceImpl,
      sparseFillEmptyRowsImpl,
      sparseReshapeImpl,
      sparseSegmentReductionImpl,
      sqrtImpl,
      squaredDifferenceImpl,
      staticRegexReplaceImpl,
      stridedSliceImpl,
      stringNGramsImpl,
      stringSplitImpl,
      stringToHashBucketFastImpl,
      subImpl,
      tileImpl,
      topKImpl,
      transposeImpl,
      uniqueImpl
    };
    var version = "4.22.0";
    tfjsCore.registerBackend(
      "cpu",
      function() {
        return new MathBackendCPU();
      },
      1
      /* priority */
    );
    var elu = unaryKernelFunc(tfjsCore.Elu, function(xi) {
      return xi >= 0 ? xi : Math.exp(xi) - 1;
    });
    var eluConfig = {
      kernelName: tfjsCore.Elu,
      backendName: "cpu",
      kernelFunc: elu
    };
    function leakyRelu(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var alpha = attrs.alpha;
      assertNotComplex([x], "leakyRelu");
      var xSize = tfjsCore.util.sizeFromShape(x.shape);
      var xVals = backend.data.get(x.dataId).values;
      var outVals = tfjsCore.util.getTypedArrayFromDType("float32", xSize);
      for (var i = 0; i < xVals.length; i++) {
        outVals[i] = xVals[i] < 0 ? alpha * xVals[i] : xVals[i];
      }
      return backend.makeTensorInfo(x.shape, "float32", outVals);
    }
    var leakyReluConfig = {
      kernelName: tfjsCore.LeakyRelu,
      backendName: "cpu",
      kernelFunc: leakyRelu
    };
    var preluImpl = createSimpleBinaryKernelImpl(function(xValue, aValue) {
      return xValue < 0 ? aValue * xValue : xValue;
    });
    function prelu(args) {
      var inputs = args.inputs, backend = args.backend;
      var x = inputs.x, alpha = inputs.alpha;
      assertNotComplex([x, alpha], "prelu");
      var aVals = backend.data.get(x.dataId).values;
      var bVals = backend.data.get(alpha.dataId).values;
      var _a2 = __read(preluImpl(x.shape, alpha.shape, aVals, bVals, "float32"), 2), resultData = _a2[0], resultShape = _a2[1];
      return backend.makeTensorInfo(resultShape, "float32", resultData);
    }
    var preluConfig = {
      kernelName: tfjsCore.Prelu,
      backendName: "cpu",
      kernelFunc: prelu
    };
    var relu = unaryKernelFunc(tfjsCore.Relu, function(xi) {
      return Math.max(0, xi);
    });
    var reluConfig = {
      kernelName: tfjsCore.Relu,
      backendName: "cpu",
      kernelFunc: relu
    };
    var relu6 = unaryKernelFunc(tfjsCore.Relu6, function(xi) {
      return Math.min(Math.max(0, xi), 6);
    });
    var relu6Config = {
      kernelName: tfjsCore.Relu6,
      backendName: "cpu",
      kernelFunc: relu6
    };
    function applyActivation(backend, x, activation, preluActivationWeights, leakyreluAlpha) {
      if (activation === "linear") {
        return identity({ inputs: { x }, backend });
      } else if (activation === "relu") {
        return relu({ inputs: { x }, backend });
      } else if (activation === "elu") {
        return elu({ inputs: { x }, backend });
      } else if (activation === "relu6") {
        return relu6({ inputs: { x }, backend });
      } else if (activation === "prelu") {
        return prelu({ inputs: { x, alpha: preluActivationWeights }, backend });
      } else if (activation === "leakyrelu") {
        return leakyRelu({ inputs: { x }, backend, attrs: { alpha: leakyreluAlpha } });
      } else if (activation === "sigmoid") {
        return sigmoid({ inputs: { x }, backend });
      }
      throw new Error("Activation ".concat(activation, " has not been implemented for the CPU backend."));
    }
    function reshape(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var shape = attrs.shape;
      var xSize = tfjsCore.util.sizeFromShape(x.shape);
      var $shape = tfjsCore.util.inferFromImplicitShape(shape, xSize);
      var $xSize = tfjsCore.util.sizeFromShape($shape);
      tfjsCore.util.assert(xSize === $xSize, function() {
        return "The new shape (".concat($shape, ") has ").concat($xSize, " elements and the old ") + "shape (".concat(x.shape, ") has ").concat(xSize, " elements. The new shape and old ") + "shape must have the same number of elements.";
      });
      backend.incRef(x.dataId);
      var xData = backend.data.get(x.dataId);
      if (xData.complexTensorInfos != null) {
        var real2 = xData.complexTensorInfos.real;
        var imag2 = xData.complexTensorInfos.imag;
        real2.shape = $shape;
        imag2.shape = $shape;
      }
      return { dataId: x.dataId, shape: $shape, dtype: x.dtype };
    }
    var reshapeConfig = {
      kernelName: tfjsCore.Reshape,
      backendName: "cpu",
      kernelFunc: reshape
    };
    function batchMatMul(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var a = inputs.a, b = inputs.b;
      var transposeA = attrs.transposeA, transposeB = attrs.transposeB;
      assertNotComplex([a, b], "matMul");
      var aRank = a.shape.length;
      var bRank = b.shape.length;
      var innerShapeA = transposeA ? a.shape[aRank - 2] : a.shape[aRank - 1];
      var innerShapeB = transposeB ? b.shape[bRank - 1] : b.shape[bRank - 2];
      var outerShapeA = transposeA ? a.shape[aRank - 1] : a.shape[aRank - 2];
      var outerShapeB = transposeB ? b.shape[bRank - 2] : b.shape[bRank - 1];
      var outerDimsA = a.shape.slice(0, -2);
      var outerDimsB = b.shape.slice(0, -2);
      var batchDimA = tfjsCore.util.sizeFromShape(outerDimsA);
      var batchDimB = tfjsCore.util.sizeFromShape(outerDimsB);
      var outShapeOuterDims = tfjsCore.broadcast_util.assertAndGetBroadcastShape(a.shape.slice(0, -2), b.shape.slice(0, -2));
      var outShape = outShapeOuterDims.concat([outerShapeA, outerShapeB]);
      tfjsCore.util.assert(innerShapeA === innerShapeB, function() {
        return "Error in matMul: inner shapes (".concat(innerShapeA, ") and (") + "".concat(innerShapeB, ") of Tensors with shapes ").concat(a.shape, " and ") + "".concat(b.shape, " and transposeA=").concat(transposeA) + " and transposeB=".concat(transposeB, " must match.");
      });
      var a3dShape = transposeA ? [batchDimA, innerShapeA, outerShapeA] : [batchDimA, outerShapeA, innerShapeA];
      var b3dShape = transposeB ? [batchDimB, outerShapeB, innerShapeB] : [batchDimB, innerShapeB, outerShapeB];
      var a3d = reshape({ inputs: { x: a }, backend, attrs: { shape: a3dShape } });
      var b3d = reshape({ inputs: { x: b }, backend, attrs: { shape: b3dShape } });
      var sharedDim = transposeA ? a3d.shape[1] : a3d.shape[2];
      var leftDim = transposeA ? a3d.shape[2] : a3d.shape[1];
      var rightDim = transposeB ? b3d.shape[1] : b3d.shape[2];
      var batchDim = Math.max(batchDimA, batchDimB);
      var a3dValues = backend.data.get(a3d.dataId).values;
      var b3dValues = backend.data.get(b3d.dataId).values;
      var a3dStrides = tfjsCore.util.computeStrides(a3d.shape);
      var b3dStrides = tfjsCore.util.computeStrides(b3d.shape);
      var _a2 = __read(transposeA ? [a3dStrides[0], 1, a3dStrides[1]] : [a3dStrides[0], a3dStrides[1], 1], 3), aBatch = _a2[0], aOuterStep = _a2[1], aInnerStep = _a2[2];
      var _b = __read(transposeB ? [1, b3dStrides[1], b3dStrides[0]] : [b3dStrides[1], 1, b3dStrides[0]], 3), bInnerStep = _b[0], bOuterStep = _b[1], bBatch = _b[2];
      var size = leftDim * rightDim;
      var result = tfjsCore.buffer([batchDim, leftDim, rightDim], a3d.dtype);
      var resVals = result.values;
      var blockSize = backend.blockSize;
      for (var bi = 0; bi < batchDim; bi++) {
        var batchIndexA = bi % batchDimA;
        var batchIndexB = bi % batchDimB;
        for (var i0 = 0; i0 < leftDim; i0 += blockSize) {
          var iBlock = Math.min(i0 + blockSize, leftDim);
          for (var j0 = 0; j0 < rightDim; j0 += blockSize) {
            var jBlock = Math.min(j0 + blockSize, rightDim);
            for (var k0 = 0; k0 < sharedDim; k0 += blockSize) {
              var kBlock = Math.min(k0 + blockSize, sharedDim);
              for (var i = i0; i < iBlock; i++) {
                for (var j = j0; j < jBlock; j++) {
                  var sum2 = 0;
                  for (var k = k0; k < kBlock; k++) {
                    var aVal = (
                      // tslint:disable-next-line: max-line-length
                      a3dValues[batchIndexA * aBatch + i * aOuterStep + k * aInnerStep]
                    );
                    var bVal = (
                      // tslint:disable-next-line: max-line-length
                      b3dValues[k * bInnerStep + j * bOuterStep + batchIndexB * bBatch]
                    );
                    sum2 += aVal * bVal;
                  }
                  resVals[bi * size + (i * rightDim + j)] += sum2;
                }
              }
            }
          }
        }
      }
      backend.disposeIntermediateTensorInfo(a3d);
      backend.disposeIntermediateTensorInfo(b3d);
      return backend.makeTensorInfo(outShape, result.dtype, result.values);
    }
    var batchMatMulConfig = {
      kernelName: tfjsCore.BatchMatMul,
      backendName: "cpu",
      kernelFunc: batchMatMul
    };
    function _fusedMatMul(args) {
      var e_12, _a2;
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var a = inputs.a, b = inputs.b, bias = inputs.bias, preluActivationWeights = inputs.preluActivationWeights;
      var transposeA = attrs.transposeA, transposeB = attrs.transposeB, activation = attrs.activation, leakyreluAlpha = attrs.leakyreluAlpha;
      var current;
      var addRes;
      var activationRes;
      var intermediates = [];
      var matMulRes = batchMatMul({ inputs: { a, b }, attrs: { transposeA, transposeB }, backend });
      current = matMulRes;
      if (bias) {
        addRes = add({ inputs: { a: current, b: bias }, backend });
        intermediates.push(current);
        current = addRes;
      }
      if (activation) {
        activationRes = applyActivation(backend, current, activation, preluActivationWeights, leakyreluAlpha);
        intermediates.push(current);
        current = activationRes;
      }
      try {
        for (var intermediates_1 = __values(intermediates), intermediates_1_1 = intermediates_1.next(); !intermediates_1_1.done; intermediates_1_1 = intermediates_1.next()) {
          var i = intermediates_1_1.value;
          backend.disposeIntermediateTensorInfo(i);
        }
      } catch (e_1_1) {
        e_12 = { error: e_1_1 };
      } finally {
        try {
          if (intermediates_1_1 && !intermediates_1_1.done && (_a2 = intermediates_1.return)) _a2.call(intermediates_1);
        } finally {
          if (e_12) throw e_12.error;
        }
      }
      return current;
    }
    var _fusedMatMulConfig = {
      kernelName: tfjsCore._FusedMatMul,
      backendName: "cpu",
      kernelFunc: _fusedMatMul
    };
    var acos = unaryKernelFunc(tfjsCore.Acos, function(xi) {
      return Math.acos(xi);
    });
    var acosConfig = {
      kernelName: tfjsCore.Acos,
      backendName: "cpu",
      kernelFunc: acos
    };
    var acosh = unaryKernelFunc(tfjsCore.Acosh, function(xi) {
      return Math.acosh(xi);
    });
    var acoshConfig = {
      kernelName: tfjsCore.Acosh,
      backendName: "cpu",
      kernelFunc: acosh
    };
    function addN(args) {
      var inputs = args.inputs, backend = args.backend;
      var tensors = inputs;
      assertNotComplex(inputs, "addN");
      var vals = tensors.map(function(t) {
        return backend.data.get(t.dataId).values;
      });
      var outBuf = tfjsCore.buffer(tensors[0].shape, tensors[0].dtype);
      var outVals = outBuf.values;
      for (var i = 0; i < tensors.length; i++) {
        var currVals = vals[i];
        for (var j = 0; j < outVals.length; j++) {
          outVals[j] += currVals[j];
        }
      }
      return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);
    }
    var addNConfig = {
      kernelName: tfjsCore.AddN,
      backendName: "cpu",
      kernelFunc: addN
    };
    function all(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis, keepDims = attrs.keepDims;
      assertNotComplex(x, "all");
      var origAxes = tfjsCore.util.parseAxisParam(axis, x.shape);
      var axes = origAxes;
      var permutedAxes = tfjsCore.backend_util.getAxesPermutation(axes, x.shape.length);
      var $x = x;
      if (permutedAxes != null) {
        $x = transpose({ inputs: { x }, backend, attrs: { perm: permutedAxes } });
        axes = tfjsCore.backend_util.getInnerMostAxes(axes.length, x.shape.length);
      }
      tfjsCore.backend_util.assertAxesAreInnerMostDims("all", axes, $x.shape.length);
      var _a2 = __read(tfjsCore.backend_util.computeOutAndReduceShapes($x.shape, axes), 2), outShape = _a2[0], reduceShape = _a2[1];
      var reduceSize = tfjsCore.util.sizeFromShape(reduceShape);
      var vals = tfjsCore.util.makeZerosTypedArray(tfjsCore.util.sizeFromShape(outShape), $x.dtype);
      var aVals = backend.data.get($x.dataId).values;
      for (var i = 0; i < vals.length; ++i) {
        var offset = i * reduceSize;
        var all_1 = aVals[offset];
        for (var j = 0; j < reduceSize; ++j) {
          var value = aVals[offset + j];
          all_1 = all_1 && value;
        }
        vals[i] = all_1;
      }
      if (permutedAxes != null) {
        backend.disposeIntermediateTensorInfo($x);
      }
      var result = backend.makeTensorInfo(outShape, $x.dtype, vals);
      if (keepDims) {
        var expandedShape = tfjsCore.backend_util.expandShapeToKeepDim(outShape, origAxes);
        var reshapedResult = reshape({ inputs: { x: result }, backend, attrs: { shape: expandedShape } });
        backend.disposeIntermediateTensorInfo(result);
        return reshapedResult;
      }
      return result;
    }
    var allConfig = {
      kernelName: tfjsCore.All,
      backendName: "cpu",
      kernelFunc: all
    };
    function any(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis, keepDims = attrs.keepDims;
      assertNotComplex(x, "any");
      var origAxes = tfjsCore.util.parseAxisParam(axis, x.shape);
      var axes = origAxes;
      var permutedAxes = tfjsCore.backend_util.getAxesPermutation(axes, x.shape.length);
      var $x = x;
      if (permutedAxes != null) {
        $x = transpose({ inputs: { x }, backend, attrs: { perm: permutedAxes } });
        axes = tfjsCore.backend_util.getInnerMostAxes(axes.length, x.shape.length);
      }
      tfjsCore.backend_util.assertAxesAreInnerMostDims("any", axes, $x.shape.length);
      var _a2 = __read(tfjsCore.backend_util.computeOutAndReduceShapes($x.shape, axes), 2), outShape = _a2[0], reduceShape = _a2[1];
      var reduceSize = tfjsCore.util.sizeFromShape(reduceShape);
      var vals = tfjsCore.util.makeZerosTypedArray(tfjsCore.util.sizeFromShape(outShape), $x.dtype);
      var aVals = backend.data.get($x.dataId).values;
      for (var i = 0; i < vals.length; ++i) {
        var offset = i * reduceSize;
        var anyVal = aVals[offset];
        for (var j = 0; j < reduceSize; ++j) {
          var value = aVals[offset + j];
          anyVal = anyVal || value;
        }
        vals[i] = anyVal;
      }
      if (permutedAxes != null) {
        backend.disposeIntermediateTensorInfo($x);
      }
      var result = backend.makeTensorInfo(outShape, $x.dtype, vals);
      if (keepDims) {
        var expandedShape = tfjsCore.backend_util.expandShapeToKeepDim(outShape, origAxes);
        var reshapedResult = reshape({ inputs: { x: result }, backend, attrs: { shape: expandedShape } });
        backend.disposeIntermediateTensorInfo(result);
        return reshapedResult;
      }
      return result;
    }
    var anyConfig = {
      kernelName: tfjsCore.Any,
      backendName: "cpu",
      kernelFunc: any
    };
    function argMax(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis;
      assertNotComplex(x, "argMax");
      var axes = tfjsCore.util.parseAxisParam(axis, x.shape);
      var permutedAxes = tfjsCore.backend_util.getAxesPermutation(axes, x.shape.length);
      var $x = x;
      var intermediateTensorInfos = [];
      if (permutedAxes != null) {
        $x = transpose({ inputs: { x }, backend, attrs: { perm: permutedAxes } });
        intermediateTensorInfos.push($x);
        axes = tfjsCore.backend_util.getInnerMostAxes(axes.length, $x.shape.length);
      }
      axes = [axes[0]];
      tfjsCore.backend_util.assertAxesAreInnerMostDims("argMax", axes, $x.shape.length);
      var _a2 = __read(tfjsCore.backend_util.computeOutAndReduceShapes($x.shape, axes), 2), outShape = _a2[0], reduceShape = _a2[1];
      var outSize = tfjsCore.util.sizeFromShape(outShape);
      var vals = tfjsCore.util.makeZerosTypedArray(outSize, "int32");
      var reduceSize = tfjsCore.util.sizeFromShape(reduceShape);
      var aVals = backend.data.get($x.dataId).values;
      for (var i = 0; i < vals.length; ++i) {
        var offset = i * reduceSize;
        var max2 = aVals[offset];
        var maxIndex = 0;
        for (var j = 0; j < reduceSize; ++j) {
          var value = aVals[offset + j];
          if (value > max2) {
            max2 = value;
            maxIndex = j;
          }
        }
        vals[i] = maxIndex;
      }
      intermediateTensorInfos.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return backend.makeTensorInfo(outShape, "int32", vals);
    }
    var argMaxConfig = {
      kernelName: tfjsCore.ArgMax,
      backendName: "cpu",
      kernelFunc: argMax
    };
    function argMin(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis;
      assertNotComplex(x, "argMin");
      var axes = tfjsCore.util.parseAxisParam(axis, x.shape);
      var permutedAxes = tfjsCore.backend_util.getAxesPermutation(axes, x.shape.length);
      var $x = x;
      var intermediateTensorInfos = [];
      if (permutedAxes != null) {
        $x = transpose({ inputs: { x }, backend, attrs: { perm: permutedAxes } });
        intermediateTensorInfos.push($x);
        axes = tfjsCore.backend_util.getInnerMostAxes(axes.length, $x.shape.length);
      }
      axes = [axes[0]];
      tfjsCore.backend_util.assertAxesAreInnerMostDims("argMin", axes, $x.shape.length);
      var _a2 = __read(tfjsCore.backend_util.computeOutAndReduceShapes($x.shape, axes), 2), outShape = _a2[0], reduceShape = _a2[1];
      var outSize = tfjsCore.util.sizeFromShape(outShape);
      var vals = tfjsCore.util.makeZerosTypedArray(outSize, "int32");
      var reduceSize = tfjsCore.util.sizeFromShape(reduceShape);
      var aVals = backend.data.get($x.dataId).values;
      for (var i = 0; i < vals.length; ++i) {
        var offset = i * reduceSize;
        var min2 = aVals[offset];
        var minIndex = 0;
        for (var j = 0; j < reduceSize; ++j) {
          var value = aVals[offset + j];
          if (value < min2) {
            min2 = value;
            minIndex = j;
          }
        }
        vals[i] = minIndex;
      }
      intermediateTensorInfos.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return backend.makeTensorInfo(outShape, "int32", vals);
    }
    var argMinConfig = {
      kernelName: tfjsCore.ArgMin,
      backendName: "cpu",
      kernelFunc: argMin
    };
    var asin = unaryKernelFunc(tfjsCore.Asin, function(xi) {
      return Math.asin(xi);
    });
    var asinConfig = {
      kernelName: tfjsCore.Asin,
      backendName: "cpu",
      kernelFunc: asin
    };
    var asinh = unaryKernelFunc(tfjsCore.Asinh, function(xi) {
      return Math.asinh(xi);
    });
    var asinhConfig = {
      kernelName: tfjsCore.Asinh,
      backendName: "cpu",
      kernelFunc: asinh
    };
    var atan = unaryKernelFunc(tfjsCore.Atan, function(xi) {
      return Math.atan(xi);
    });
    var atanConfig = {
      kernelName: tfjsCore.Atan,
      backendName: "cpu",
      kernelFunc: atan
    };
    var atan2Impl = createSimpleBinaryKernelImpl(function(aValue, bValue) {
      return Math.atan2(aValue, bValue);
    });
    var atan2 = binaryKernelFunc(tfjsCore.Atan2, atan2Impl);
    var atan2Config = {
      kernelName: tfjsCore.Atan2,
      backendName: "cpu",
      kernelFunc: atan2
    };
    var atanh = unaryKernelFunc(tfjsCore.Atanh, function(xi) {
      return Math.atanh(xi);
    });
    var atanhConfig = {
      kernelName: tfjsCore.Atanh,
      backendName: "cpu",
      kernelFunc: atanh
    };
    function pool(xValues, xShape, dtype, strides, convInfo, poolType) {
      var strideHeight = convInfo.strideHeight;
      var strideWidth = convInfo.strideWidth;
      var dilationHeight = convInfo.dilationHeight;
      var dilationWidth = convInfo.dilationWidth;
      var effectiveFilterHeight = convInfo.effectiveFilterHeight;
      var effectiveFilterWidth = convInfo.effectiveFilterWidth;
      var padTop = convInfo.padInfo.top;
      var padLeft = convInfo.padInfo.left;
      var initialValue = poolType === "max" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
      var output = tfjsCore.buffer(convInfo.outShape, dtype);
      var outputVals = output.values;
      var outputBatchStrides = convInfo.outShape[1] * convInfo.outShape[2] * convInfo.outShape[3];
      var outputRowStrides = convInfo.outShape[2] * convInfo.outShape[3];
      var outputColStrides = convInfo.outShape[3];
      for (var b = 0; b < convInfo.batchSize; ++b) {
        var outputBatchOffset = b * outputBatchStrides;
        var inputBatchOffset = b * strides[0];
        for (var d = 0; d < convInfo.inChannels; ++d) {
          for (var yR = 0; yR < convInfo.outHeight; ++yR) {
            var xRCorner = yR * strideHeight - padTop;
            var xRMin = Math.max(0, xRCorner);
            var xRMax = Math.min(convInfo.inHeight, effectiveFilterHeight + xRCorner);
            var outputRowOffset = outputBatchOffset + yR * outputRowStrides;
            for (var yC = 0; yC < convInfo.outWidth; ++yC) {
              var xCCorner = yC * strideWidth - padLeft;
              var xCMin = Math.max(0, xCCorner);
              var xCMax = Math.min(convInfo.inWidth, effectiveFilterWidth + xCCorner);
              var minMaxValue = initialValue;
              var avgValue = 0;
              var count = 0;
              for (var xR = xRMin; xR < xRMax; xR += dilationHeight) {
                var xROffset = inputBatchOffset + xR * strides[1];
                for (var xC = xCMin; xC < xCMax; xC += dilationWidth) {
                  var xCOffset = xROffset + xC * strides[2];
                  var pixel = xValues[xCOffset + d];
                  if (poolType === "max" && pixel > minMaxValue) {
                    minMaxValue = pixel;
                  } else if (poolType === "avg") {
                    avgValue += pixel;
                    count++;
                  }
                }
                if (isNaN(minMaxValue)) {
                  break;
                }
              }
              var outputOffset = outputRowOffset + yC * outputColStrides + d;
              outputVals[outputOffset] = poolType === "avg" ? avgValue / count : minMaxValue;
            }
          }
        }
      }
      return output;
    }
    function maxPoolPositions(xValues, xShape, dtype, convInfo, flattenPositions, includeBatchInIndex) {
      if (flattenPositions === void 0) {
        flattenPositions = false;
      }
      if (includeBatchInIndex === void 0) {
        includeBatchInIndex = false;
      }
      var maxPositions = tfjsCore.buffer(convInfo.outShape, "int32");
      var strideHeight = convInfo.strideHeight;
      var strideWidth = convInfo.strideWidth;
      var dilationHeight = convInfo.dilationHeight;
      var dilationWidth = convInfo.dilationWidth;
      var effectiveFilterHeight = convInfo.effectiveFilterHeight;
      var effectiveFilterWidth = convInfo.effectiveFilterWidth;
      var padTop = convInfo.padInfo.top;
      var padLeft = convInfo.padInfo.left;
      var xBuf = tfjsCore.buffer(xShape, dtype, xValues);
      for (var b = 0; b < convInfo.batchSize; ++b) {
        for (var d = 0; d < convInfo.inChannels; ++d) {
          for (var yR = 0; yR < convInfo.outHeight; ++yR) {
            var xRCorner = yR * strideHeight - padTop;
            var xRMin = xRCorner;
            while (xRMin < 0) {
              xRMin += dilationHeight;
            }
            var xRMax = Math.min(convInfo.inHeight, effectiveFilterHeight + xRCorner);
            for (var yC = 0; yC < convInfo.outWidth; ++yC) {
              var xCCorner = yC * strideWidth - padLeft;
              var xCMin = xCCorner;
              while (xCMin < 0) {
                xCMin += dilationWidth;
              }
              var xCMax = Math.min(convInfo.inWidth, effectiveFilterWidth + xCCorner);
              var maxValue = Number.NEGATIVE_INFINITY;
              var maxPosition = -1;
              for (var xR = xRMin; xR < xRMax; xR += dilationHeight) {
                var wR = xR - xRCorner;
                for (var xC = xCMin; xC < xCMax; xC += dilationWidth) {
                  var wC = xC - xCCorner;
                  var pixel = xBuf.get(b, xR, xC, d);
                  if (pixel > maxValue) {
                    maxValue = pixel;
                    if (flattenPositions) {
                      maxPosition = includeBatchInIndex ? ((b * convInfo.inHeight + xR) * convInfo.inWidth + xC) * convInfo.inChannels + d : (xR * convInfo.inWidth + xC) * convInfo.inChannels + d;
                    } else {
                      maxPosition = wR * effectiveFilterWidth + wC;
                    }
                  }
                }
              }
              maxPositions.set(maxPosition, b, yR, yC, d);
            }
          }
        }
      }
      return maxPositions;
    }
    function pool3d(xValues, xShape, dtype, strides, convInfo, poolType) {
      var strideDepth = convInfo.strideDepth;
      var strideHeight = convInfo.strideHeight;
      var strideWidth = convInfo.strideWidth;
      var dilationDepth = convInfo.dilationDepth;
      var dilationHeight = convInfo.dilationHeight;
      var dilationWidth = convInfo.dilationWidth;
      var effectiveFilterDepth = convInfo.effectiveFilterDepth;
      var effectiveFilterHeight = convInfo.effectiveFilterHeight;
      var effectiveFilterWidth = convInfo.effectiveFilterWidth;
      var padFront = convInfo.padInfo.front;
      var padTop = convInfo.padInfo.top;
      var padLeft = convInfo.padInfo.left;
      var initialValue = poolType === "max" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
      var output = tfjsCore.buffer(convInfo.outShape, dtype);
      var outputVals = output.values;
      var outputBatchStrides = convInfo.outShape[1] * convInfo.outShape[2] * convInfo.outShape[3] * convInfo.outShape[4];
      var outputDepthStrides = convInfo.outShape[2] * convInfo.outShape[3] * convInfo.outShape[4];
      var outputRowStrides = convInfo.outShape[3] * convInfo.outShape[4];
      var outputColStrides = convInfo.outShape[4];
      for (var batch = 0; batch < convInfo.batchSize; ++batch) {
        var outputBatchOffset = batch * outputBatchStrides;
        var inputBatchOffset = batch * strides[0];
        for (var channel = 0; channel < convInfo.inChannels; ++channel) {
          for (var yDepth = 0; yDepth < convInfo.outDepth; ++yDepth) {
            var xDepthCorner = yDepth * strideDepth - padFront;
            var xDepthMin = xDepthCorner;
            while (xDepthMin < 0) {
              xDepthMin += dilationDepth;
            }
            var xDepthMax = Math.min(convInfo.inDepth, effectiveFilterDepth + xDepthCorner);
            var outputDepthOffset = outputBatchOffset + yDepth * outputDepthStrides;
            for (var yRow = 0; yRow < convInfo.outHeight; ++yRow) {
              var xRowCorner = yRow * strideHeight - padTop;
              var xRowMin = xRowCorner;
              while (xRowMin < 0) {
                xRowMin += dilationHeight;
              }
              var xRowMax = Math.min(convInfo.inHeight, effectiveFilterHeight + xRowCorner);
              var outputRowOffset = outputDepthOffset + yRow * outputRowStrides;
              for (var yCol = 0; yCol < convInfo.outWidth; ++yCol) {
                var xColCorner = yCol * strideWidth - padLeft;
                var xColMin = xColCorner;
                while (xColMin < 0) {
                  xColMin += dilationWidth;
                }
                var xColMax = Math.min(convInfo.inWidth, effectiveFilterWidth + xColCorner);
                var outputColOffset = outputRowOffset + yCol * outputColStrides;
                var minMaxValue = initialValue;
                var avgValue = 0;
                var count = 0;
                for (var xDepth = xDepthMin; xDepth < xDepthMax; xDepth += dilationDepth) {
                  var xDepthOffset = inputBatchOffset + xDepth * strides[1];
                  for (var xRow = xRowMin; xRow < xRowMax; xRow += dilationHeight) {
                    var xRowOffset = xDepthOffset + xRow * strides[2];
                    for (var xCol = xColMin; xCol < xColMax; xCol += dilationWidth) {
                      var xColOffset = xRowOffset + xCol * strides[3];
                      var pixel = xValues[xColOffset + channel];
                      if (poolType === "max" && pixel > minMaxValue) {
                        minMaxValue = pixel;
                      } else if (poolType === "avg") {
                        avgValue += pixel;
                        count++;
                      }
                      if (isNaN(minMaxValue)) {
                        break;
                      }
                    }
                    if (isNaN(minMaxValue)) {
                      break;
                    }
                  }
                  if (isNaN(minMaxValue)) {
                    break;
                  }
                }
                var outputOffset = outputColOffset + channel;
                outputVals[outputOffset] = poolType === "avg" ? avgValue / Math.max(count, 1) : minMaxValue;
              }
            }
          }
        }
      }
      return output;
    }
    function maxPool3dPositions(xBuf, convInfo) {
      var maxPositions = tfjsCore.buffer(convInfo.outShape, "int32");
      var strideDepth = convInfo.strideDepth;
      var strideHeight = convInfo.strideHeight;
      var strideWidth = convInfo.strideWidth;
      var dilationDepth = convInfo.dilationDepth;
      var dilationHeight = convInfo.dilationHeight;
      var dilationWidth = convInfo.dilationWidth;
      var effectiveFilterDepth = convInfo.effectiveFilterDepth;
      var effectiveFilterHeight = convInfo.effectiveFilterHeight;
      var effectiveFilterWidth = convInfo.effectiveFilterWidth;
      var padFront = convInfo.padInfo.front;
      var padTop = convInfo.padInfo.top;
      var padLeft = convInfo.padInfo.left;
      for (var batch = 0; batch < convInfo.batchSize; ++batch) {
        for (var channel = 0; channel < convInfo.inChannels; ++channel) {
          for (var yDepth = 0; yDepth < convInfo.outDepth; ++yDepth) {
            var xDepthCorner = yDepth * strideDepth - padFront;
            var xDepthMin = xDepthCorner;
            while (xDepthMin < 0) {
              xDepthMin += dilationDepth;
            }
            var xDepthMax = Math.min(convInfo.inDepth, effectiveFilterDepth + xDepthCorner);
            for (var yRow = 0; yRow < convInfo.outHeight; ++yRow) {
              var xRowCorner = yRow * strideHeight - padTop;
              var xRowMin = xRowCorner;
              while (xRowMin < 0) {
                xRowMin += dilationHeight;
              }
              var xRowMax = Math.min(convInfo.inHeight, effectiveFilterHeight + xRowCorner);
              for (var yCol = 0; yCol < convInfo.outWidth; ++yCol) {
                var xColCorner = yCol * strideWidth - padLeft;
                var xColMin = xColCorner;
                while (xColMin < 0) {
                  xColMin += dilationWidth;
                }
                var xColMax = Math.min(convInfo.inWidth, effectiveFilterWidth + xColCorner);
                var maxValue = Number.NEGATIVE_INFINITY;
                var maxPosition = -1;
                for (var xDepth = xDepthMin; xDepth < xDepthMax; xDepth += dilationDepth) {
                  var wDepth = xDepth - xDepthCorner;
                  for (var xRow = xRowMin; xRow < xRowMax; xRow += dilationHeight) {
                    var wRow = xRow - xRowCorner;
                    for (var xCol = xColMin; xCol < xColMax; xCol += dilationWidth) {
                      var wCol = xCol - xColCorner;
                      var pixel = xBuf.get(batch, xDepth, xRow, xCol, channel);
                      if (pixel >= maxValue) {
                        maxValue = pixel;
                        maxPosition = wDepth * effectiveFilterHeight * effectiveFilterWidth + wRow * effectiveFilterHeight + wCol;
                      }
                    }
                  }
                }
                maxPositions.set(maxPosition, batch, yDepth, yRow, yCol, channel);
              }
            }
          }
        }
      }
      return maxPositions;
    }
    function avgPool(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      assertNotComplex(x, "avgPool");
      var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
      var dilations = 1;
      tfjsCore.util.assert(tfjsCore.backend_util.eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in avgPool: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      var convInfo = tfjsCore.backend_util.computePool2DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode);
      var res;
      if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 && tfjsCore.util.arraysEqual(convInfo.inShape, convInfo.outShape)) {
        res = identity({ inputs: { x }, backend });
      } else {
        var xValues = backend.data.get(x.dataId).values;
        var strides_1 = tfjsCore.util.computeStrides(x.shape);
        var buffer = pool(xValues, x.shape, x.dtype, strides_1, convInfo, "avg");
        res = backend.makeTensorInfo(convInfo.outShape, x.dtype, buffer.values);
      }
      return res;
    }
    var avgPoolConfig = {
      kernelName: tfjsCore.AvgPool,
      backendName: "cpu",
      kernelFunc: avgPool
    };
    function avgPool3D(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode, dataFormat = attrs.dataFormat;
      assertNotComplex(x, "avgPool3d");
      var convInfo = tfjsCore.backend_util.computePool3DInfo(x.shape, filterSize, strides, 1, pad, dimRoundingMode, dataFormat);
      var xValues = backend.data.get(x.dataId).values;
      var outBuf = pool3d(xValues, x.shape, x.dtype, tfjsCore.util.computeStrides(x.shape), convInfo, "avg");
      return backend.makeTensorInfo(outBuf.shape, "float32", outBuf.values);
    }
    var avgPool3DConfig = {
      kernelName: tfjsCore.AvgPool3D,
      backendName: "cpu",
      kernelFunc: avgPool3D
    };
    function avgPool3DGrad(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var dy = inputs.dy, input = inputs.input;
      var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
      assertNotComplex([dy, input], "avgPool3DGrad");
      var convInfo = tfjsCore.backend_util.computePool3DInfo(input.shape, filterSize, strides, 1, pad, dimRoundingMode);
      var strideDepth = convInfo.strideDepth;
      var strideHeight = convInfo.strideHeight;
      var strideWidth = convInfo.strideWidth;
      var filterDepth = convInfo.filterDepth;
      var filterHeight = convInfo.filterHeight;
      var filterWidth = convInfo.filterWidth;
      var dilationDepth = convInfo.dilationDepth;
      var dilationHeight = convInfo.dilationHeight;
      var dilationWidth = convInfo.dilationWidth;
      var effectiveFilterDepth = convInfo.effectiveFilterDepth;
      var effectiveFilterHeight = convInfo.effectiveFilterHeight;
      var effectiveFilterWidth = convInfo.effectiveFilterWidth;
      var padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;
      var padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
      var padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
      var dx = tfjsCore.buffer(input.shape, "float32");
      var avgMultiplier = 1 / (filterDepth * filterHeight * filterWidth);
      var dyBuf = backend.bufferSync(dy);
      for (var batch = 0; batch < convInfo.batchSize; ++batch) {
        for (var channel = 0; channel < convInfo.inChannels; ++channel) {
          for (var dxDepth = 0; dxDepth < convInfo.inDepth; ++dxDepth) {
            for (var dxRow = 0; dxRow < convInfo.inHeight; ++dxRow) {
              for (var dxCol = 0; dxCol < convInfo.inWidth; ++dxCol) {
                var dyDepthCorner = dxDepth - padFront;
                var dyRowCorner = dxRow - padTop;
                var dyColCorner = dxCol - padLeft;
                var dotProd = 0;
                for (var wDepth = 0; wDepth < effectiveFilterDepth; wDepth += dilationDepth) {
                  var dyDepth = (dyDepthCorner + wDepth) / strideDepth;
                  if (dyDepth < 0 || dyDepth >= convInfo.outDepth || Math.floor(dyDepth) !== dyDepth) {
                    continue;
                  }
                  for (var wRow = 0; wRow < effectiveFilterHeight; wRow += dilationHeight) {
                    var dyRow = (dyRowCorner + wRow) / strideHeight;
                    if (dyRow < 0 || dyRow >= convInfo.outHeight || Math.floor(dyRow) !== dyRow) {
                      continue;
                    }
                    for (var wCol = 0; wCol < effectiveFilterWidth; wCol += dilationWidth) {
                      var dyCol = (dyColCorner + wCol) / strideWidth;
                      if (dyCol < 0 || dyCol >= convInfo.outWidth || Math.floor(dyCol) !== dyCol) {
                        continue;
                      }
                      var pixel = dyBuf.get(batch, dyDepth, dyRow, dyCol, channel);
                      dotProd += pixel;
                    }
                  }
                }
                dx.set(dotProd * avgMultiplier, batch, dxDepth, dxRow, dxCol, channel);
              }
            }
          }
        }
      }
      return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);
    }
    var avgPool3DGradConfig = {
      kernelName: tfjsCore.AvgPool3DGrad,
      backendName: "cpu",
      kernelFunc: avgPool3DGrad
    };
    function avgPoolGrad(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var dy = inputs.dy, input = inputs.input;
      var x = input;
      assertNotComplex([dy, input], "avgPoolGrad");
      var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad;
      var convInfo = tfjsCore.backend_util.computePool2DInfo(x.shape, filterSize, strides, 1, pad);
      var strideHeight = convInfo.strideHeight;
      var strideWidth = convInfo.strideWidth;
      var filterHeight = convInfo.filterHeight;
      var filterWidth = convInfo.filterWidth;
      var dilationHeight = convInfo.dilationHeight;
      var dilationWidth = convInfo.dilationWidth;
      var effectiveFilterHeight = convInfo.effectiveFilterHeight;
      var effectiveFilterWidth = convInfo.effectiveFilterWidth;
      var padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
      var padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
      var dx = tfjsCore.buffer(x.shape, "float32");
      var avgMultiplier = 1 / (filterHeight * filterWidth);
      var dyData = backend.data.get(dy.dataId).values;
      var dyBuf = tfjsCore.buffer(dy.shape, "float32", dyData);
      for (var b = 0; b < convInfo.batchSize; ++b) {
        for (var d = 0; d < convInfo.inChannels; ++d) {
          for (var dxR = 0; dxR < convInfo.inHeight; ++dxR) {
            for (var dxC = 0; dxC < convInfo.inWidth; ++dxC) {
              var dyRCorner = dxR - padTop;
              var dyCCorner = dxC - padLeft;
              var dotProd = 0;
              for (var wR = 0; wR < effectiveFilterHeight; wR += dilationHeight) {
                var dyR = (dyRCorner + wR) / strideHeight;
                if (dyR < 0 || dyR >= convInfo.outHeight || Math.floor(dyR) !== dyR) {
                  continue;
                }
                for (var wC = 0; wC < effectiveFilterWidth; wC += dilationWidth) {
                  var dyC = (dyCCorner + wC) / strideWidth;
                  if (dyC < 0 || dyC >= convInfo.outWidth || Math.floor(dyC) !== dyC) {
                    continue;
                  }
                  var pixel = dyBuf.get(b, dyR, dyC, d);
                  dotProd += pixel;
                }
              }
              dx.set(dotProd * avgMultiplier, b, dxR, dxC, d);
            }
          }
        }
      }
      return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);
    }
    var avgPoolGradConfig = {
      kernelName: tfjsCore.AvgPoolGrad,
      backendName: "cpu",
      kernelFunc: avgPoolGrad
    };
    function batchNorm(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, scale2 = inputs.scale, offset = inputs.offset, mean2 = inputs.mean, variance = inputs.variance;
      tfjsCore.util.assert(mean2.shape.length === variance.shape.length, function() {
        return "Batch normalization gradient requires mean and variance to have equal ranks.";
      });
      tfjsCore.util.assert(offset == null || mean2.shape.length === offset.shape.length, function() {
        return "Batch normalization gradient requires mean and offset to have equal ranks.";
      });
      tfjsCore.util.assert(scale2 == null || mean2.shape.length === scale2.shape.length, function() {
        return "Batch normalization gradient requires mean and scale to have equal ranks.";
      });
      assertNotComplex([x, mean2, variance, scale2, offset], "batchNorm");
      var varianceEpsilon = attrs.varianceEpsilon;
      if (varianceEpsilon == null) {
        varianceEpsilon = 1e-3;
      }
      var xVals = backend.data.get(x.dataId).values;
      var mVals = backend.data.get(mean2.dataId).values;
      var varVals = backend.data.get(variance.dataId).values;
      var sVals = scale2 ? backend.data.get(scale2.dataId).values : new Float32Array([1]);
      var offVals = offset ? backend.data.get(offset.dataId).values : new Float32Array([0]);
      var outVals = new Float32Array(xVals.length);
      var offValsLength = offVals.length;
      var sValsLength = sVals.length;
      var varValsLength = varVals.length;
      var mValsLength = mVals.length;
      var offi = 0;
      var mi = 0;
      var si = 0;
      var vi = 0;
      for (var i = 0; i < xVals.length; ++i) {
        outVals[i] = offVals[offi++] + (xVals[i] - mVals[mi++]) * sVals[si++] / Math.sqrt(varVals[vi++] + varianceEpsilon);
        if (offi >= offValsLength) {
          offi = 0;
        }
        if (mi >= mValsLength) {
          mi = 0;
        }
        if (si >= sValsLength) {
          si = 0;
        }
        if (vi >= varValsLength) {
          vi = 0;
        }
      }
      return backend.makeTensorInfo(x.shape, x.dtype, outVals);
    }
    var batchNormConfig = {
      kernelName: tfjsCore.FusedBatchNorm,
      backendName: "cpu",
      kernelFunc: batchNorm
    };
    function batchToSpaceND(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var blockShape = attrs.blockShape, crops = attrs.crops;
      assertNotComplex([x], "batchToSpaceND");
      var prod2 = blockShape.reduce(function(a, b) {
        return a * b;
      });
      var reshaped = tfjsCore.backend_util.getReshaped(x.shape, blockShape, prod2);
      var permuted = tfjsCore.backend_util.getPermuted(reshaped.length, blockShape.length);
      var reshapedPermuted = tfjsCore.backend_util.getReshapedPermuted(x.shape, blockShape, prod2);
      var sliceBeginCoords = tfjsCore.backend_util.getSliceBeginCoords(crops, blockShape.length);
      var sliceSize = tfjsCore.backend_util.getSliceSize(reshapedPermuted, crops, blockShape.length);
      var xReshaped = reshape({ inputs: { x }, backend, attrs: { shape: reshaped } });
      var xTransposed = transpose({ inputs: { x: xReshaped }, backend, attrs: { perm: permuted } });
      var xTransposedReshaped = reshape({ inputs: { x: xTransposed }, backend, attrs: { shape: reshapedPermuted } });
      var result = slice({
        inputs: { x: xTransposedReshaped },
        backend,
        attrs: { begin: sliceBeginCoords, size: sliceSize }
      });
      backend.disposeIntermediateTensorInfo(xReshaped);
      backend.disposeIntermediateTensorInfo(xTransposed);
      backend.disposeIntermediateTensorInfo(xTransposedReshaped);
      return result;
    }
    var batchToSpaceNDConfig = {
      kernelName: tfjsCore.BatchToSpaceND,
      backendName: "cpu",
      kernelFunc: batchToSpaceND
    };
    function bincount(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, weights = inputs.weights;
      var size = attrs.size;
      var xVals = backend.data.get(x.dataId).values;
      var weightsVals = backend.data.get(weights.dataId).values;
      var outVals = bincountImpl(xVals, weightsVals, weights.dtype, weights.shape, size);
      return backend.makeTensorInfo([size], weights.dtype, outVals);
    }
    var bincountConfig = {
      kernelName: tfjsCore.Bincount,
      backendName: "cpu",
      kernelFunc: bincount
    };
    function broadcastArgs(args) {
      var inputs = args.inputs, backend = args.backend;
      var s0 = inputs.s0, s1 = inputs.s1;
      var s0Vals = backend.data.get(s0.dataId).values;
      var s1Vals = backend.data.get(s1.dataId).values;
      var broadcastShape = tfjsCore.backend_util.assertAndGetBroadcastShape(Array.from(s0Vals), Array.from(s1Vals));
      return backend.makeTensorInfo([broadcastShape.length], "int32", Int32Array.from(broadcastShape));
    }
    var broadcastArgsConfig = {
      kernelName: tfjsCore.BroadcastArgs,
      backendName: "cpu",
      kernelFunc: broadcastArgs
    };
    var clipByValue = unaryKernelFunc(tfjsCore.ClipByValue, function(xi, attrs) {
      var clipAttrs = attrs;
      if (xi > clipAttrs.clipValueMax) {
        return clipAttrs.clipValueMax;
      }
      return xi < clipAttrs.clipValueMin ? clipAttrs.clipValueMin : xi;
    });
    var clipByValueConfig = {
      kernelName: tfjsCore.ClipByValue,
      backendName: "cpu",
      kernelFunc: clipByValue
    };
    var complexAbs = function(args) {
      var x = args.inputs.x;
      var cpuBackend = args.backend;
      var resultValues = new Float32Array(tfjsCore.util.sizeFromShape(x.shape));
      var complexVals = cpuBackend.data.get(x.dataId);
      var real2 = complexVals.complexTensorInfos.real;
      var imag2 = complexVals.complexTensorInfos.imag;
      var realVals = cpuBackend.data.get(real2.dataId).values;
      var imagVals = cpuBackend.data.get(imag2.dataId).values;
      for (var i = 0; i < realVals.length; i++) {
        var real_1 = realVals[i];
        var imag_1 = imagVals[i];
        resultValues[i] = Math.hypot(real_1, imag_1);
      }
      return cpuBackend.makeOutput(resultValues, x.shape, "float32");
    };
    var complexAbsConfig = {
      kernelName: tfjsCore.ComplexAbs,
      backendName: "cpu",
      kernelFunc: complexAbs
    };
    function imag(args) {
      var inputs = args.inputs, backend = args.backend;
      var input = inputs.input;
      var imag2 = backend.data.get(input.dataId).complexTensorInfos.imag;
      var imagVal = backend.data.get(imag2.dataId).values;
      return backend.makeTensorInfo(imag2.shape, imag2.dtype, imagVal);
    }
    var imagConfig = {
      kernelName: tfjsCore.Imag,
      backendName: "cpu",
      kernelFunc: imag
    };
    function concat(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var axis = attrs.axis;
      var $axis = tfjsCore.util.parseAxisParam(axis, inputs[0].shape)[0];
      var shapes = inputs.map(function(t) {
        return t.shape;
      });
      tfjsCore.backend_util.assertParamsConsistent(shapes, $axis);
      var outShape = tfjsCore.backend_util.computeOutShape(inputs.map(function(t) {
        return t.shape;
      }), $axis);
      if (tfjsCore.util.sizeFromShape(outShape) === 0) {
        return backend.makeTensorInfo(outShape, inputs[0].dtype, []);
      }
      var $inputs = inputs.filter(function(t) {
        return tfjsCore.util.sizeFromShape(t.shape) > 0;
      });
      if ($inputs.length === 1) {
        return identity({ inputs: { x: $inputs[0] }, backend });
      }
      if ($inputs[0].dtype === "complex64") {
        var reals = $inputs.map(function(t) {
          return real({ inputs: { input: t }, backend });
        });
        var imags = $inputs.map(function(t) {
          return imag({ inputs: { input: t }, backend });
        });
        var realConcated = concat({ inputs: reals, backend, attrs: { axis: $axis } });
        var imagConcated = concat({ inputs: imags, backend, attrs: { axis: $axis } });
        var result = complex({ inputs: { real: realConcated, imag: imagConcated }, backend });
        reals.forEach(function(r) {
          return backend.disposeIntermediateTensorInfo(r);
        });
        imags.forEach(function(i) {
          return backend.disposeIntermediateTensorInfo(i);
        });
        backend.disposeIntermediateTensorInfo(realConcated);
        backend.disposeIntermediateTensorInfo(imagConcated);
        return result;
      }
      var inputs2D = $inputs.map(function(t) {
        var innerSize = tfjsCore.util.sizeFromShape(t.shape.slice($axis));
        var shape = [-1, innerSize];
        return reshape({ inputs: { x: t }, backend, attrs: { shape } });
      });
      var inputsValShapes = inputs2D.map(function(t) {
        return { vals: backend.data.get(t.dataId).values, shape: t.shape };
      });
      outShape = tfjsCore.backend_util.computeOutShape(
        inputs2D.map(function(t) {
          return t.shape;
        }),
        1
        /* axis */
      );
      var simplyConcat = inputs2D[0].shape[0] === 1;
      var outVals = concatImpl(inputsValShapes, outShape, inputs[0].dtype, simplyConcat);
      var finalOutShape = tfjsCore.backend_util.computeOutShape($inputs.map(function(t) {
        return t.shape;
      }), $axis);
      var outInfo = backend.makeTensorInfo(finalOutShape, inputs[0].dtype, outVals);
      inputs2D.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return outInfo;
    }
    var concatConfig = {
      kernelName: tfjsCore.Concat,
      backendName: "cpu",
      kernelFunc: concat
    };
    function conv2D(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, filter = inputs.filter;
      var strides = attrs.strides, pad = attrs.pad, dataFormat = attrs.dataFormat, dilations = attrs.dilations, dimRoundingMode = attrs.dimRoundingMode;
      assertNotComplex([x, filter], "conv2d");
      var $dataFormat = tfjsCore.backend_util.convertConv2DDataFormat(dataFormat);
      var convInfo = tfjsCore.backend_util.computeConv2DInfo(x.shape, filter.shape, strides, dilations, pad, dimRoundingMode, false, $dataFormat);
      var filterHeight = convInfo.filterHeight;
      var filterWidth = convInfo.filterWidth;
      var dilationHeight = convInfo.dilationHeight;
      var dilationWidth = convInfo.dilationWidth;
      var padLeft = convInfo.padInfo.left;
      var padTop = convInfo.padInfo.top;
      var isChannelsLast = convInfo.dataFormat === "channelsLast";
      var y = new tfjsCore.TensorBuffer(convInfo.outShape, x.dtype);
      var xStrides = tfjsCore.util.computeStrides(x.shape);
      var filterStrides = tfjsCore.util.computeStrides(filter.shape);
      var xBatchStride = xStrides[0];
      var xRowStride = isChannelsLast ? xStrides[1] : xStrides[2];
      var xColStride = isChannelsLast ? xStrides[2] : 1;
      var xChannelStride = isChannelsLast ? 1 : xStrides[1];
      var yBatchStride = y.strides[0];
      var yRowStride = isChannelsLast ? y.strides[1] : y.strides[2];
      var yColStride = isChannelsLast ? y.strides[2] : 1;
      var yChannelStride = isChannelsLast ? 1 : y.strides[1];
      var xVals = backend.data.get(x.dataId).values;
      var wVals = backend.data.get(filter.dataId).values;
      var yVals = y.values;
      for (var b = 0; b < convInfo.batchSize; ++b) {
        var xOffset1 = b * xBatchStride;
        var yOffset1 = b * yBatchStride;
        for (var yR = 0; yR < convInfo.outHeight; ++yR) {
          var yOffset2 = yOffset1 + yR * yRowStride;
          var xRCorner = yR * convInfo.strideHeight - padTop;
          for (var wR = 0; wR < filterHeight; ++wR) {
            var xR = xRCorner + wR * dilationHeight;
            if (xR < 0 || xR >= convInfo.inHeight) {
              continue;
            }
            var wOffset1 = wR * filterStrides[0];
            var xOffset2 = xOffset1 + xR * xRowStride;
            for (var yC = 0; yC < convInfo.outWidth; ++yC) {
              var yOffset3 = yOffset2 + yC * yColStride;
              var xCCorner = yC * convInfo.strideWidth - padLeft;
              for (var wC = 0; wC < filterWidth; ++wC) {
                var xC = xCCorner + wC * dilationWidth;
                if (xC < 0 || xC >= convInfo.inWidth) {
                  continue;
                }
                var wOffset2 = wOffset1 + wC * filterStrides[1];
                var xOffset3 = xOffset2 + xC * xColStride;
                var wOffset3 = wOffset2;
                for (var d1 = 0; d1 < convInfo.inChannels; ++d1) {
                  var xVal = xVals[xOffset3 + d1 * xChannelStride];
                  for (var d2 = 0; d2 < convInfo.outChannels; ++d2) {
                    yVals[yOffset3 + d2 * yChannelStride] += xVal * wVals[wOffset3 + d2];
                  }
                  wOffset3 += convInfo.outChannels;
                }
              }
            }
          }
        }
      }
      return backend.makeTensorInfo(y.shape, y.dtype, yVals);
    }
    var conv2DConfig = {
      kernelName: tfjsCore.Conv2D,
      backendName: "cpu",
      kernelFunc: conv2D
    };
    function conv2DBackpropFilter(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, dy = inputs.dy;
      var strides = attrs.strides, pad = attrs.pad, dataFormat = attrs.dataFormat, dimRoundingMode = attrs.dimRoundingMode, filterShape = attrs.filterShape;
      assertNotComplex([x, dy], "conv2dBackpropFilter");
      var $dataFormat = tfjsCore.backend_util.convertConv2DDataFormat(dataFormat);
      var convInfo = tfjsCore.backend_util.computeConv2DInfo(x.shape, filterShape, strides, 1, pad, dimRoundingMode, false, $dataFormat);
      var strideHeight = convInfo.strideHeight, strideWidth = convInfo.strideWidth, filterHeight = convInfo.filterHeight, filterWidth = convInfo.filterWidth;
      var isChannelsLast = convInfo.dataFormat === "channelsLast";
      var dW = new tfjsCore.TensorBuffer(convInfo.filterShape, "float32");
      var leftPad = convInfo.padInfo.left;
      var topPad = convInfo.padInfo.top;
      var xVals = backend.data.get(x.dataId).values;
      var dyVals = backend.data.get(dy.dataId).values;
      var xBuf = new tfjsCore.TensorBuffer(x.shape, x.dtype, xVals);
      var dyBuf = new tfjsCore.TensorBuffer(dy.shape, dy.dtype, dyVals);
      for (var wR = 0; wR < filterHeight; ++wR) {
        var yRMin = Math.max(0, Math.ceil((topPad - wR) / strideHeight));
        var yRMax = Math.min(convInfo.outHeight, (convInfo.inHeight + topPad - wR) / strideHeight);
        for (var wC = 0; wC < filterWidth; ++wC) {
          var yCMin = Math.max(0, Math.ceil((leftPad - wC) / strideWidth));
          var yCMax = Math.min(convInfo.outWidth, (convInfo.inWidth + leftPad - wC) / strideWidth);
          for (var d1 = 0; d1 < convInfo.inChannels; ++d1) {
            for (var d2 = 0; d2 < convInfo.outChannels; ++d2) {
              var dotProd = 0;
              for (var b = 0; b < convInfo.batchSize; ++b) {
                for (var yR = yRMin; yR < yRMax; ++yR) {
                  var xR = wR + yR * strideHeight - topPad;
                  for (var yC = yCMin; yC < yCMax; ++yC) {
                    var xC = wC + yC * strideWidth - leftPad;
                    if (isChannelsLast) {
                      dotProd += xBuf.get(b, xR, xC, d1) * dyBuf.get(b, yR, yC, d2);
                    } else {
                      dotProd += xBuf.get(b, d1, xR, xC) * dyBuf.get(b, d2, yR, yC);
                    }
                  }
                }
              }
              dW.set(dotProd, wR, wC, d1, d2);
            }
          }
        }
      }
      return backend.makeTensorInfo(dW.shape, dW.dtype, dW.values);
    }
    var conv2DBackpropFilterConfig = {
      kernelName: tfjsCore.Conv2DBackpropFilter,
      backendName: "cpu",
      kernelFunc: conv2DBackpropFilter
    };
    function conv2DBackpropInput(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var dy = inputs.dy, filter = inputs.filter;
      var inputShape = attrs.inputShape, strides = attrs.strides, pad = attrs.pad, dataFormat = attrs.dataFormat, dimRoundingMode = attrs.dimRoundingMode;
      assertNotComplex([dy, filter], "conv2dBackpropInput");
      var filterStrides = tfjsCore.util.computeStrides(filter.shape);
      var dyStrides = tfjsCore.util.computeStrides(dy.shape);
      var $dataFormat = tfjsCore.backend_util.convertConv2DDataFormat(dataFormat);
      var convInfo = tfjsCore.backend_util.computeConv2DInfo(inputShape, filter.shape, strides, 1, pad, dimRoundingMode, false, $dataFormat);
      var dx = new tfjsCore.TensorBuffer(convInfo.inShape, "float32");
      var dxValues = dx.values;
      var dyValues = backend.data.get(dy.dataId).values;
      var fltValues = backend.data.get(filter.dataId).values;
      var _a2 = __read(filterStrides, 3), fltS0 = _a2[0], fltS1 = _a2[1], fltS2 = _a2[2];
      var batchSize = convInfo.batchSize, filterHeight = convInfo.filterHeight, filterWidth = convInfo.filterWidth, inChannels = convInfo.inChannels, inHeight = convInfo.inHeight, inWidth = convInfo.inWidth, outChannels = convInfo.outChannels, outHeight = convInfo.outHeight, outWidth = convInfo.outWidth, strideHeight = convInfo.strideHeight, strideWidth = convInfo.strideWidth;
      $dataFormat = convInfo.dataFormat;
      var topPad = filterHeight - 1 - convInfo.padInfo.top;
      var leftPad = filterWidth - 1 - convInfo.padInfo.left;
      var isChannelsLast = $dataFormat === "channelsLast";
      var xBatchStride = dx.strides[0];
      var xRowStride = isChannelsLast ? dx.strides[1] : dx.strides[2];
      var xColStride = isChannelsLast ? dx.strides[2] : 1;
      var xChannelStride = isChannelsLast ? 1 : dx.strides[1];
      var yBatchStride = dyStrides[0];
      var yRowStride = isChannelsLast ? dyStrides[1] : dyStrides[2];
      var yColStride = isChannelsLast ? dyStrides[2] : 1;
      var yChannelStride = isChannelsLast ? 1 : dyStrides[1];
      for (var b = 0; b < batchSize; ++b) {
        for (var d1 = 0; d1 < inChannels; ++d1) {
          for (var xR = 0; xR < inHeight; ++xR) {
            var xRCorner = xR - topPad;
            var xRMin = Math.max(0, Math.ceil(xRCorner / strideHeight));
            var yRMax = Math.min(outHeight, (filterHeight + xRCorner) / strideHeight);
            for (var xC = 0; xC < inWidth; ++xC) {
              var xCCorner = xC - leftPad;
              var xCMin = Math.max(0, Math.ceil(xCCorner / strideWidth));
              var yCMax = Math.min(outWidth, (filterWidth + xCCorner) / strideWidth);
              var dotProd = 0;
              for (var yR = xRMin; yR < yRMax; ++yR) {
                var wR = yR * strideHeight - xRCorner;
                for (var yC = xCMin; yC < yCMax; ++yC) {
                  var wC = yC * strideWidth - xCCorner;
                  var dyOffset = yBatchStride * b + yRowStride * yR + yColStride * yC;
                  var fltOffset = fltS0 * (filterHeight - 1 - wR) + fltS1 * (filterWidth - 1 - wC) + fltS2 * d1;
                  for (var d2 = 0; d2 < outChannels; ++d2) {
                    var pixel = dyValues[dyOffset + yChannelStride * d2];
                    var weight = fltValues[fltOffset + d2];
                    dotProd += pixel * weight;
                  }
                }
              }
              var dxOffset = xBatchStride * b + xRowStride * xR + xColStride * xC + xChannelStride * d1;
              dxValues[dxOffset] = dotProd;
            }
          }
        }
      }
      return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);
    }
    var conv2DBackpropInputConfig = {
      kernelName: tfjsCore.Conv2DBackpropInput,
      backendName: "cpu",
      kernelFunc: conv2DBackpropInput
    };
    function conv3D(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, filter = inputs.filter;
      var strides = attrs.strides, pad = attrs.pad, dilations = attrs.dilations;
      assertNotComplex([x, filter], "conv3d");
      var convInfo = tfjsCore.backend_util.computeConv3DInfo(x.shape, filter.shape, strides, dilations, pad);
      var filterDepth = convInfo.filterDepth, filterHeight = convInfo.filterHeight, filterWidth = convInfo.filterWidth, dilationDepth = convInfo.dilationDepth, dilationHeight = convInfo.dilationHeight, dilationWidth = convInfo.dilationWidth, padInfo = convInfo.padInfo;
      var padFront = padInfo.front;
      var padLeft = padInfo.left;
      var padTop = padInfo.top;
      var y = new tfjsCore.TensorBuffer(convInfo.outShape, x.dtype);
      var xVals = backend.data.get(x.dataId).values;
      var wVals = backend.data.get(filter.dataId).values;
      var yVals = y.values;
      var xStrides = tfjsCore.util.computeStrides(x.shape);
      var filterStrides = tfjsCore.util.computeStrides(filter.shape);
      for (var b = 0; b < convInfo.batchSize; ++b) {
        var xOffset1 = b * xStrides[0];
        var yOffset1 = b * y.strides[0];
        for (var yF = 0; yF < convInfo.outDepth; ++yF) {
          var yOffset2 = yOffset1 + yF * y.strides[1];
          var xFCorner = yF * convInfo.strideDepth - padFront;
          for (var wF = 0; wF < filterDepth; ++wF) {
            var xF = xFCorner + wF * dilationDepth;
            if (xF < 0 || xF >= convInfo.inDepth) {
              continue;
            }
            var wOffset1 = wF * filterStrides[0];
            var xOffset2 = xOffset1 + xF * xStrides[1];
            for (var yR = 0; yR < convInfo.outHeight; ++yR) {
              var yOffset3 = yOffset2 + yR * y.strides[2];
              var xRCorner = yR * convInfo.strideHeight - padTop;
              for (var wR = 0; wR < filterHeight; ++wR) {
                var xR = xRCorner + wR * dilationHeight;
                if (xR < 0 || xR >= convInfo.inHeight) {
                  continue;
                }
                var wOffset2 = wOffset1 + wR * filterStrides[1];
                var xOffset3 = xOffset2 + xR * xStrides[2];
                for (var yC = 0; yC < convInfo.outWidth; ++yC) {
                  var yOffset4 = yOffset3 + yC * convInfo.outChannels;
                  var xCCorner = yC * convInfo.strideWidth - padLeft;
                  for (var wC = 0; wC < filterWidth; ++wC) {
                    var xC = xCCorner + wC * dilationWidth;
                    if (xC < 0 || xC >= convInfo.inWidth) {
                      continue;
                    }
                    var wOffset3 = wOffset2 + wC * filterStrides[2];
                    var xOffset4 = xOffset3 + xC * convInfo.inChannels;
                    var wOffset4 = wOffset3;
                    for (var d1 = 0; d1 < convInfo.inChannels; ++d1) {
                      var xVal = xVals[xOffset4 + d1];
                      for (var d2 = 0; d2 < convInfo.outChannels; ++d2) {
                        yVals[yOffset4 + d2] += xVal * wVals[wOffset4 + d2];
                      }
                      wOffset4 += convInfo.outChannels;
                    }
                  }
                }
              }
            }
          }
        }
      }
      return backend.makeTensorInfo(y.shape, y.dtype, y.values);
    }
    var conv3DConfig = {
      kernelName: tfjsCore.Conv3D,
      backendName: "cpu",
      kernelFunc: conv3D
    };
    function conv3DBackpropFilterV2(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, dy = inputs.dy;
      var strides = attrs.strides, pad = attrs.pad, filterShape = attrs.filterShape;
      assertNotComplex([x, dy], "conv3dBackpropFilterV2");
      var xStrides = tfjsCore.util.computeStrides(x.shape);
      var dyStrides = tfjsCore.util.computeStrides(dy.shape);
      var convInfo = tfjsCore.backend_util.computeConv3DInfo(x.shape, filterShape, strides, 1, pad);
      var strideDepth = convInfo.strideDepth;
      var strideHeight = convInfo.strideHeight;
      var strideWidth = convInfo.strideWidth;
      var filterDepth = convInfo.filterDepth;
      var filterHeight = convInfo.filterHeight;
      var filterWidth = convInfo.filterWidth;
      var dw = new tfjsCore.TensorBuffer(convInfo.filterShape, "float32");
      var dwValues = dw.values;
      var _a2 = __read(dw.strides, 4), dwS0 = _a2[0], dwS1 = _a2[1], dwS2 = _a2[2], dwS3 = _a2[3];
      var dyValues = backend.data.get(dy.dataId).values;
      var _b = __read(dyStrides, 4), dyS0 = _b[0], dyS1 = _b[1], dyS2 = _b[2], dyS3 = _b[3];
      var xValues = backend.data.get(x.dataId).values;
      var _c = __read(xStrides, 4), xS0 = _c[0], xS1 = _c[1], xS2 = _c[2], xS3 = _c[3];
      var frontPad = convInfo.padInfo.front;
      var leftPad = convInfo.padInfo.left;
      var topPad = convInfo.padInfo.top;
      for (var wF = 0; wF < filterDepth; ++wF) {
        var yFMin = Math.max(0, Math.ceil((frontPad - wF) / strideDepth));
        var yFMax = Math.min(convInfo.outDepth, (convInfo.inDepth + frontPad - wF) / strideDepth);
        var wOffset1 = wF * dwS0;
        for (var wR = 0; wR < filterHeight; ++wR) {
          var yRMin = Math.max(0, Math.ceil((topPad - wR) / strideHeight));
          var yRMax = Math.min(convInfo.outHeight, (convInfo.inHeight + topPad - wR) / strideHeight);
          var wOffset2 = wR * dwS1 + wOffset1;
          for (var wC = 0; wC < filterWidth; ++wC) {
            var yCMin = Math.max(0, Math.ceil((leftPad - wC) / strideWidth));
            var yCMax = Math.min(convInfo.outWidth, (convInfo.inWidth + leftPad - wC) / strideWidth);
            var wOffset3 = wC * dwS2 + wOffset2;
            for (var d1 = 0; d1 < convInfo.inChannels; ++d1) {
              var wOffset4 = d1 * dwS3 + wOffset3;
              for (var d2 = 0; d2 < convInfo.outChannels; ++d2) {
                var dotProd = 0;
                for (var b = 0; b < convInfo.batchSize; ++b) {
                  var xOffset1 = b * xS0;
                  var yOffset1 = b * dyS0;
                  for (var yF = yFMin; yF < yFMax; ++yF) {
                    var xF = wF + yF * strideDepth - frontPad;
                    var xOffset2 = xF * xS1 + xOffset1;
                    var yOffset2 = yF * dyS1 + yOffset1;
                    for (var yR = yRMin; yR < yRMax; ++yR) {
                      var xR = wR + yR * strideHeight - topPad;
                      var xOffset3 = xR * xS2 + xOffset2;
                      var yOffset3 = yR * dyS2 + yOffset2;
                      for (var yC = yCMin; yC < yCMax; ++yC) {
                        var xC = wC + yC * strideWidth - leftPad;
                        var xOffset4 = xC * xS3 + xOffset3;
                        var yOffset4 = yC * dyS3 + yOffset3;
                        dotProd += xValues[xOffset4 + d1] * dyValues[yOffset4 + d2];
                      }
                    }
                  }
                }
                dwValues[wOffset4 + d2] = dotProd;
              }
            }
          }
        }
      }
      return backend.makeTensorInfo(dw.shape, dw.dtype, dw.values);
    }
    var conv3DBackpropFilterV2Config = {
      kernelName: tfjsCore.Conv3DBackpropFilterV2,
      backendName: "cpu",
      kernelFunc: conv3DBackpropFilterV2
    };
    function conv3DBackpropInputV2(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var dy = inputs.dy, filter = inputs.filter;
      var pad = attrs.pad, strides = attrs.strides, inputShape = attrs.inputShape;
      assertNotComplex([dy], "conv3dBackpropInputV2");
      var dyStrides = tfjsCore.util.computeStrides(dy.shape);
      var filterStrides = tfjsCore.util.computeStrides(filter.shape);
      var convInfo = tfjsCore.backend_util.computeConv3DInfo(inputShape, filter.shape, strides, 1, pad);
      var dx = new tfjsCore.TensorBuffer(convInfo.inShape, "float32");
      var dxValues = dx.values;
      var _a2 = __read(dx.strides, 4), dxS0 = _a2[0], dxS1 = _a2[1], dxS2 = _a2[2], dxS3 = _a2[3];
      var dyValues = backend.data.get(dy.dataId).values;
      var _b = __read(dyStrides, 4), dyS0 = _b[0], dyS1 = _b[1], dyS2 = _b[2], dyS3 = _b[3];
      var fltValues = backend.data.get(filter.dataId).values;
      var _c = __read(filterStrides, 4), fltS0 = _c[0], fltS1 = _c[1], fltS2 = _c[2], fltS3 = _c[3];
      var batchSize = convInfo.batchSize, filterDepth = convInfo.filterDepth, filterHeight = convInfo.filterHeight, filterWidth = convInfo.filterWidth, inChannels = convInfo.inChannels, inDepth = convInfo.inDepth, inHeight = convInfo.inHeight, inWidth = convInfo.inWidth, outChannels = convInfo.outChannels, outDepth = convInfo.outDepth, outHeight = convInfo.outHeight, outWidth = convInfo.outWidth, strideDepth = convInfo.strideDepth, strideHeight = convInfo.strideHeight, strideWidth = convInfo.strideWidth;
      var frontPad = filterDepth - 1 - convInfo.padInfo.front;
      var topPad = filterHeight - 1 - convInfo.padInfo.top;
      var leftPad = filterWidth - 1 - convInfo.padInfo.left;
      for (var b = 0; b < batchSize; ++b) {
        for (var d1 = 0; d1 < inChannels; ++d1) {
          for (var xF = 0; xF < inDepth; ++xF) {
            var xFCorner = xF - frontPad;
            var xFMin = Math.max(0, Math.ceil(xFCorner / strideDepth));
            var yFMax = Math.min(outDepth, (filterDepth + xFCorner) / strideDepth);
            for (var xR = 0; xR < inHeight; ++xR) {
              var xRCorner = xR - topPad;
              var xRMin = Math.max(0, Math.ceil(xRCorner / strideHeight));
              var yRMax = Math.min(outHeight, (filterHeight + xRCorner) / strideHeight);
              for (var xC = 0; xC < inWidth; ++xC) {
                var xCCorner = xC - leftPad;
                var xCMin = Math.max(0, Math.ceil(xCCorner / strideWidth));
                var yCMax = Math.min(outWidth, (filterWidth + xCCorner) / strideWidth);
                var dotProd = 0;
                for (var yF = xFMin; yF < yFMax; ++yF) {
                  var wF = yF * strideDepth - xFCorner;
                  for (var yR = xRMin; yR < yRMax; ++yR) {
                    var wR = yR * strideHeight - xRCorner;
                    for (var yC = xCMin; yC < yCMax; ++yC) {
                      var wC = yC * strideWidth - xCCorner;
                      var dyOffset = dyS0 * b + dyS1 * yF + dyS2 * yR + dyS3 * yC;
                      var fltOffset = fltS0 * (filterDepth - 1 - wF) + fltS1 * (filterHeight - 1 - wR) + fltS2 * (filterWidth - 1 - wC) + fltS3 * d1;
                      for (var d2 = 0; d2 < outChannels; ++d2) {
                        var pixel = dyValues[dyOffset + d2];
                        var weight = fltValues[fltOffset + d2];
                        dotProd += pixel * weight;
                      }
                    }
                  }
                }
                dxValues[dxS0 * b + dxS1 * xF + dxS2 * xR + dxS3 * xC + d1] = dotProd;
              }
            }
          }
        }
      }
      return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);
    }
    var conv3DBackpropInputV2Config = {
      kernelName: tfjsCore.Conv3DBackpropInputV2,
      backendName: "cpu",
      kernelFunc: conv3DBackpropInputV2
    };
    var cos = unaryKernelFunc(tfjsCore.Cos, function(xi) {
      return Math.cos(xi);
    });
    var cosConfig = {
      kernelName: tfjsCore.Cos,
      backendName: "cpu",
      kernelFunc: cos
    };
    var cosh = unaryKernelFunc(tfjsCore.Cosh, function(xi) {
      return Math.cosh(xi);
    });
    var coshConfig = {
      kernelName: tfjsCore.Cosh,
      backendName: "cpu",
      kernelFunc: cosh
    };
    function cropAndResize(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var image = inputs.image, boxes = inputs.boxes, boxInd = inputs.boxInd;
      var cropSize = attrs.cropSize, method = attrs.method, extrapolationValue = attrs.extrapolationValue;
      var _a2 = __read(image.shape, 4), batch = _a2[0], imageHeight = _a2[1], imageWidth = _a2[2], numChannels = _a2[3];
      var numBoxes = boxes.shape[0];
      var _b = __read(cropSize, 2), cropHeight = _b[0], cropWidth = _b[1];
      var output = tfjsCore.buffer([numBoxes, cropHeight, cropWidth, numChannels], "float32");
      var boxVals = backend.data.get(boxes.dataId).values;
      var boxIndVals = backend.data.get(boxInd.dataId).values;
      var imageVals = backend.data.get(image.dataId).values;
      var inStride = tfjsCore.util.computeStrides(image.shape);
      var outStride = tfjsCore.util.computeStrides(output.shape);
      for (var b = 0; b < numBoxes; b++) {
        var startInd = b * 4;
        var y1 = boxVals[startInd];
        var x1 = boxVals[startInd + 1];
        var y2 = boxVals[startInd + 2];
        var x2 = boxVals[startInd + 3];
        var bInd = boxIndVals[b];
        if (bInd >= batch) {
          continue;
        }
        var heightScale = cropHeight > 1 ? (y2 - y1) * (imageHeight - 1) / (cropHeight - 1) : 0;
        var widthScale = cropWidth > 1 ? (x2 - x1) * (imageWidth - 1) / (cropWidth - 1) : 0;
        for (var y = 0; y < cropHeight; y++) {
          var yInd = cropHeight > 1 ? y1 * (imageHeight - 1) + y * heightScale : 0.5 * (y1 + y2) * (imageHeight - 1);
          if (yInd < 0 || yInd > imageHeight - 1) {
            for (var x = 0; x < cropWidth; x++) {
              for (var c = 0; c < numChannels; c++) {
                var ind = c + x * outStride[2] + y * outStride[1] + b * outStride[0];
                output.values[ind] = extrapolationValue;
              }
            }
            continue;
          }
          if (method === "bilinear") {
            var topInd = Math.floor(yInd);
            var bottomInd = Math.ceil(yInd);
            var yLerp = yInd - topInd;
            for (var x = 0; x < cropWidth; x++) {
              var xInd = cropWidth > 1 ? x1 * (imageWidth - 1) + x * widthScale : 0.5 * (x1 + x2) * (imageWidth - 1);
              if (xInd < 0 || xInd > imageWidth - 1) {
                for (var c = 0; c < numChannels; c++) {
                  var ind = c + x * outStride[2] + y * outStride[1] + b * outStride[0];
                  output.values[ind] = extrapolationValue;
                }
                continue;
              }
              var leftInd = Math.floor(xInd);
              var rightInd = Math.ceil(xInd);
              var xLerp = xInd - leftInd;
              for (var c = 0; c < numChannels; c++) {
                var ind = c + leftInd * inStride[2] + topInd * inStride[1] + bInd * inStride[0];
                var topLeft = imageVals[ind];
                ind = c + rightInd * inStride[2] + topInd * inStride[1] + bInd * inStride[0];
                var topRight = imageVals[ind];
                ind = c + leftInd * inStride[2] + bottomInd * inStride[1] + bInd * inStride[0];
                var bottomLeft = imageVals[ind];
                ind = c + rightInd * inStride[2] + bottomInd * inStride[1] + bInd * inStride[0];
                var bottomRight = imageVals[ind];
                var top = topLeft + (topRight - topLeft) * xLerp;
                var bottom = bottomLeft + (bottomRight - bottomLeft) * xLerp;
                ind = c + x * outStride[2] + y * outStride[1] + b * outStride[0];
                output.values[ind] = top + (bottom - top) * yLerp;
              }
            }
          } else {
            for (var x = 0; x < cropWidth; ++x) {
              var xInd = cropWidth > 1 ? x1 * (imageWidth - 1) + x * widthScale : 0.5 * (x1 + x2) * (imageWidth - 1);
              if (xInd < 0 || xInd > imageWidth - 1) {
                for (var c = 0; c < numChannels; c++) {
                  var ind = c + x * outStride[2] + y * outStride[1] + b * outStride[0];
                  output.values[ind] = extrapolationValue;
                }
                continue;
              }
              var closestX = Math.round(xInd);
              var closestY = Math.round(yInd);
              for (var c = 0; c < numChannels; c++) {
                var inInd = c + closestX * inStride[2] + closestY * inStride[1] + bInd * inStride[0];
                var outInd = c + x * outStride[2] + y * outStride[1] + b * outStride[0];
                output.values[outInd] = imageVals[inInd];
              }
            }
          }
        }
      }
      return backend.makeTensorInfo(output.shape, output.dtype, output.values);
    }
    var cropAndResizeConfig = {
      kernelName: tfjsCore.CropAndResize,
      backendName: "cpu",
      kernelFunc: cropAndResize
    };
    function cumprod(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis, exclusive = attrs.exclusive, reverse2 = attrs.reverse;
      assertNotComplex(x, "cumprod");
      var permutation = tfjsCore.backend_util.getAxesPermutation([axis], x.shape.length);
      var $x = x;
      if (permutation != null) {
        $x = transpose({ inputs: { x }, backend, attrs: { perm: permutation } });
      }
      var permutedAxis = tfjsCore.backend_util.getInnerMostAxes(1, x.shape.length)[0];
      if (permutedAxis !== $x.shape.length - 1) {
        throw new Error("backend.cumprod in CPU expects an inner-most " + "axis=".concat($x.shape.length - 1, " but got axis=").concat(permutedAxis));
      }
      var resultDtype = tfjsCore.upcastType($x.dtype, "int32");
      var vals = tfjsCore.util.makeOnesTypedArray(tfjsCore.util.sizeFromShape($x.shape), resultDtype);
      var aVals = backend.data.get($x.dataId).values;
      var finalDim = $x.shape[$x.shape.length - 1];
      var indexAdjuster = reverse2 ? function(i2, j2) {
        return i2 + finalDim - j2 - 1;
      } : function(i2, j2) {
        return i2 + j2;
      };
      for (var i = 0; i < aVals.length; i += finalDim) {
        for (var j = 0; j < finalDim; j++) {
          var idx = indexAdjuster(i, j);
          if (j === 0) {
            vals[idx] = exclusive ? 1 : aVals[idx];
          } else {
            var prevIdx = indexAdjuster(i, j - 1);
            vals[idx] = exclusive ? aVals[prevIdx] * vals[prevIdx] : aVals[idx] * vals[prevIdx];
          }
        }
      }
      var result = backend.makeTensorInfo($x.shape, resultDtype, vals);
      if (permutation != null) {
        var reversePermutation = tfjsCore.backend_util.getUndoAxesPermutation(permutation);
        var reverseTransposedResult = transpose({ inputs: { x: result }, backend, attrs: { perm: reversePermutation } });
        backend.disposeIntermediateTensorInfo(result);
        backend.disposeIntermediateTensorInfo($x);
        return reverseTransposedResult;
      }
      return result;
    }
    var cumprodConfig = {
      kernelName: tfjsCore.Cumprod,
      backendName: "cpu",
      kernelFunc: cumprod
    };
    function cumsum(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis, exclusive = attrs.exclusive, reverse2 = attrs.reverse;
      assertNotComplex(x, "cumsum");
      var permutation = tfjsCore.backend_util.getAxesPermutation([axis], x.shape.length);
      var $x = x;
      if (permutation != null) {
        $x = transpose({ inputs: { x }, backend, attrs: { perm: permutation } });
      }
      var permutedAxis = tfjsCore.backend_util.getInnerMostAxes(1, x.shape.length)[0];
      if (permutedAxis !== $x.shape.length - 1) {
        throw new Error("backend.cumsum in CPU expects an inner-most " + "axis=".concat($x.shape.length - 1, " but got axis=").concat(permutedAxis));
      }
      var resultDtype = tfjsCore.upcastType($x.dtype, "int32");
      var vals = tfjsCore.util.makeZerosTypedArray(tfjsCore.util.sizeFromShape($x.shape), resultDtype);
      var aVals = backend.data.get($x.dataId).values;
      var finalDim = $x.shape[$x.shape.length - 1];
      var indexAdjuster = reverse2 ? function(i2, j2) {
        return i2 + finalDim - j2 - 1;
      } : function(i2, j2) {
        return i2 + j2;
      };
      for (var i = 0; i < aVals.length; i += finalDim) {
        for (var j = 0; j < finalDim; j++) {
          var idx = indexAdjuster(i, j);
          if (j === 0) {
            vals[idx] = exclusive ? 0 : aVals[idx];
          } else {
            var prevIdx = indexAdjuster(i, j - 1);
            vals[idx] = exclusive ? aVals[prevIdx] + vals[prevIdx] : aVals[idx] + vals[prevIdx];
          }
        }
      }
      var result = backend.makeTensorInfo($x.shape, resultDtype, vals);
      if (permutation != null) {
        var reversePermutation = tfjsCore.backend_util.getUndoAxesPermutation(permutation);
        var reverseTransposedResult = transpose({ inputs: { x: result }, backend, attrs: { perm: reversePermutation } });
        backend.disposeIntermediateTensorInfo(result);
        backend.disposeIntermediateTensorInfo($x);
        return reverseTransposedResult;
      }
      return result;
    }
    var cumsumConfig = {
      kernelName: tfjsCore.Cumsum,
      backendName: "cpu",
      kernelFunc: cumsum
    };
    function denseBincount(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, weights = inputs.weights;
      var size = attrs.size, binaryOutput = attrs.binaryOutput;
      if (x.shape.length === 1) {
        var xVals = backend.data.get(x.dataId).values;
        var weightsVals = backend.data.get(weights.dataId).values;
        var outVals = bincountImpl(xVals, weightsVals, weights.dtype, weights.shape, size);
        return backend.makeTensorInfo([size], weights.dtype, outVals);
      } else if (x.shape.length === 2) {
        var xBuf = backend.bufferSync(x);
        var weightsBuf = backend.bufferSync(weights);
        var outBuf = bincountReduceImpl(xBuf, weightsBuf, size, binaryOutput);
        return backend.makeTensorInfo(outBuf.shape, weights.dtype, outBuf.values);
      }
      throw new Error("Error in denseBincount: input must be at most rank 2, but got rank" + "".concat(x.shape.length, "."));
    }
    var denseBincountConfig = {
      kernelName: tfjsCore.DenseBincount,
      backendName: "cpu",
      kernelFunc: denseBincount
    };
    function depthToSpace(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var blockSize = attrs.blockSize, dataFormat = attrs.dataFormat;
      tfjsCore.util.assert(dataFormat === "NHWC", function() {
        return "Only NHWC dataFormat supported on CPU for depthToSpace. Got ".concat(dataFormat);
      });
      var batchSize = x.shape[0];
      var inputHeight = x.shape[1];
      var inputWidth = x.shape[2];
      var inputDepth = x.shape[3];
      var outputHeight = inputHeight * blockSize;
      var outputWidth = inputWidth * blockSize;
      var outputDepth = inputDepth / (blockSize * blockSize);
      var xValues = backend.data.get(x.dataId).values;
      var result = new Float32Array(batchSize * outputHeight * outputWidth * outputDepth);
      var outputIdx = 0;
      for (var b = 0; b < batchSize; ++b) {
        for (var h = 0; h < outputHeight; ++h) {
          var inH = Math.floor(h / blockSize);
          var offsetH = h % blockSize;
          for (var w = 0; w < outputWidth; ++w) {
            var inW = Math.floor(w / blockSize);
            var offsetW = w % blockSize;
            var offsetD = (offsetH * blockSize + offsetW) * outputDepth;
            for (var d = 0; d < outputDepth; ++d) {
              var inD = d + offsetD;
              var inputIdx = inD + inputDepth * (inW + inputWidth * (inH + inputHeight * b));
              result[outputIdx++] = xValues[inputIdx];
            }
          }
        }
      }
      return backend.makeTensorInfo([batchSize, outputHeight, outputWidth, outputDepth], x.dtype, result);
    }
    var depthToSpaceConfig = {
      kernelName: tfjsCore.DepthToSpace,
      backendName: "cpu",
      kernelFunc: depthToSpace
    };
    function depthwiseConv2dNative(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, filter = inputs.filter;
      var strides = attrs.strides, pad = attrs.pad, dilations = attrs.dilations, dimRoundingMode = attrs.dimRoundingMode;
      assertNotComplex([x, filter], "depthwiseConv2DNative");
      var xStrides = tfjsCore.util.computeStrides(x.shape);
      var filterStrides = tfjsCore.util.computeStrides(filter.shape);
      var $dilations = dilations;
      if ($dilations == null) {
        $dilations = [1, 1];
      }
      tfjsCore.util.assert(tfjsCore.backend_util.eitherStridesOrDilationsAreOne(strides, $dilations), function() {
        return "Error in depthwiseConv2d: Either strides or dilations must be " + "1. Got strides ".concat(strides, " and dilations '").concat($dilations, "'");
      });
      var convInfo = tfjsCore.backend_util.computeConv2DInfo(
        x.shape,
        filter.shape,
        strides,
        $dilations,
        pad,
        dimRoundingMode,
        true
        /* depthwise */
      );
      var filterHeight = convInfo.filterHeight, filterWidth = convInfo.filterWidth, dilationHeight = convInfo.dilationHeight, dilationWidth = convInfo.dilationWidth, padInfo = convInfo.padInfo;
      var padLeft = padInfo.left;
      var padTop = padInfo.top;
      var chMul = convInfo.outChannels / convInfo.inChannels;
      var y = new tfjsCore.TensorBuffer(convInfo.outShape, x.dtype);
      var xVals = backend.data.get(x.dataId).values;
      var wVals = backend.data.get(filter.dataId).values;
      var yVals = y.values;
      for (var b = 0; b < convInfo.batchSize; ++b) {
        var xOffset1 = b * xStrides[0];
        var yOffset1 = b * y.strides[0];
        for (var yR = 0; yR < convInfo.outHeight; ++yR) {
          var yOffset2 = yOffset1 + yR * y.strides[1];
          var xRCorner = yR * convInfo.strideHeight - padTop;
          for (var wR = 0; wR < filterHeight; ++wR) {
            var xR = xRCorner + wR * dilationHeight;
            if (xR < 0 || xR >= convInfo.inHeight) {
              continue;
            }
            var wOffset1 = wR * filterStrides[0];
            var xOffset2 = xOffset1 + xR * xStrides[1];
            for (var yC = 0; yC < convInfo.outWidth; ++yC) {
              var yOffset3 = yOffset2 + yC * y.strides[2];
              var xCCorner = yC * convInfo.strideWidth - padLeft;
              for (var wC = 0; wC < filterWidth; ++wC) {
                var xC = xCCorner + wC * dilationWidth;
                if (xC < 0 || xC >= convInfo.inWidth) {
                  continue;
                }
                var wOffset2 = wOffset1 + wC * filterStrides[1];
                var xOffset3 = xOffset2 + xC * convInfo.inChannels;
                var yOffset4 = yOffset3;
                var wOffset3 = wOffset2;
                for (var d1 = 0; d1 < convInfo.inChannels; ++d1) {
                  var xVal = xVals[xOffset3 + d1];
                  for (var q = 0; q < chMul; ++q) {
                    yVals[yOffset4 + q] += xVal * wVals[wOffset3 + q];
                  }
                  yOffset4 += chMul;
                  wOffset3 += chMul;
                }
              }
            }
          }
        }
      }
      return backend.makeTensorInfo(y.shape, y.dtype, y.values);
    }
    var depthwiseConv2dNativeConfig = {
      kernelName: tfjsCore.DepthwiseConv2dNative,
      backendName: "cpu",
      kernelFunc: depthwiseConv2dNative
    };
    function depthwiseConv2dNativeBackpropFilter(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, dy = inputs.dy;
      var strides = attrs.strides, dilations = attrs.dilations, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode, filterShape = attrs.filterShape;
      assertNotComplex([x, dy], "depthwiseConv2dNativeBackpropFilter");
      var convInfo = tfjsCore.backend_util.computeConv2DInfo(
        x.shape,
        filterShape,
        strides,
        dilations,
        pad,
        dimRoundingMode,
        true
        /* depthwise */
      );
      var strideHeight = convInfo.strideHeight, strideWidth = convInfo.strideWidth, filterHeight = convInfo.filterHeight, filterWidth = convInfo.filterWidth;
      var dW = new tfjsCore.TensorBuffer(convInfo.filterShape, "float32");
      var leftPad = convInfo.padInfo.left;
      var topPad = convInfo.padInfo.top;
      var chMul = convInfo.outChannels / convInfo.inChannels;
      var xVals = backend.data.get(x.dataId).values;
      var xBuf = new tfjsCore.TensorBuffer(x.shape, x.dtype, xVals);
      var dyVals = backend.data.get(dy.dataId).values;
      var dyBuf = new tfjsCore.TensorBuffer(dy.shape, dy.dtype, dyVals);
      for (var wR = 0; wR < filterHeight; ++wR) {
        var yRMin = Math.max(0, Math.ceil((topPad - wR) / strideHeight));
        var yRMax = Math.min(convInfo.outHeight, (convInfo.inHeight + topPad - wR) / strideHeight);
        for (var wC = 0; wC < filterWidth; ++wC) {
          var yCMin = Math.max(0, Math.ceil((leftPad - wC) / strideWidth));
          var yCMax = Math.min(convInfo.outWidth, (convInfo.inWidth + leftPad - wC) / strideWidth);
          for (var d2 = 0; d2 < convInfo.outChannels; ++d2) {
            var d1 = Math.trunc(d2 / chMul);
            var dm = d2 % chMul;
            var dotProd = 0;
            for (var b = 0; b < convInfo.batchSize; ++b) {
              for (var yR = yRMin; yR < yRMax; ++yR) {
                var xR = wR + yR * strideHeight - topPad;
                for (var yC = yCMin; yC < yCMax; ++yC) {
                  var xC = wC + yC * strideWidth - leftPad;
                  dotProd += xBuf.get(b, xR, xC, d1) * dyBuf.get(b, yR, yC, d2);
                }
              }
            }
            dW.set(dotProd, wR, wC, d1, dm);
          }
        }
      }
      return backend.makeTensorInfo(dW.shape, dW.dtype, dW.values);
    }
    var depthwiseConv2dNativeBackpropFilterConfig = {
      kernelName: tfjsCore.DepthwiseConv2dNativeBackpropFilter,
      backendName: "cpu",
      kernelFunc: depthwiseConv2dNativeBackpropFilter
    };
    function depthwiseConv2dNativeBackpropInput(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var dy = inputs.dy, filter = inputs.filter;
      var strides = attrs.strides, dilations = attrs.dilations, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode, inputShape = attrs.inputShape;
      assertNotComplex([dy, filter], "depthwiseConv2DNativeBackpropInput");
      var dyStrides = tfjsCore.util.computeStrides(dy.shape);
      var filterStrides = tfjsCore.util.computeStrides(filter.shape);
      var convInfo = tfjsCore.backend_util.computeConv2DInfo(
        inputShape,
        filter.shape,
        strides,
        dilations,
        pad,
        dimRoundingMode,
        true
        /* depthwise */
      );
      var dx = new tfjsCore.TensorBuffer(convInfo.inShape, "float32");
      var dxValues = dx.values;
      var _a2 = __read(dx.strides, 3), dxS0 = _a2[0], dxS1 = _a2[1], dxS2 = _a2[2];
      var dyValues = backend.data.get(dy.dataId).values;
      var _b = __read(dyStrides, 3), dyS0 = _b[0], dyS1 = _b[1], dyS2 = _b[2];
      var fltValues = backend.data.get(filter.dataId).values;
      var _c = __read(filterStrides, 3), fltS0 = _c[0], fltS1 = _c[1], fltS2 = _c[2];
      var batchSize = convInfo.batchSize, filterHeight = convInfo.filterHeight, filterWidth = convInfo.filterWidth, inChannels = convInfo.inChannels, inHeight = convInfo.inHeight, inWidth = convInfo.inWidth, outChannels = convInfo.outChannels, outHeight = convInfo.outHeight, outWidth = convInfo.outWidth, strideHeight = convInfo.strideHeight, strideWidth = convInfo.strideWidth;
      var topPad = filterHeight - 1 - convInfo.padInfo.top;
      var leftPad = filterWidth - 1 - convInfo.padInfo.left;
      var chMul = outChannels / inChannels;
      for (var b = 0; b < batchSize; ++b) {
        for (var d1 = 0; d1 < inChannels; ++d1) {
          for (var xR = 0; xR < inHeight; ++xR) {
            var xRCorner = xR - topPad;
            var xRMin = Math.max(0, Math.ceil(xRCorner / strideHeight));
            var yRMax = Math.min(outHeight, (filterHeight + xRCorner) / strideHeight);
            for (var xC = 0; xC < inWidth; ++xC) {
              var xCCorner = xC - leftPad;
              var xCMin = Math.max(0, Math.ceil(xCCorner / strideWidth));
              var yCMax = Math.min(outWidth, (filterWidth + xCCorner) / strideWidth);
              var dotProd = 0;
              for (var yR = xRMin; yR < yRMax; ++yR) {
                var wR = yR * strideHeight - xRCorner;
                for (var yC = xCMin; yC < yCMax; ++yC) {
                  var wC = yC * strideWidth - xCCorner;
                  var dyOffset = dyS0 * b + dyS1 * yR + dyS2 * yC;
                  var fltOffset = fltS0 * (filterHeight - 1 - wR) + fltS1 * (filterWidth - 1 - wC) + fltS2 * d1;
                  for (var dm = 0; dm < chMul; ++dm) {
                    var d2 = d1 * chMul + dm;
                    var pixel = dyValues[dyOffset + d2];
                    var weight = fltValues[fltOffset + dm];
                    dotProd += pixel * weight;
                  }
                }
              }
              dxValues[dxS0 * b + dxS1 * xR + dxS2 * xC + d1] = dotProd;
            }
          }
        }
      }
      return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);
    }
    var depthwiseConv2dNativeBackpropInputConfig = {
      kernelName: tfjsCore.DepthwiseConv2dNativeBackpropInput,
      backendName: "cpu",
      kernelFunc: depthwiseConv2dNativeBackpropInput
    };
    function diag(args) {
      var inputs = args.inputs, backend = args.backend;
      var x = inputs.x;
      var xSize = tfjsCore.util.sizeFromShape(x.shape);
      var xVals = backend.data.get(x.dataId).values;
      var outBuf = tfjsCore.buffer([xSize, xSize], x.dtype);
      var vals = outBuf.values;
      for (var i = 0; i < xVals.length; i++) {
        vals[i * xSize + i] = xVals[i];
      }
      var outShape = __spreadArray(__spreadArray([], __read(x.shape), false), __read(x.shape), false);
      return backend.makeTensorInfo(outShape, outBuf.dtype, outBuf.values);
    }
    var diagConfig = {
      kernelName: tfjsCore.Diag,
      backendName: "cpu",
      kernelFunc: diag
    };
    var dilation2DConfig = {
      kernelName: tfjsCore.Dilation2D,
      backendName: "cpu",
      kernelFunc: function(_a2) {
        var inputs = _a2.inputs, backend = _a2.backend, attrs = _a2.attrs;
        var x = inputs.x, filter = inputs.filter;
        var strides = attrs.strides, pad = attrs.pad, dilations = attrs.dilations;
        var cpuBackend = backend;
        var xVals = cpuBackend.data.get(x.dataId).values;
        var xRank = x.shape.length;
        var filterVals = cpuBackend.data.get(filter.dataId).values;
        var filterRank = filter.shape.length;
        var _b = tfjsCore.backend_util.computeDilation2DInfo(x.shape, filter.shape, strides, pad, "NHWC", dilations), batchSize = _b.batchSize, inHeight = _b.inHeight, inWidth = _b.inWidth, inChannels = _b.inChannels, outHeight = _b.outHeight, outWidth = _b.outWidth, padInfo = _b.padInfo, strideHeight = _b.strideHeight, strideWidth = _b.strideWidth, filterHeight = _b.filterHeight, filterWidth = _b.filterWidth, dilationHeight = _b.dilationHeight, dilationWidth = _b.dilationWidth, outShape = _b.outShape;
        var outSize = tfjsCore.util.sizeFromShape(outShape);
        var outRank = outShape.length;
        var outputVals = tfjsCore.util.getArrayFromDType(x.dtype, outSize);
        for (var b = 0; b < batchSize; ++b) {
          for (var hOut = 0; hOut < outHeight; ++hOut) {
            var hBeg = hOut * strideHeight - padInfo.top;
            for (var wOut = 0; wOut < outWidth; ++wOut) {
              var wBeg = wOut * strideWidth - padInfo.left;
              for (var d = 0; d < inChannels; ++d) {
                var curVal = Number.MIN_SAFE_INTEGER;
                for (var h = 0; h < filterHeight; ++h) {
                  var hIn = hBeg + h * dilationHeight;
                  if (hIn >= 0 && hIn < inHeight) {
                    for (var w = 0; w < filterWidth; ++w) {
                      var wIn = wBeg + w * dilationWidth;
                      if (wIn >= 0 && wIn < inWidth) {
                        var xIndex = tfjsCore.util.locToIndex([b, hIn, wIn, d], xRank, tfjsCore.util.computeStrides(x.shape));
                        var filterIndex = tfjsCore.util.locToIndex([h, w, d], filterRank, tfjsCore.util.computeStrides(filter.shape));
                        var val = xVals[xIndex] + filterVals[filterIndex];
                        if (val > curVal) {
                          curVal = val;
                        }
                      }
                    }
                  }
                }
                var outputIndex = tfjsCore.util.locToIndex([b, hOut, wOut, d], outRank, tfjsCore.util.computeStrides(outShape));
                outputVals[outputIndex] = curVal;
              }
            }
          }
        }
        var dataId = cpuBackend.write(tfjsCore.util.toTypedArray(outputVals, x.dtype), outShape, x.dtype);
        return { dataId, shape: outShape, dtype: x.dtype };
      }
    };
    var dilation2DBackpropFilterConfig = {
      kernelName: tfjsCore.Dilation2DBackpropFilter,
      backendName: "cpu",
      kernelFunc: function(_a2) {
        var inputs = _a2.inputs, backend = _a2.backend, attrs = _a2.attrs;
        var x = inputs.x, filter = inputs.filter, dy = inputs.dy;
        var strides = attrs.strides, pad = attrs.pad, dilations = attrs.dilations;
        var cpuBackend = backend;
        var $x = tfjsCore.util.toNestedArray(x.shape, cpuBackend.data.get(x.dataId).values);
        var $filter = tfjsCore.util.toNestedArray(filter.shape, cpuBackend.data.get(filter.dataId).values);
        var _b = tfjsCore.backend_util.computeDilation2DInfo(x.shape, filter.shape, strides, pad, "NHWC", dilations), batchSize = _b.batchSize, inHeight = _b.inHeight, inWidth = _b.inWidth, inChannels = _b.inChannels, outHeight = _b.outHeight, outWidth = _b.outWidth, padInfo = _b.padInfo, strideHeight = _b.strideHeight, strideWidth = _b.strideWidth, filterHeight = _b.filterHeight, filterWidth = _b.filterWidth, dilationHeight = _b.dilationHeight, dilationWidth = _b.dilationWidth, outShape = _b.outShape;
        tfjsCore.util.assert(dy.rank === outShape.length, function() {
          return "Error in ".concat(tfjsCore.Dilation2DBackpropFilter, ", dy ") + "must have the same rank as output ".concat(outShape.length, ", but got ") + "".concat(dy.rank);
        });
        var $dy = tfjsCore.util.toNestedArray(outShape, cpuBackend.data.get(dy.dataId).values);
        var gradients = tfjsCore.util.makeZerosNestedTypedArray(filter.shape, filter.dtype);
        for (var b = 0; b < batchSize; ++b) {
          for (var hOut = 0; hOut < outHeight; ++hOut) {
            var hBeg = hOut * strideHeight - padInfo.top;
            for (var wOut = 0; wOut < outWidth; ++wOut) {
              var wBeg = wOut * strideWidth - padInfo.left;
              for (var d = 0; d < inChannels; ++d) {
                var curVal = Number.MIN_SAFE_INTEGER;
                var hMax = 0;
                var wMax = 0;
                for (var h = 0; h < filterHeight; ++h) {
                  var hIn = hBeg + h * dilationHeight;
                  if (hIn >= 0 && hIn < inHeight) {
                    for (var w = 0; w < filterWidth; ++w) {
                      var wIn = wBeg + w * dilationWidth;
                      if (wIn >= 0 && wIn < inWidth) {
                        var val = $x[b][hIn][wIn][d] + $filter[h][w][d];
                        if (val > curVal) {
                          curVal = val;
                          hMax = h;
                          wMax = w;
                        }
                      }
                    }
                  }
                }
                gradients[hMax][wMax][d] += $dy[b][hOut][wOut][d];
              }
            }
          }
        }
        var dataId = cpuBackend.write(tfjsCore.util.toTypedArray(gradients, x.dtype), filter.shape, filter.dtype);
        return { dataId, shape: filter.shape, dtype: filter.dtype };
      }
    };
    var dilation2DBackpropInputConfig = {
      kernelName: tfjsCore.Dilation2DBackpropInput,
      backendName: "cpu",
      kernelFunc: function(_a2) {
        var inputs = _a2.inputs, backend = _a2.backend, attrs = _a2.attrs;
        var x = inputs.x, filter = inputs.filter, dy = inputs.dy;
        var strides = attrs.strides, pad = attrs.pad, dilations = attrs.dilations;
        var cpuBackend = backend;
        var $x = tfjsCore.util.toNestedArray(x.shape, cpuBackend.data.get(x.dataId).values);
        var $filter = tfjsCore.util.toNestedArray(filter.shape, cpuBackend.data.get(filter.dataId).values);
        var _b = tfjsCore.backend_util.computeDilation2DInfo(x.shape, filter.shape, strides, pad, "NHWC", dilations), batchSize = _b.batchSize, inHeight = _b.inHeight, inWidth = _b.inWidth, inChannels = _b.inChannels, outHeight = _b.outHeight, outWidth = _b.outWidth, padInfo = _b.padInfo, strideHeight = _b.strideHeight, strideWidth = _b.strideWidth, filterHeight = _b.filterHeight, filterWidth = _b.filterWidth, dilationHeight = _b.dilationHeight, dilationWidth = _b.dilationWidth, outShape = _b.outShape;
        tfjsCore.util.assert(dy.rank === outShape.length, function() {
          return "Error in ".concat(tfjsCore.Dilation2DBackpropInput, ", dy ") + "must have the same rank as output ".concat(outShape.length, ", but got ") + "".concat(dy.rank);
        });
        var $dy = tfjsCore.util.toNestedArray(outShape, cpuBackend.data.get(dy.dataId).values);
        var gradients = tfjsCore.util.makeZerosNestedTypedArray(x.shape, x.dtype);
        for (var b = 0; b < batchSize; ++b) {
          for (var hOut = 0; hOut < outHeight; ++hOut) {
            var hBeg = hOut * strideHeight - padInfo.top;
            for (var wOut = 0; wOut < outWidth; ++wOut) {
              var wBeg = wOut * strideWidth - padInfo.left;
              for (var d = 0; d < inChannels; ++d) {
                var curVal = Number.MIN_SAFE_INTEGER;
                var hInMax = hBeg < 0 ? 0 : hBeg;
                var wInMax = wBeg < 0 ? 0 : wBeg;
                for (var h = 0; h < filterHeight; ++h) {
                  var hIn = hBeg + h * dilationHeight;
                  if (hIn >= 0 && hIn < inHeight) {
                    for (var w = 0; w < filterWidth; ++w) {
                      var wIn = wBeg + w * dilationWidth;
                      if (wIn >= 0 && wIn < inWidth) {
                        var val = $x[b][hIn][wIn][d] + $filter[h][w][d];
                        if (val > curVal) {
                          curVal = val;
                          hInMax = hIn;
                          wInMax = wIn;
                        }
                      }
                    }
                  }
                }
                gradients[b][hInMax][wInMax][d] += $dy[b][hOut][wOut][d];
              }
            }
          }
        }
        var dataId = cpuBackend.write(tfjsCore.util.toTypedArray(gradients, x.dtype), x.shape, x.dtype);
        return { dataId, shape: x.shape, dtype: x.dtype };
      }
    };
    function draw(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var image = inputs.image;
      var canvas = attrs.canvas, options = attrs.options;
      var _a2 = options || {}, contextOptions = _a2.contextOptions, imageOptions = _a2.imageOptions;
      var alpha = (imageOptions === null || imageOptions === void 0 ? void 0 : imageOptions.alpha) || 1;
      var contextType = (contextOptions === null || contextOptions === void 0 ? void 0 : contextOptions.contextType) || "2d";
      if (contextType !== "2d") {
        throw new Error("Context type ".concat(contextOptions.contextType, " is not supported by the CPU backend."));
      }
      var ctx = canvas.getContext(contextType, (contextOptions === null || contextOptions === void 0 ? void 0 : contextOptions.contextAttributes) || {});
      if (ctx == null) {
        throw new Error("Could not get the context with ".concat(contextType, " type."));
      }
      var _b = __read(image.shape.slice(0, 2), 2), height = _b[0], width = _b[1];
      var depth = image.shape.length === 2 ? 1 : image.shape[2];
      var data = backend.data.get(image.dataId).values;
      var multiplier = image.dtype === "float32" ? 255 : 1;
      var bytes = new Uint8ClampedArray(width * height * 4);
      for (var i = 0; i < height * width; ++i) {
        var rgba = [0, 0, 0, 255 * alpha];
        for (var d = 0; d < depth; d++) {
          var value = data[i * depth + d];
          if (image.dtype === "float32") {
            if (value < 0 || value > 1) {
              throw new Error("Tensor values for a float32 Tensor must be in the " + "range [0 - 1] but encountered ".concat(value, "."));
            }
          } else if (image.dtype === "int32") {
            if (value < 0 || value > 255) {
              throw new Error("Tensor values for a int32 Tensor must be in the " + "range [0 - 255] but encountered ".concat(value, "."));
            }
          }
          if (depth === 1) {
            rgba[0] = value * multiplier;
            rgba[1] = value * multiplier;
            rgba[2] = value * multiplier;
          } else {
            rgba[d] = value * multiplier;
          }
        }
        var j = i * 4;
        bytes[j + 0] = Math.round(rgba[0]);
        bytes[j + 1] = Math.round(rgba[1]);
        bytes[j + 2] = Math.round(rgba[2]);
        bytes[j + 3] = Math.round(rgba[3]);
      }
      canvas.width = width;
      canvas.height = height;
      var imageData = new ImageData(bytes, width, height);
      ctx.putImageData(imageData, 0, 0);
      return image;
    }
    var drawConfig = {
      kernelName: tfjsCore.Draw,
      backendName: "cpu",
      kernelFunc: draw
    };
    function sum(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis, keepDims = attrs.keepDims;
      assertNotComplex(x, "sum");
      var $x;
      if (x.dtype === "bool") {
        $x = cast({ inputs: { x }, backend, attrs: { dtype: "int32" } });
      } else {
        $x = identity({ inputs: { x }, backend });
      }
      var xRank = $x.shape.length;
      var axes = tfjsCore.util.parseAxisParam(axis, $x.shape);
      var permutation = tfjsCore.backend_util.getAxesPermutation(axes, xRank);
      var reductionAxes = axes;
      var permutedX = $x;
      if (permutation != null) {
        permutedX = transpose({ inputs: { x: $x }, backend, attrs: { perm: permutation } });
        reductionAxes = tfjsCore.backend_util.getInnerMostAxes(reductionAxes.length, xRank);
      }
      tfjsCore.backend_util.assertAxesAreInnerMostDims("sum", reductionAxes, permutedX.shape.length);
      var _a2 = __read(tfjsCore.backend_util.computeOutAndReduceShapes(permutedX.shape, reductionAxes), 2), outShape = _a2[0], reduceShape = _a2[1];
      var resultDtype = tfjsCore.backend_util.upcastType(permutedX.dtype, "int32");
      var result = zeros(backend, outShape, resultDtype);
      var reduceSize = tfjsCore.util.sizeFromShape(reduceShape);
      var vals = backend.data.get(result.dataId).values;
      var aVals = backend.data.get(permutedX.dataId).values;
      for (var i = 0; i < vals.length; ++i) {
        var offset = i * reduceSize;
        var sum_1 = 0;
        for (var j = 0; j < reduceSize; ++j) {
          sum_1 += aVals[offset + j];
        }
        vals[i] = sum_1;
      }
      if (keepDims) {
        var newShape = tfjsCore.backend_util.expandShapeToKeepDim(result.shape, axes);
        var oldResult = result;
        result = reshape({ inputs: { x: result }, backend, attrs: { shape: newShape } });
        backend.disposeIntermediateTensorInfo(oldResult);
      }
      backend.disposeIntermediateTensorInfo($x);
      if (permutation != null) {
        backend.disposeIntermediateTensorInfo(permutedX);
      }
      return result;
    }
    var sumConfig = {
      kernelName: tfjsCore.Sum,
      backendName: "cpu",
      kernelFunc: sum
    };
    function einsum(args) {
      var e_12, _a2, e_2, _b;
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var equation = attrs.equation;
      var tensors = inputs;
      var _c = tfjsCore.backend_util.decodeEinsumEquation(equation, tensors.length), allDims = _c.allDims, summedDims = _c.summedDims, idDims = _c.idDims;
      tfjsCore.backend_util.checkEinsumDimSizes(allDims.length, idDims, tensors);
      var _d = tfjsCore.backend_util.getEinsumComputePath(summedDims, idDims), path = _d.path, steps = _d.steps;
      var nSteps = steps.length;
      var out = null;
      var numDimsRemaining = allDims.length;
      var tensorsToDispose = [];
      for (var i = 0; i < nSteps; ++i) {
        try {
          for (var _e = (e_12 = void 0, __values(steps[i])), _f = _e.next(); !_f.done; _f = _e.next()) {
            var idTerm = _f.value;
            var _g = tfjsCore.backend_util.getEinsumPermutation(numDimsRemaining, idDims[idTerm]), perm = _g.permutationIndices, dimsToExpand = _g.expandDims;
            var x = void 0;
            if (tfjsCore.backend_util.isIdentityPermutation(perm)) {
              x = tensors[idTerm];
            } else {
              x = transpose({ inputs: { x: tensors[idTerm] }, backend, attrs: { perm } });
              tensorsToDispose.push(x);
            }
            var targetShape = x.shape.slice();
            for (var k = 0; k < dimsToExpand.length; ++k) {
              targetShape.splice(dimsToExpand[k], 0, 1);
            }
            if (!tfjsCore.util.arraysEqual(x.shape, targetShape)) {
              x = reshape({ inputs: { x }, backend, attrs: { shape: targetShape } });
              tensorsToDispose.push(x);
            }
            if (out === null) {
              out = x;
            } else {
              out = multiply({ inputs: { a: x, b: out }, backend });
              tensorsToDispose.push(out);
            }
          }
        } catch (e_1_1) {
          e_12 = { error: e_1_1 };
        } finally {
          try {
            if (_f && !_f.done && (_a2 = _e.return)) _a2.call(_e);
          } finally {
            if (e_12) throw e_12.error;
          }
        }
        if (i < nSteps - 1) {
          if (path[i] >= 0) {
            out = sum({
              inputs: { x: out },
              backend,
              attrs: {
                axis: path[i] - (allDims.length - numDimsRemaining),
                keepDims: false
              }
            });
            tensorsToDispose.push(out);
          }
          numDimsRemaining--;
        }
      }
      try {
        for (var tensorsToDispose_1 = __values(tensorsToDispose), tensorsToDispose_1_1 = tensorsToDispose_1.next(); !tensorsToDispose_1_1.done; tensorsToDispose_1_1 = tensorsToDispose_1.next()) {
          var tensorInfo = tensorsToDispose_1_1.value;
          if (tensorInfo === out) {
            continue;
          }
          backend.disposeIntermediateTensorInfo(tensorInfo);
        }
      } catch (e_2_1) {
        e_2 = { error: e_2_1 };
      } finally {
        try {
          if (tensorsToDispose_1_1 && !tensorsToDispose_1_1.done && (_b = tensorsToDispose_1.return)) _b.call(tensorsToDispose_1);
        } finally {
          if (e_2) throw e_2.error;
        }
      }
      return out;
    }
    var einsumConfig = {
      kernelName: tfjsCore.Einsum,
      backendName: "cpu",
      kernelFunc: einsum
    };
    function eluGrad(args) {
      var inputs = args.inputs, backend = args.backend;
      var dy = inputs.dy, y = inputs.y;
      assertNotComplex([dy, y], "eluGrad");
      var resultValues = new Float32Array(tfjsCore.util.sizeFromShape(y.shape));
      var values = backend.data.get(y.dataId).values;
      var dyValues = backend.data.get(dy.dataId).values;
      for (var i = 0; i < values.length; ++i) {
        var v = values[i];
        if (v >= 0) {
          resultValues[i] = dyValues[i];
        } else {
          resultValues[i] = dyValues[i] * (v + 1);
        }
      }
      return backend.makeTensorInfo(y.shape, "float32", resultValues);
    }
    var eluGradConfig = {
      kernelName: tfjsCore.EluGrad,
      backendName: "cpu",
      kernelFunc: eluGrad
    };
    var p = tfjsCore.backend_util.ERF_P;
    var a1 = tfjsCore.backend_util.ERF_A1;
    var a2 = tfjsCore.backend_util.ERF_A2;
    var a3 = tfjsCore.backend_util.ERF_A3;
    var a4 = tfjsCore.backend_util.ERF_A4;
    var a5 = tfjsCore.backend_util.ERF_A5;
    var erf = unaryKernelFunc(tfjsCore.Erf, function(xi) {
      var sign2 = Math.sign(xi);
      var v = Math.abs(xi);
      var t = 1 / (1 + p * v);
      return sign2 * (1 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-v * v));
    });
    var erfConfig = {
      kernelName: tfjsCore.Erf,
      backendName: "cpu",
      kernelFunc: erf
    };
    function expandDims(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var input = inputs.input;
      var dim = attrs.dim;
      var inputRank = input.shape.length;
      var newShape = input.shape.slice();
      var $dim = dim;
      if (dim < 0) {
        tfjsCore.util.assert(-(inputRank + 1) <= dim, function() {
          return "Axis must be in the interval [".concat(-(inputRank + 1), ", ").concat(inputRank, "]");
        });
        $dim = inputRank + dim + 1;
      }
      newShape.splice($dim, 0, 1);
      return reshape({ inputs: { x: input }, backend, attrs: { shape: newShape } });
    }
    var expandDimsConfig = {
      kernelName: tfjsCore.ExpandDims,
      backendName: "cpu",
      kernelFunc: expandDims
    };
    var realDivImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a / b;
    });
    var div = binaryKernelFunc(tfjsCore.RealDiv, realDivImpl);
    var realDivConfig = {
      kernelName: tfjsCore.RealDiv,
      backendName: "cpu",
      kernelFunc: div
    };
    function fftBatch(input, inverse, cpuBackend) {
      var inputShape = input.shape;
      var batch = inputShape[0];
      var innerDim = inputShape[1];
      var inputVals = cpuBackend.data.get(input.dataId);
      var real2D = inputVals.complexTensorInfos.real;
      var imag2D = inputVals.complexTensorInfos.imag;
      var resultShape = [batch, innerDim];
      var resultSize = tfjsCore.util.sizeFromShape(resultShape);
      var resultReal = tfjsCore.util.getTypedArrayFromDType("float32", resultSize);
      var resultImag = tfjsCore.util.getTypedArrayFromDType("float32", resultSize);
      for (var b = 0; b < batch; b++) {
        var r = slice({
          inputs: { x: real2D },
          backend: cpuBackend,
          attrs: { begin: [b, 0], size: [1, innerDim] }
        });
        var i = slice({
          inputs: { x: imag2D },
          backend: cpuBackend,
          attrs: { begin: [b, 0], size: [1, innerDim] }
        });
        var input_1 = complex({ inputs: { real: r, imag: i }, backend: cpuBackend });
        var _a2 = fftImpl(input_1, inverse, cpuBackend), real_1 = _a2.real, imag_1 = _a2.imag;
        var res = tfjsCore.backend_util.mergeRealAndImagArrays(real_1, imag_1);
        for (var d = 0; d < innerDim; d++) {
          var c = tfjsCore.backend_util.getComplexWithIndex(res, d);
          resultReal[b * innerDim + d] = c.real;
          resultImag[b * innerDim + d] = c.imag;
        }
        cpuBackend.disposeIntermediateTensorInfo(r);
        cpuBackend.disposeIntermediateTensorInfo(i);
        cpuBackend.disposeIntermediateTensorInfo(input_1);
      }
      var $realInfo = cpuBackend.makeTensorInfo(resultShape, "float32", resultReal);
      var $imagInfo = cpuBackend.makeTensorInfo(resultShape, "float32", resultImag);
      var result = complex({ inputs: { real: $realInfo, imag: $imagInfo }, backend: cpuBackend });
      cpuBackend.disposeIntermediateTensorInfo($realInfo);
      cpuBackend.disposeIntermediateTensorInfo($imagInfo);
      return result;
    }
    function fftImpl(input, inverse, cpuBackend) {
      var inputSize = tfjsCore.util.sizeFromShape(input.shape);
      var inputVals = cpuBackend.data.get(input.dataId);
      var realVals = cpuBackend.data.get(inputVals.complexTensorInfos.real.dataId).values;
      var imagVals = cpuBackend.data.get(inputVals.complexTensorInfos.imag.dataId).values;
      if (isExponentOf2(inputSize)) {
        var result = fftRadix2(realVals, imagVals, inputSize, inverse, cpuBackend);
        var resultShape = [input.shape[0], input.shape[1]];
        if (inverse) {
          var realInfo = cpuBackend.makeTensorInfo(resultShape, "float32", result.real);
          var imagInfo = cpuBackend.makeTensorInfo(resultShape, "float32", result.imag);
          var sizeInfo = cpuBackend.makeTensorInfo([], "float32", tfjsCore.util.createScalarValue(inputSize, "float32"));
          var sizeInfoCopy = identity({ inputs: { x: sizeInfo }, backend: cpuBackend });
          var divRealInfo = realDivConfig.kernelFunc({ inputs: { a: realInfo, b: sizeInfo }, backend: cpuBackend });
          var divImagInfo = realDivConfig.kernelFunc({ inputs: { a: imagInfo, b: sizeInfoCopy }, backend: cpuBackend });
          var divRealVals = cpuBackend.data.get(divRealInfo.dataId).values;
          var divImagVals = cpuBackend.data.get(divImagInfo.dataId).values;
          cpuBackend.disposeIntermediateTensorInfo(realInfo);
          cpuBackend.disposeIntermediateTensorInfo(imagInfo);
          cpuBackend.disposeIntermediateTensorInfo(sizeInfo);
          cpuBackend.disposeIntermediateTensorInfo(sizeInfoCopy);
          cpuBackend.disposeIntermediateTensorInfo(divRealInfo);
          cpuBackend.disposeIntermediateTensorInfo(divImagInfo);
          return { real: divRealVals, imag: divImagVals };
        }
        return result;
      } else {
        var data = tfjsCore.backend_util.mergeRealAndImagArrays(realVals, imagVals);
        var rawOutput = fourierTransformByMatmul(data, inputSize, inverse);
        return tfjsCore.backend_util.splitRealAndImagArrays(rawOutput);
      }
    }
    function isExponentOf2(size) {
      return (size & size - 1) === 0;
    }
    function fftRadix2(realVals, imagVals, size, inverse, cpuBackend) {
      if (size === 1) {
        return { real: realVals, imag: imagVals };
      }
      var data = tfjsCore.backend_util.mergeRealAndImagArrays(realVals, imagVals);
      var half = size / 2;
      var evenComplex = tfjsCore.backend_util.complexWithEvenIndex(data);
      var evenRealVals = evenComplex.real;
      var evenImagVals = evenComplex.imag;
      var evenShape = [evenRealVals.length];
      var evenRealInfo = cpuBackend.makeTensorInfo(evenShape, "float32", evenRealVals);
      var evenImagInfo = cpuBackend.makeTensorInfo(evenShape, "float32", evenImagVals);
      var evenTensorInfo = complex({ inputs: { real: evenRealInfo, imag: evenImagInfo }, backend: cpuBackend });
      var oddComplex = tfjsCore.backend_util.complexWithOddIndex(data);
      var oddRealVals = oddComplex.real;
      var oddImagVals = oddComplex.imag;
      var oddShape = [oddRealVals.length];
      var oddRealInfo = cpuBackend.makeTensorInfo(oddShape, "float32", oddRealVals);
      var oddImagInfo = cpuBackend.makeTensorInfo(oddShape, "float32", oddImagVals);
      var oddTensorInfo = complex({ inputs: { real: oddRealInfo, imag: oddImagInfo }, backend: cpuBackend });
      var $evenComplex = fftRadix2(evenRealVals, evenImagVals, half, inverse, cpuBackend);
      var $evenRealVals = $evenComplex.real;
      var $evenImagVals = $evenComplex.imag;
      var $evenShape = [$evenRealVals.length];
      var $evenRealInfo = cpuBackend.makeTensorInfo($evenShape, "float32", $evenRealVals);
      var $evenImagInfo = cpuBackend.makeTensorInfo($evenShape, "float32", $evenImagVals);
      var $evenTensorInfo = complex({
        inputs: { real: $evenRealInfo, imag: $evenImagInfo },
        backend: cpuBackend
      });
      var $oddComplex = fftRadix2(oddRealVals, oddImagVals, half, inverse, cpuBackend);
      var $oddRealVals = $oddComplex.real;
      var $oddImagVals = $oddComplex.imag;
      var $oddShape = [$oddRealVals.length];
      var $oddRealInfo = cpuBackend.makeTensorInfo($oddShape, "float32", $oddRealVals);
      var $oddImagInfo = cpuBackend.makeTensorInfo($oddShape, "float32", $oddImagVals);
      var $oddTensorInfo = complex({ inputs: { real: $oddRealInfo, imag: $oddImagInfo }, backend: cpuBackend });
      var e = tfjsCore.backend_util.exponents(size, inverse);
      var eShape = [e.real.length];
      var eRealInfo = cpuBackend.makeTensorInfo(eShape, "float32", e.real);
      var eImagInfo = cpuBackend.makeTensorInfo(eShape, "float32", e.imag);
      var complexInfo = complex({ inputs: { real: eRealInfo, imag: eImagInfo }, backend: cpuBackend });
      var exponentInfo = multiply({ inputs: { a: complexInfo, b: $oddTensorInfo }, backend: cpuBackend });
      var addPart = add({
        inputs: { a: $evenTensorInfo, b: exponentInfo },
        backend: cpuBackend
      });
      var subPart = sub({
        inputs: { a: $evenTensorInfo, b: exponentInfo },
        backend: cpuBackend
      });
      var addPartReal = real({ inputs: { input: addPart }, backend: cpuBackend });
      var subPartReal = real({ inputs: { input: subPart }, backend: cpuBackend });
      var addPartImag = imag({ inputs: { input: addPart }, backend: cpuBackend });
      var subPartImag = imag({ inputs: { input: subPart }, backend: cpuBackend });
      var $real = concat({
        inputs: [addPartReal, subPartReal],
        backend: cpuBackend,
        attrs: { axis: 0 }
      });
      var $imag = concat({
        inputs: [addPartImag, subPartImag],
        backend: cpuBackend,
        attrs: { axis: 0 }
      });
      var $realVals = cpuBackend.data.get($real.dataId).values;
      var $imagVals = cpuBackend.data.get($imag.dataId).values;
      cpuBackend.disposeIntermediateTensorInfo(evenRealInfo);
      cpuBackend.disposeIntermediateTensorInfo(evenImagInfo);
      cpuBackend.disposeIntermediateTensorInfo(evenTensorInfo);
      cpuBackend.disposeIntermediateTensorInfo(oddRealInfo);
      cpuBackend.disposeIntermediateTensorInfo(oddImagInfo);
      cpuBackend.disposeIntermediateTensorInfo(oddTensorInfo);
      cpuBackend.disposeIntermediateTensorInfo($evenRealInfo);
      cpuBackend.disposeIntermediateTensorInfo($evenImagInfo);
      cpuBackend.disposeIntermediateTensorInfo($evenTensorInfo);
      cpuBackend.disposeIntermediateTensorInfo($oddRealInfo);
      cpuBackend.disposeIntermediateTensorInfo($oddImagInfo);
      cpuBackend.disposeIntermediateTensorInfo($oddTensorInfo);
      cpuBackend.disposeIntermediateTensorInfo(eRealInfo);
      cpuBackend.disposeIntermediateTensorInfo(eImagInfo);
      cpuBackend.disposeIntermediateTensorInfo(complexInfo);
      cpuBackend.disposeIntermediateTensorInfo(exponentInfo);
      cpuBackend.disposeIntermediateTensorInfo(addPart);
      cpuBackend.disposeIntermediateTensorInfo(subPart);
      cpuBackend.disposeIntermediateTensorInfo(addPartReal);
      cpuBackend.disposeIntermediateTensorInfo(addPartImag);
      cpuBackend.disposeIntermediateTensorInfo(subPartReal);
      cpuBackend.disposeIntermediateTensorInfo(subPartImag);
      cpuBackend.disposeIntermediateTensorInfo($real);
      cpuBackend.disposeIntermediateTensorInfo($imag);
      return { real: $realVals, imag: $imagVals };
    }
    function fourierTransformByMatmul(data, size, inverse) {
      var ret = new Float32Array(size * 2);
      for (var r = 0; r < size; r++) {
        var real_2 = 0;
        var imag_2 = 0;
        for (var c = 0; c < size; c++) {
          var e = tfjsCore.backend_util.exponent(r * c, size, inverse);
          var term = tfjsCore.backend_util.getComplexWithIndex(data, c);
          real_2 += term.real * e.real - term.imag * e.imag;
          imag_2 += term.real * e.imag + term.imag * e.real;
        }
        if (inverse) {
          real_2 /= size;
          imag_2 /= size;
        }
        tfjsCore.backend_util.assignToTypedArray(ret, real_2, imag_2, r);
      }
      return ret;
    }
    function fft(args) {
      var inputs = args.inputs, backend = args.backend;
      var input = inputs.input;
      var inputSize = tfjsCore.util.sizeFromShape(input.shape);
      var innerDimensionSize = input.shape[input.shape.length - 1];
      var batch = inputSize / innerDimensionSize;
      var input2D = reshape({
        inputs: { x: input },
        backend,
        attrs: { shape: [batch, innerDimensionSize] }
      });
      var result = fftBatch(input2D, false, backend);
      var resultReshaped = reshape({ inputs: { x: result }, backend, attrs: { shape: input.shape } });
      backend.disposeIntermediateTensorInfo(input2D);
      backend.disposeIntermediateTensorInfo(result);
      return resultReshaped;
    }
    var fftConfig = {
      kernelName: tfjsCore.FFT,
      backendName: "cpu",
      kernelFunc: fft
    };
    function fill(args) {
      var backend = args.backend, attrs = args.attrs;
      var shape = attrs.shape, value = attrs.value, dtype = attrs.dtype;
      var $dtype = dtype || tfjsCore.util.inferDtype(value);
      var values = tfjsCore.util.getArrayFromDType($dtype, tfjsCore.util.sizeFromShape(shape));
      fillValues(values, value, $dtype);
      return backend.makeTensorInfo(shape, $dtype, values);
    }
    var fillConfig = {
      kernelName: tfjsCore.Fill,
      backendName: "cpu",
      kernelFunc: fill
    };
    function fillValues(values, value, dtype) {
      if (dtype === "string") {
        values.fill(value);
      } else {
        values.fill(value);
      }
    }
    var flipLeftRightConfig = {
      kernelName: tfjsCore.FlipLeftRight,
      backendName: "cpu",
      kernelFunc: function(_a2) {
        var inputs = _a2.inputs;
        _a2.attrs;
        var backend = _a2.backend;
        var image = inputs.image;
        var cpuBackend = backend;
        var output = tfjsCore.util.getTypedArrayFromDType(image.dtype, tfjsCore.util.sizeFromShape(image.shape));
        var _b = __read(image.shape, 4), batch = _b[0], imageHeight = _b[1], imageWidth = _b[2], numChannels = _b[3];
        var imageVals = cpuBackend.data.get(image.dataId).values;
        for (var batchIdx = 0; batchIdx < batch; batchIdx++) {
          var batchOffset = batchIdx * imageWidth * imageHeight * numChannels;
          for (var row = 0; row < imageHeight; row++) {
            var rowOffset = row * (imageWidth * numChannels);
            for (var col = 0; col < imageWidth; col++) {
              var colOffset = col * numChannels;
              for (var channel = 0; channel < numChannels; channel++) {
                var coordX = Math.round(imageWidth - col - 1);
                var outIdx = batchOffset + rowOffset + colOffset + channel;
                var outputValue = imageVals[outIdx];
                if (coordX >= 0 && coordX < imageWidth) {
                  var rotatedColOffset = coordX * numChannels;
                  var imageIdx = batchOffset + rowOffset + rotatedColOffset + channel;
                  outputValue = imageVals[imageIdx];
                }
                output[outIdx] = outputValue;
              }
            }
          }
        }
        var dataId = cpuBackend.write(output, image.shape, image.dtype);
        return { dataId, shape: image.shape, dtype: image.dtype };
      }
    };
    function fusedConv2D(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, filter = inputs.filter, bias = inputs.bias, preluActivationWeights = inputs.preluActivationWeights;
      var strides = attrs.strides, pad = attrs.pad, dataFormat = attrs.dataFormat, dilations = attrs.dilations, dimRoundingMode = attrs.dimRoundingMode, activation = attrs.activation, leakyreluAlpha = attrs.leakyreluAlpha;
      var result = conv2D({
        inputs: { x, filter },
        backend,
        attrs: { strides, pad, dataFormat, dilations, dimRoundingMode }
      });
      if (bias) {
        var resultOld = result;
        if (dataFormat === "NCHW" && bias.shape.length === 1 && bias.shape[0] !== 1) {
          var reshapedBias = reshape({ inputs: { x: bias }, backend, attrs: { shape: [bias.shape[0], 1, 1] } });
          result = add({ inputs: { a: result, b: reshapedBias }, backend });
          backend.disposeIntermediateTensorInfo(reshapedBias);
        } else {
          result = add({ inputs: { a: result, b: bias }, backend });
        }
        backend.disposeIntermediateTensorInfo(resultOld);
      }
      if (activation) {
        var resultOld = result;
        if (dataFormat === "NCHW" && activation === "prelu" && preluActivationWeights.shape.length === 1 && preluActivationWeights.shape[0] !== 1) {
          var reshapedAlpha = reshape({
            inputs: { x: preluActivationWeights },
            backend,
            attrs: { shape: [preluActivationWeights.shape[0], 1, 1] }
          });
          result = applyActivation(backend, result, activation, reshapedAlpha, leakyreluAlpha);
          backend.disposeIntermediateTensorInfo(reshapedAlpha);
        } else {
          result = applyActivation(backend, result, activation, preluActivationWeights, leakyreluAlpha);
        }
        backend.disposeIntermediateTensorInfo(resultOld);
      }
      return result;
    }
    var fusedConv2DConfig = {
      kernelName: tfjsCore.FusedConv2D,
      backendName: "cpu",
      kernelFunc: fusedConv2D
    };
    function fusedDepthwiseConv2D(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, filter = inputs.filter, bias = inputs.bias, preluActivationWeights = inputs.preluActivationWeights;
      var strides = attrs.strides, pad = attrs.pad, dataFormat = attrs.dataFormat, dilations = attrs.dilations, dimRoundingMode = attrs.dimRoundingMode, activation = attrs.activation, leakyreluAlpha = attrs.leakyreluAlpha;
      var result = depthwiseConv2dNative({
        inputs: { x, filter },
        backend,
        attrs: { strides, pad, dataFormat, dilations, dimRoundingMode }
      });
      if (bias) {
        var oldResult = result;
        result = add({ inputs: { a: result, b: bias }, backend });
        backend.disposeIntermediateTensorInfo(oldResult);
      }
      if (activation) {
        var oldResult = result;
        result = applyActivation(backend, result, activation, preluActivationWeights, leakyreluAlpha);
        backend.disposeIntermediateTensorInfo(oldResult);
      }
      return result;
    }
    var fusedDepthwiseConv2DConfig = {
      kernelName: tfjsCore.FusedDepthwiseConv2D,
      backendName: "cpu",
      kernelFunc: fusedDepthwiseConv2D
    };
    function gatherNd(args) {
      var inputs = args.inputs, backend = args.backend;
      var params = inputs.params, indices = inputs.indices;
      var paramsSize = tfjsCore.util.sizeFromShape(params.shape);
      var indicesShape = indices.shape;
      var sliceRank = indicesShape[indicesShape.length - 1];
      var _a2 = __read(tfjsCore.backend_util.prepareAndValidate(params, indices), 4), resultShape = _a2[0], numSlices = _a2[1], sliceSize = _a2[2], strides = _a2[3];
      if (numSlices === 0) {
        return backend.makeTensorInfo(resultShape, params.dtype, []);
      }
      var indicesData = backend.data.get(indices.dataId).values;
      var paramsBuf = backend.bufferSync(params);
      var outBuf = gatherNdImpl(indicesData, paramsBuf, params.dtype, numSlices, sliceRank, sliceSize, strides, params.shape, paramsSize);
      return backend.makeTensorInfo(resultShape, params.dtype, outBuf.values);
    }
    var gatherNdConfig = {
      kernelName: tfjsCore.GatherNd,
      backendName: "cpu",
      kernelFunc: gatherNd
    };
    function gatherV2(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, indices = inputs.indices;
      var axis = attrs.axis, batchDims = attrs.batchDims;
      assertNotComplex([x, indices], "gatherV2");
      var parsedAxis = tfjsCore.util.parseAxisParam(axis, x.shape)[0];
      var indicesVals = backend.data.get(indices.dataId).values;
      var axisDim = x.shape[parsedAxis];
      var _loop_1 = function(i2) {
        var index = indicesVals[i2];
        tfjsCore.util.assert(index <= axisDim - 1 && index >= 0, function() {
          return "GatherV2: the index value ".concat(index, " is not in [0, ").concat(axisDim - 1, "]");
        });
      };
      for (var i = 0; i < indicesVals.length; ++i) {
        _loop_1(i);
      }
      var $batchDims = batchDims;
      if (batchDims == null) {
        $batchDims = 0;
      }
      var indicesSize = tfjsCore.util.sizeFromShape(indices.shape);
      var shapeInfo = tfjsCore.backend_util.segment_util.collectGatherOpShapeInfo(x, indices, parsedAxis, $batchDims);
      var flattenX = reshape({
        inputs: { x },
        backend,
        attrs: {
          shape: [
            shapeInfo.batchSize,
            shapeInfo.outerSize,
            shapeInfo.dimSize,
            shapeInfo.sliceSize
          ]
        }
      });
      var flattenIndex = reshape({
        inputs: { x: indices },
        backend,
        attrs: { shape: [shapeInfo.batchSize, indicesSize / shapeInfo.batchSize] }
      });
      var flattenOutputShape = [
        shapeInfo.batchSize,
        shapeInfo.outerSize,
        indicesSize / shapeInfo.batchSize,
        shapeInfo.sliceSize
      ];
      var indicesBuf = backend.bufferSync(flattenIndex);
      var xBuf = backend.bufferSync(flattenX);
      var outBuf = gatherV2Impl(xBuf, indicesBuf, flattenOutputShape);
      backend.disposeIntermediateTensorInfo(flattenX);
      backend.disposeIntermediateTensorInfo(flattenIndex);
      return backend.makeTensorInfo(shapeInfo.outputShape, outBuf.dtype, outBuf.values);
    }
    var gatherV2Config = {
      kernelName: tfjsCore.GatherV2,
      backendName: "cpu",
      kernelFunc: gatherV2
    };
    function ifft(args) {
      var inputs = args.inputs, backend = args.backend;
      var input = inputs.input;
      var inputSize = tfjsCore.util.sizeFromShape(input.shape);
      var innerDimensionSize = input.shape[input.shape.length - 1];
      var batch = inputSize / innerDimensionSize;
      var input2D = reshape({
        inputs: { x: input },
        backend,
        attrs: { shape: [batch, innerDimensionSize] }
      });
      var result = fftBatch(input2D, true, backend);
      var resultReshaped = reshape({ inputs: { x: result }, backend, attrs: { shape: input.shape } });
      backend.disposeIntermediateTensorInfo(input2D);
      backend.disposeIntermediateTensorInfo(result);
      return resultReshaped;
    }
    var ifftConfig = {
      kernelName: tfjsCore.IFFT,
      backendName: "cpu",
      kernelFunc: ifft
    };
    var isFinite2 = unaryKernelFunc(tfjsCore.IsFinite, function(xi) {
      return Number.isFinite(xi) ? 1 : 0;
    }, "bool");
    var isFiniteConfig = {
      kernelName: tfjsCore.IsFinite,
      backendName: "cpu",
      kernelFunc: isFinite2
    };
    var isInf = unaryKernelFunc(tfjsCore.IsInf, function(xi) {
      return Math.abs(xi) === Infinity ? 1 : 0;
    }, "bool");
    var isInfConfig = {
      kernelName: tfjsCore.IsInf,
      backendName: "cpu",
      kernelFunc: isInf
    };
    var isNaN$1 = unaryKernelFunc(tfjsCore.IsNan, function(xi) {
      return Number.isNaN(xi) ? 1 : 0;
    }, "bool");
    var isNaNConfig = {
      kernelName: tfjsCore.IsNan,
      backendName: "cpu",
      kernelFunc: isNaN$1
    };
    function linSpace(args) {
      var backend = args.backend, attrs = args.attrs;
      var start = attrs.start, stop = attrs.stop, num = attrs.num;
      var outVals = linSpaceImpl(start, stop, num);
      return backend.makeTensorInfo([outVals.length], "float32", outVals);
    }
    var linSpaceConfig = {
      kernelName: tfjsCore.LinSpace,
      backendName: "cpu",
      kernelFunc: linSpace
    };
    var log1p = unaryKernelFunc(tfjsCore.Log1p, function(xi) {
      return Math.log1p(xi);
    });
    var log1pConfig = {
      kernelName: tfjsCore.Log1p,
      backendName: "cpu",
      kernelFunc: log1p
    };
    var logicalAndImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a && b;
    });
    var logicalAnd = binaryKernelFunc(tfjsCore.LogicalAnd, logicalAndImpl, null, "bool");
    var logicalAndConfig = {
      kernelName: tfjsCore.LogicalAnd,
      backendName: "cpu",
      kernelFunc: logicalAnd
    };
    var logicalNot = unaryKernelFunc(tfjsCore.LogicalNot, function(xi) {
      return xi ? 0 : 1;
    }, "bool");
    var logicalNotConfig = {
      kernelName: tfjsCore.LogicalNot,
      backendName: "cpu",
      kernelFunc: logicalNot
    };
    var logicalOrImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a || b;
    });
    var logicalOr = binaryKernelFunc(tfjsCore.LogicalOr, logicalOrImpl, null, "bool");
    var logicalOrConfig = {
      kernelName: tfjsCore.LogicalOr,
      backendName: "cpu",
      kernelFunc: logicalOr
    };
    function lRN(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var depthRadius = attrs.depthRadius, bias = attrs.bias, alpha = attrs.alpha, beta = attrs.beta;
      assertNotComplex(x, "LRN");
      var channels = x.shape[3];
      var maxD = channels - 1;
      var xValues = backend.data.get(x.dataId).values;
      var size = tfjsCore.util.sizeFromShape(x.shape);
      var result = new Float32Array(size);
      function sumAcrossChannels(offset2) {
        var currentChannel = offset2 % channels;
        var beginSumOffset = offset2 - currentChannel + Math.max(0, currentChannel - depthRadius);
        var endSumOffset = offset2 - currentChannel + Math.min(currentChannel + depthRadius, maxD);
        var sum3 = 0;
        for (; beginSumOffset <= endSumOffset; beginSumOffset++) {
          var z = xValues[beginSumOffset];
          sum3 += z * z;
        }
        return sum3;
      }
      for (var offset = 0; offset < size; offset++) {
        var sum2 = sumAcrossChannels(offset);
        var val = xValues[offset] * Math.pow(bias + alpha * sum2, -beta);
        result[offset] = val;
      }
      return backend.makeTensorInfo(x.shape, x.dtype, result);
    }
    var LRNConfig = {
      kernelName: tfjsCore.LRN,
      backendName: "cpu",
      kernelFunc: lRN
    };
    function lRNGrad(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, y = inputs.y, dy = inputs.dy;
      var depthRadius = attrs.depthRadius, bias = attrs.bias, alpha = attrs.alpha, beta = attrs.beta;
      assertNotComplex(dy, "LRNGrad");
      var dySize = tfjsCore.util.sizeFromShape(dy.shape);
      var channels = dy.shape[3];
      var dyValues = backend.data.get(dy.dataId).values;
      var xValues = backend.data.get(x.dataId).values;
      var yValues = backend.data.get(y.dataId).values;
      var result = new Float32Array(dySize);
      var size = dySize;
      for (var offset = 0; offset < size; offset++) {
        var currentChannel = offset % channels;
        var depthBegin = offset - currentChannel + Math.max(0, currentChannel - depthRadius);
        var depthEnd = offset - currentChannel + Math.min(channels, currentChannel + depthRadius + 1);
        var norm = 0;
        for (var k = depthBegin; k < depthEnd; k++) {
          norm += Math.pow(xValues[k], 2);
        }
        norm = alpha * norm + bias;
        for (var k = depthBegin; k < depthEnd; k++) {
          var dyi = -2 * alpha * beta * xValues[k] * yValues[offset] / norm;
          if (offset === k) {
            dyi += Math.pow(norm, -beta);
          }
          dyi *= dyValues[offset];
          result[k] += dyi;
        }
      }
      return backend.makeTensorInfo(dy.shape, x.dtype, result);
    }
    var LRNGradConfig = {
      kernelName: tfjsCore.LRNGrad,
      backendName: "cpu",
      kernelFunc: lRNGrad
    };
    function max(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var reductionIndices = attrs.reductionIndices, keepDims = attrs.keepDims;
      var cpuBackend = backend;
      var xShape = x.shape;
      var xRank = xShape.length;
      var origAxes = tfjsCore.util.parseAxisParam(reductionIndices, xShape);
      var axes = origAxes;
      var permutedAxes = tfjsCore.backend_util.getAxesPermutation(axes, xRank);
      var xVals = cpuBackend.data.get(x.dataId).values;
      if (permutedAxes != null) {
        var newShape = new Array(xRank);
        for (var i = 0; i < newShape.length; i++) {
          newShape[i] = xShape[permutedAxes[i]];
        }
        xVals = transposeImpl(xVals, xShape, x.dtype, permutedAxes, newShape);
        axes = tfjsCore.backend_util.getInnerMostAxes(axes.length, xRank);
        xShape = newShape;
      }
      assertNotComplex(x, "max");
      tfjsCore.backend_util.assertAxesAreInnerMostDims("max", axes, xRank);
      var _a2 = __read(tfjsCore.backend_util.computeOutAndReduceShapes(xShape, axes), 2), maxOutShape = _a2[0], reduceShape = _a2[1];
      var reduceSize = tfjsCore.util.sizeFromShape(reduceShape);
      var result = maxImpl(xVals, reduceSize, maxOutShape, x.dtype);
      var dataId = cpuBackend.write(result, maxOutShape, x.dtype);
      var outShape = maxOutShape;
      if (keepDims) {
        var newShape = tfjsCore.backend_util.expandShapeToKeepDim(maxOutShape, origAxes);
        outShape = newShape;
      }
      return { dataId, shape: outShape, dtype: x.dtype };
    }
    var maxConfig = {
      kernelName: tfjsCore.Max,
      backendName: "cpu",
      kernelFunc: max
    };
    function maxPool(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      assertNotComplex(x, "maxPool");
      var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
      var dilations = 1;
      tfjsCore.util.assert(tfjsCore.backend_util.eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in maxPool: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      var convInfo = tfjsCore.backend_util.computePool2DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode);
      var res;
      if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 && tfjsCore.util.arraysEqual(convInfo.inShape, convInfo.outShape)) {
        res = identity({ inputs: { x }, backend });
      } else {
        var xValues = backend.data.get(x.dataId).values;
        var strides_1 = tfjsCore.util.computeStrides(x.shape);
        var buffer = pool(xValues, x.shape, x.dtype, strides_1, convInfo, "max");
        res = backend.makeTensorInfo(convInfo.outShape, x.dtype, buffer.values);
      }
      return res;
    }
    var maxPoolConfig = {
      kernelName: tfjsCore.MaxPool,
      backendName: "cpu",
      kernelFunc: maxPool
    };
    function maxPool3D(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode, dataFormat = attrs.dataFormat;
      assertNotComplex(x, "maxPool3d");
      var convInfo = tfjsCore.backend_util.computePool3DInfo(x.shape, filterSize, strides, 1, pad, dimRoundingMode, dataFormat);
      var xValues = backend.data.get(x.dataId).values;
      var outBuf = pool3d(xValues, x.shape, x.dtype, tfjsCore.util.computeStrides(x.shape), convInfo, "max");
      return backend.makeTensorInfo(outBuf.shape, "float32", outBuf.values);
    }
    var maxPool3DConfig = {
      kernelName: tfjsCore.MaxPool3D,
      backendName: "cpu",
      kernelFunc: maxPool3D
    };
    function maxPool3DGrad(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var dy = inputs.dy, input = inputs.input;
      var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
      assertNotComplex([dy, input], "maxPool3DGrad");
      var convInfo = tfjsCore.backend_util.computePool3DInfo(input.shape, filterSize, strides, 1, pad, dimRoundingMode);
      var inputBuf = backend.bufferSync(input);
      var maxPosBuf = maxPool3dPositions(inputBuf, convInfo);
      var strideDepth = convInfo.strideDepth;
      var strideHeight = convInfo.strideHeight;
      var strideWidth = convInfo.strideWidth;
      var dilationDepth = convInfo.dilationDepth;
      var dilationHeight = convInfo.dilationHeight;
      var dilationWidth = convInfo.dilationWidth;
      var effectiveFilterDepth = convInfo.effectiveFilterDepth;
      var effectiveFilterHeight = convInfo.effectiveFilterHeight;
      var effectiveFilterWidth = convInfo.effectiveFilterWidth;
      var padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;
      var padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
      var padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
      var dx = tfjsCore.buffer(input.shape, "float32");
      var dyBuf = backend.bufferSync(dy);
      for (var batch = 0; batch < convInfo.batchSize; ++batch) {
        for (var channel = 0; channel < convInfo.inChannels; ++channel) {
          for (var dxDepth = 0; dxDepth < convInfo.inDepth; ++dxDepth) {
            for (var dxRow = 0; dxRow < convInfo.inHeight; ++dxRow) {
              for (var dxCol = 0; dxCol < convInfo.inWidth; ++dxCol) {
                var dyDepthCorner = dxDepth - padFront;
                var dyRowCorner = dxRow - padTop;
                var dyColCorner = dxCol - padLeft;
                var dotProd = 0;
                for (var wDepth = 0; wDepth < effectiveFilterDepth; wDepth += dilationDepth) {
                  var dyDepth = (dyDepthCorner + wDepth) / strideDepth;
                  if (dyDepth < 0 || dyDepth >= convInfo.outDepth || Math.floor(dyDepth) !== dyDepth) {
                    continue;
                  }
                  for (var wRow = 0; wRow < effectiveFilterHeight; wRow += dilationHeight) {
                    var dyRow = (dyRowCorner + wRow) / strideHeight;
                    if (dyRow < 0 || dyRow >= convInfo.outHeight || Math.floor(dyRow) !== dyRow) {
                      continue;
                    }
                    for (var wCol = 0; wCol < effectiveFilterWidth; wCol += dilationWidth) {
                      var dyCol = (dyColCorner + wCol) / strideWidth;
                      if (dyCol < 0 || dyCol >= convInfo.outWidth || Math.floor(dyCol) !== dyCol) {
                        continue;
                      }
                      var maxPos = effectiveFilterDepth * effectiveFilterHeight * effectiveFilterWidth - 1 - maxPosBuf.get(batch, dyDepth, dyRow, dyCol, channel);
                      var curPos = wDepth * effectiveFilterHeight * effectiveFilterWidth + wRow * effectiveFilterWidth + wCol;
                      var mask = maxPos === curPos ? 1 : 0;
                      if (mask === 0) {
                        continue;
                      }
                      var pixel = dyBuf.get(batch, dyDepth, dyRow, dyCol, channel);
                      dotProd += pixel * mask;
                    }
                  }
                }
                dx.set(dotProd, batch, dxDepth, dxRow, dxCol, channel);
              }
            }
          }
        }
      }
      return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);
    }
    var maxPool3DGradConfig = {
      kernelName: tfjsCore.MaxPool3DGrad,
      backendName: "cpu",
      kernelFunc: maxPool3DGrad
    };
    function maxPoolGrad(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var dy = inputs.dy, input = inputs.input, output = inputs.output;
      var x = input;
      assertNotComplex([input, output], "maxPoolGrad");
      var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
      var convInfo = tfjsCore.backend_util.computePool2DInfo(x.shape, filterSize, strides, 1, pad, dimRoundingMode);
      var xValues = backend.data.get(x.dataId).values;
      var maxPosBuf = tfjsCore.buffer(convInfo.outShape, x.dtype, maxPoolPositions(xValues, x.shape, x.dtype, convInfo).values);
      var strideHeight = convInfo.strideHeight;
      var strideWidth = convInfo.strideWidth;
      var dilationHeight = convInfo.dilationHeight;
      var dilationWidth = convInfo.dilationWidth;
      var effectiveFilterHeight = convInfo.effectiveFilterHeight;
      var effectiveFilterWidth = convInfo.effectiveFilterWidth;
      var padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
      var padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
      var dx = tfjsCore.buffer(x.shape, "float32");
      var dyData = backend.data.get(dy.dataId).values;
      var dyBuf = tfjsCore.buffer(dy.shape, "float32", dyData);
      for (var b = 0; b < convInfo.batchSize; ++b) {
        for (var d = 0; d < convInfo.inChannels; ++d) {
          for (var dxR = 0; dxR < convInfo.inHeight; ++dxR) {
            for (var dxC = 0; dxC < convInfo.inWidth; ++dxC) {
              var dyRCorner = dxR - padTop;
              var dyCCorner = dxC - padLeft;
              var dotProd = 0;
              for (var wR = 0; wR < effectiveFilterHeight; wR += dilationHeight) {
                var dyR = (dyRCorner + wR) / strideHeight;
                if (dyR < 0 || dyR >= convInfo.outHeight || Math.floor(dyR) !== dyR) {
                  continue;
                }
                for (var wC = 0; wC < effectiveFilterWidth; wC += dilationWidth) {
                  var dyC = (dyCCorner + wC) / strideWidth;
                  if (dyC < 0 || dyC >= convInfo.outWidth || Math.floor(dyC) !== dyC) {
                    continue;
                  }
                  var maxPos = effectiveFilterHeight * effectiveFilterWidth - 1 - maxPosBuf.get(b, dyR, dyC, d);
                  var curPos = wR * effectiveFilterWidth + wC;
                  var mask = maxPos === curPos ? 1 : 0;
                  if (mask === 0) {
                    continue;
                  }
                  var pixel = dyBuf.get(b, dyR, dyC, d);
                  dotProd += pixel * mask;
                }
              }
              dx.set(dotProd, b, dxR, dxC, d);
            }
          }
        }
      }
      return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);
    }
    var maxPoolGradConfig = {
      kernelName: tfjsCore.MaxPoolGrad,
      backendName: "cpu",
      kernelFunc: maxPoolGrad
    };
    function maxPoolWithArgmaxImpl(xValues, xShape, dtype, includeBatchInIndex, convInfo) {
      var strides = tfjsCore.util.computeStrides(xShape);
      var maxPools = pool(xValues, xShape, dtype, strides, convInfo, "max");
      var maxPositions = maxPoolPositions(xValues, xShape, dtype, convInfo, true, includeBatchInIndex);
      return [maxPools.values, maxPositions.values];
    }
    var maxPoolWithArgmaxConfig = {
      kernelName: tfjsCore.MaxPoolWithArgmax,
      backendName: "cpu",
      kernelFunc: function(_a2) {
        var inputs = _a2.inputs, attrs = _a2.attrs, backend = _a2.backend;
        var x = inputs.x;
        var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, includeBatchInIndex = attrs.includeBatchInIndex;
        var cpuBackend = backend;
        assertNotComplex(x, "MaxPoolWithArgmax");
        var values = cpuBackend.data.get(x.dataId).values;
        var convInfo = tfjsCore.backend_util.computePool2DInfo(x.shape, filterSize, strides, [1, 1], pad);
        var _b = __read(maxPoolWithArgmaxImpl(values, x.shape, x.dtype, includeBatchInIndex, convInfo), 2), pooled = _b[0], indexes = _b[1];
        var pooledDataId = cpuBackend.write(pooled, convInfo.outShape, x.dtype);
        var indexesDataId = cpuBackend.write(indexes, convInfo.outShape, x.dtype);
        return [
          { dataId: pooledDataId, shape: convInfo.outShape, dtype: x.dtype },
          { dataId: indexesDataId, shape: convInfo.outShape, dtype: "int32" }
        ];
      }
    };
    function mean(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis, keepDims = attrs.keepDims;
      var axes = tfjsCore.util.parseAxisParam(axis, x.shape);
      var shapes = tfjsCore.backend_util.computeOutAndReduceShapes(x.shape, axes);
      var reduceShape = shapes[1];
      var reduceSize = tfjsCore.util.sizeFromShape(reduceShape);
      var toDispose = [];
      var reduceSizeScalar = backend.makeTensorInfo([], "float32", new Float32Array([reduceSize]));
      toDispose.push(reduceSizeScalar);
      var $x = cast({ inputs: { x }, backend, attrs: { dtype: "float32" } });
      toDispose.push($x);
      var res = div({ inputs: { a: $x, b: reduceSizeScalar }, backend });
      toDispose.push(res);
      var result = sum({ inputs: { x: res }, backend, attrs: { axis, keepDims } });
      toDispose.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return result;
    }
    var meanConfig = {
      kernelName: tfjsCore.Mean,
      backendName: "cpu",
      kernelFunc: mean
    };
    function min(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis, keepDims = attrs.keepDims;
      assertNotComplex(x, "min");
      var origAxes = tfjsCore.util.parseAxisParam(axis, x.shape);
      var axes = origAxes;
      var permutedAxes = tfjsCore.backend_util.getAxesPermutation(axes, x.shape.length);
      var $x = x;
      if (permutedAxes != null) {
        $x = transpose({ inputs: { x }, backend, attrs: { perm: permutedAxes } });
        axes = tfjsCore.backend_util.getInnerMostAxes(axes.length, x.shape.length);
      }
      tfjsCore.backend_util.assertAxesAreInnerMostDims("min", axes, $x.shape.length);
      var _a2 = __read(tfjsCore.backend_util.computeOutAndReduceShapes($x.shape, axes), 2), outShape = _a2[0], reduceShape = _a2[1];
      var reduceSize = tfjsCore.util.sizeFromShape(reduceShape);
      var vals = tfjsCore.util.makeZerosTypedArray(tfjsCore.util.sizeFromShape(outShape), $x.dtype);
      var aVals = backend.data.get($x.dataId).values;
      for (var i = 0; i < vals.length; ++i) {
        var offset = i * reduceSize;
        var min_1 = aVals[offset];
        for (var j = 0; j < reduceSize; ++j) {
          var value = aVals[offset + j];
          if (Number.isNaN(value) || value < min_1) {
            min_1 = value;
          }
        }
        vals[i] = min_1;
      }
      if (permutedAxes != null) {
        backend.disposeIntermediateTensorInfo($x);
      }
      var result = backend.makeTensorInfo(outShape, $x.dtype, vals);
      if (keepDims) {
        var expandedShape = tfjsCore.backend_util.expandShapeToKeepDim(outShape, origAxes);
        var reshapedResult = reshape({ inputs: { x: result }, backend, attrs: { shape: expandedShape } });
        backend.disposeIntermediateTensorInfo(result);
        return reshapedResult;
      }
      return result;
    }
    var minConfig = {
      kernelName: tfjsCore.Min,
      backendName: "cpu",
      kernelFunc: min
    };
    function mirrorPad(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var paddings = attrs.paddings, mode = attrs.mode;
      assertNotComplex(x, "mirrorPad");
      var outShape = paddings.map(
        function(p2, i2) {
          return p2[0] + x.shape[i2] + p2[1];
        }
        /* afterPad */
      );
      var start = paddings.map(function(p2) {
        return p2[0];
      });
      var end = paddings.map(function(p2, i2) {
        return p2[0] + x.shape[i2];
      });
      var offset = mode === "reflect" ? 0 : 1;
      var xVals = backend.data.get(x.dataId).values;
      var xRank = x.shape.length;
      var xStrides = tfjsCore.util.computeStrides(x.shape);
      var resultSize = tfjsCore.util.sizeFromShape(outShape);
      var resultRank = outShape.length;
      var resultStrides = tfjsCore.util.computeStrides(outShape);
      var resVals = tfjsCore.util.getTypedArrayFromDType(x.dtype, resultSize);
      for (var i = 0; i < resultSize; i++) {
        var coords = tfjsCore.util.indexToLoc(i, resultRank, resultStrides);
        for (var i_1 = 0; i_1 < resultRank; i_1++) {
          if (coords[i_1] < start[i_1]) {
            coords[i_1] = start[i_1] * 2 - coords[i_1] - offset;
          } else if (coords[i_1] >= end[i_1]) {
            coords[i_1] = (end[i_1] - 1) * 2 - coords[i_1] + offset;
          }
        }
        coords = coords.map(function(c, i2) {
          return c - start[i2];
        });
        var inIndex = tfjsCore.util.locToIndex(coords, xRank, xStrides);
        resVals[i] = xVals[inIndex];
      }
      var outId = backend.write(resVals, outShape, x.dtype);
      return { dataId: outId, shape: outShape, dtype: x.dtype };
    }
    var mirrorPadConfig = {
      kernelName: tfjsCore.MirrorPad,
      backendName: "cpu",
      kernelFunc: mirrorPad
    };
    var modImpl = createSimpleBinaryKernelImpl(function(aValue, bValue) {
      var rem = aValue % bValue;
      if (aValue < 0 && bValue < 0 || aValue >= 0 && bValue >= 0) {
        return rem;
      } else {
        return (rem + bValue) % bValue;
      }
    });
    var mod = binaryKernelFunc(tfjsCore.Mod, modImpl);
    var modConfig = {
      kernelName: tfjsCore.Mod,
      backendName: "cpu",
      kernelFunc: mod
    };
    function softmax(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var logits = inputs.logits;
      var dim = attrs.dim;
      var logitsRank = logits.shape.length;
      var $dim = dim;
      if ($dim === -1) {
        $dim = logitsRank - 1;
      }
      if ($dim !== logitsRank - 1) {
        throw Error("Softmax along a non-last dimension is not yet supported. " + "Logits was rank ".concat(logitsRank, " and dim was ").concat($dim));
      }
      var axes = tfjsCore.util.parseAxisParam([$dim], logits.shape);
      var maxLogit = max({
        inputs: { x: logits },
        backend,
        attrs: { reductionIndices: axes, keepDims: false }
      });
      var expandedShape = tfjsCore.backend_util.expandShapeToKeepDim(maxLogit.shape, axes);
      var maxLogitReshaped = reshape({ inputs: { x: maxLogit }, backend, attrs: { shape: expandedShape } });
      var a = sub({ inputs: { a: logits, b: maxLogitReshaped }, backend });
      var b = exp({ inputs: { x: a }, backend });
      var sumExp = sum({ inputs: { x: b }, backend, attrs: { axis: axes, keepDims: false } });
      var sumReshaped = reshape({ inputs: { x: sumExp }, backend, attrs: { shape: expandedShape } });
      var result = div({ inputs: { a: b, b: sumReshaped }, backend });
      backend.disposeIntermediateTensorInfo(maxLogit);
      backend.disposeIntermediateTensorInfo(maxLogitReshaped);
      backend.disposeIntermediateTensorInfo(a);
      backend.disposeIntermediateTensorInfo(b);
      backend.disposeIntermediateTensorInfo(sumExp);
      backend.disposeIntermediateTensorInfo(sumReshaped);
      return result;
    }
    var softmaxConfig = {
      kernelName: tfjsCore.Softmax,
      backendName: "cpu",
      kernelFunc: softmax
    };
    function multinomial(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var logits = inputs.logits;
      var numSamples = attrs.numSamples, seed = attrs.seed, normalized = attrs.normalized;
      assertNotComplex(logits, "multinomial");
      var probabilities = normalized ? logits : softmax({ inputs: { logits }, backend, attrs: { dim: -1 } });
      var batchSize = probabilities.shape[0];
      var numEvents = probabilities.shape[1];
      var probVals = backend.data.get(probabilities.dataId).values;
      var resShape = [batchSize, numSamples];
      var resVals = tfjsCore.util.makeZerosTypedArray(tfjsCore.util.sizeFromShape(resShape), "int32");
      for (var b = 0; b < batchSize; ++b) {
        var offset = b * numEvents;
        var cdf = new Float32Array(numEvents - 1);
        cdf[0] = probVals[offset];
        for (var event = 1; event < cdf.length; ++event) {
          cdf[event] = cdf[event - 1] + probVals[offset + event];
        }
        var random = seedrandom__namespace.alea(seed.toString());
        var outOffset = b * numSamples;
        for (var sampleId = 0; sampleId < numSamples; ++sampleId) {
          var r = random();
          resVals[outOffset + sampleId] = cdf.length;
          for (var event = 0; event < cdf.length; event++) {
            if (r < cdf[event]) {
              resVals[outOffset + sampleId] = event;
              break;
            }
          }
        }
      }
      if (!normalized) {
        backend.disposeIntermediateTensorInfo(probabilities);
      }
      return backend.makeTensorInfo(resShape, "int32", resVals);
    }
    var multinomialConfig = {
      kernelName: tfjsCore.Multinomial,
      backendName: "cpu",
      kernelFunc: multinomial
    };
    var nonMaxSuppressionV3Impl = tfjsCore.kernel_impls.nonMaxSuppressionV3Impl;
    function nonMaxSuppressionV3(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var boxes = inputs.boxes, scores = inputs.scores;
      var maxOutputSize = attrs.maxOutputSize, iouThreshold = attrs.iouThreshold, scoreThreshold = attrs.scoreThreshold;
      assertNotComplex(boxes, "NonMaxSuppression");
      var boxesVals = backend.data.get(boxes.dataId).values;
      var scoresVals = backend.data.get(scores.dataId).values;
      var selectedIndices = nonMaxSuppressionV3Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold).selectedIndices;
      return backend.makeTensorInfo([selectedIndices.length], "int32", new Int32Array(selectedIndices));
    }
    var nonMaxSuppressionV3Config = {
      kernelName: tfjsCore.NonMaxSuppressionV3,
      backendName: "cpu",
      kernelFunc: nonMaxSuppressionV3
    };
    var nonMaxSuppressionV4Impl = tfjsCore.kernel_impls.nonMaxSuppressionV4Impl;
    function nonMaxSuppressionV4(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var boxes = inputs.boxes, scores = inputs.scores;
      var maxOutputSize = attrs.maxOutputSize, iouThreshold = attrs.iouThreshold, scoreThreshold = attrs.scoreThreshold, padToMaxOutputSize = attrs.padToMaxOutputSize;
      assertNotComplex(boxes, "NonMaxSuppressionPadded");
      var boxesVals = backend.data.get(boxes.dataId).values;
      var scoresVals = backend.data.get(scores.dataId).values;
      var _a2 = nonMaxSuppressionV4Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize), selectedIndices = _a2.selectedIndices, validOutputs = _a2.validOutputs;
      return [
        backend.makeTensorInfo([selectedIndices.length], "int32", new Int32Array(selectedIndices)),
        backend.makeTensorInfo([], "int32", new Int32Array([validOutputs]))
      ];
    }
    var nonMaxSuppressionV4Config = {
      kernelName: tfjsCore.NonMaxSuppressionV4,
      backendName: "cpu",
      kernelFunc: nonMaxSuppressionV4
    };
    var nonMaxSuppressionV5Impl = tfjsCore.kernel_impls.nonMaxSuppressionV5Impl;
    function nonMaxSuppressionV5(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var boxes = inputs.boxes, scores = inputs.scores;
      var maxOutputSize = attrs.maxOutputSize, iouThreshold = attrs.iouThreshold, scoreThreshold = attrs.scoreThreshold, softNmsSigma = attrs.softNmsSigma;
      assertNotComplex(boxes, "NonMaxSuppressionWithScore");
      var boxesVals = backend.data.get(boxes.dataId).values;
      var scoresVals = backend.data.get(scores.dataId).values;
      var maxOutputSizeVal = maxOutputSize;
      var iouThresholdVal = iouThreshold;
      var scoreThresholdVal = scoreThreshold;
      var softNmsSigmaVal = softNmsSigma;
      var _a2 = nonMaxSuppressionV5Impl(boxesVals, scoresVals, maxOutputSizeVal, iouThresholdVal, scoreThresholdVal, softNmsSigmaVal), selectedIndices = _a2.selectedIndices, selectedScores = _a2.selectedScores;
      return [
        backend.makeTensorInfo([selectedIndices.length], "int32", new Int32Array(selectedIndices)),
        backend.makeTensorInfo([selectedScores.length], "float32", new Float32Array(selectedScores))
      ];
    }
    var nonMaxSuppressionV5Config = {
      kernelName: tfjsCore.NonMaxSuppressionV5,
      backendName: "cpu",
      kernelFunc: nonMaxSuppressionV5
    };
    function oneHot(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var indices = inputs.indices;
      var dtype = attrs.dtype, depth = attrs.depth, onValue = attrs.onValue, offValue = attrs.offValue;
      assertNotComplex(indices, "oneHot");
      var indicesSize = tfjsCore.util.sizeFromShape(indices.shape);
      var res = new Float32Array(indicesSize * depth);
      res.fill(offValue);
      var indicesVal = backend.data.get(indices.dataId).values;
      for (var event = 0; event < indicesSize; ++event) {
        if (indicesVal[event] >= 0 && indicesVal[event] < depth) {
          res[event * depth + indicesVal[event]] = onValue;
        }
      }
      return backend.makeTensorInfo(__spreadArray(__spreadArray([], __read(indices.shape), false), [depth], false), dtype, res);
    }
    var oneHotConfig = {
      kernelName: tfjsCore.OneHot,
      backendName: "cpu",
      kernelFunc: oneHot
    };
    function zerosLike(args) {
      var inputs = args.inputs, backend = args.backend;
      var x = inputs.x;
      if (x.dtype === "string") {
        throw new Error("zerosLike is not supported for string tensors");
      } else if (x.dtype === "complex64") {
        var realPart = real({ inputs: { input: x }, backend });
        var r = zerosLike({ inputs: { x: realPart }, backend });
        var imagPart = imag({ inputs: { input: x }, backend });
        var i = zerosLike({ inputs: { x: imagPart }, backend });
        var result = complex({ inputs: { real: r, imag: i }, backend });
        backend.disposeIntermediateTensorInfo(realPart);
        backend.disposeIntermediateTensorInfo(r);
        backend.disposeIntermediateTensorInfo(imagPart);
        backend.disposeIntermediateTensorInfo(i);
        return result;
      } else {
        return fill({ backend, attrs: { shape: x.shape, value: 0, dtype: x.dtype } });
      }
    }
    var zerosLikeConfig = {
      kernelName: tfjsCore.ZerosLike,
      backendName: "cpu",
      kernelFunc: zerosLike
    };
    function onesLike(args) {
      var inputs = args.inputs, backend = args.backend;
      var x = inputs.x;
      if (x.dtype === "string") {
        throw new Error("onesLike is not supported for string tensors");
      } else if (x.dtype === "complex64") {
        var realPart = real({ inputs: { input: x }, backend });
        var r = onesLike({ inputs: { x: realPart }, backend });
        var imagPart = imag({ inputs: { input: x }, backend });
        var i = zerosLike({ inputs: { x: imagPart }, backend });
        var result = complex({ inputs: { real: r, imag: i }, backend });
        backend.disposeIntermediateTensorInfo(realPart);
        backend.disposeIntermediateTensorInfo(r);
        backend.disposeIntermediateTensorInfo(imagPart);
        backend.disposeIntermediateTensorInfo(i);
        return result;
      } else {
        return fill({ backend, attrs: { shape: x.shape, value: 1, dtype: x.dtype } });
      }
    }
    var onesLikeConfig = {
      kernelName: tfjsCore.OnesLike,
      backendName: "cpu",
      kernelFunc: onesLike
    };
    function pack(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var axis = attrs.axis;
      if (inputs.length === 1) {
        return expandDims({ inputs: { input: inputs[0] }, backend, attrs: { dim: axis } });
      }
      var shape = inputs[0].shape;
      var dtype = inputs[0].dtype;
      inputs.forEach(function(t) {
        tfjsCore.util.assertShapesMatch(shape, t.shape, "All tensors passed to stack must have matching shapes");
        tfjsCore.util.assert(dtype === t.dtype, function() {
          return "All tensors passed to stack must have matching dtypes";
        });
      });
      var intermediateTensorInfos = [];
      var expandedTensors = inputs.map(function(t) {
        var expandedT = expandDims({ inputs: { input: t }, backend, attrs: { dim: axis } });
        intermediateTensorInfos.push(expandedT);
        return expandedT;
      });
      var result = concat({ inputs: expandedTensors, backend, attrs: { axis } });
      intermediateTensorInfos.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return result;
    }
    var packConfig = {
      kernelName: tfjsCore.Pack,
      backendName: "cpu",
      kernelFunc: pack
    };
    function padV2(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var paddings = attrs.paddings, constantValue = attrs.constantValue;
      assertNotComplex(x, "pad");
      var outShape = paddings.map(
        function(p2, i2) {
          return p2[0] + x.shape[i2] + p2[1];
        }
        /* afterPad */
      );
      var start = paddings.map(function(p2) {
        return p2[0];
      });
      var xVals = backend.data.get(x.dataId).values;
      var xSize = tfjsCore.util.sizeFromShape(x.shape);
      var xRank = x.shape.length;
      var xStrides = tfjsCore.util.computeStrides(x.shape);
      var resultSize = tfjsCore.util.sizeFromShape(outShape);
      var resultRank = outShape.length;
      var resultStrides = tfjsCore.util.computeStrides(outShape);
      var resVals = tfjsCore.util.getTypedArrayFromDType(x.dtype, resultSize);
      if (constantValue !== 0) {
        resVals.fill(constantValue);
      }
      for (var i = 0; i < xSize; i++) {
        var coords = tfjsCore.util.indexToLoc(i, xRank, xStrides);
        var outCoords = coords.map(function(c, i2) {
          return c + start[i2];
        });
        var outIndex = tfjsCore.util.locToIndex(outCoords, resultRank, resultStrides);
        resVals[outIndex] = xVals[i];
      }
      var outId = backend.write(resVals, outShape, x.dtype);
      return { dataId: outId, shape: outShape, dtype: x.dtype };
    }
    var padV2Config = {
      kernelName: tfjsCore.PadV2,
      backendName: "cpu",
      kernelFunc: padV2
    };
    var powImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return Math.pow(a, b);
    });
    var pow = binaryKernelFunc(tfjsCore.Pow, powImpl);
    var powConfig = {
      kernelName: tfjsCore.Pow,
      backendName: "cpu",
      kernelFunc: pow
    };
    function raggedGather(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var paramsNestedSplits = inputs.paramsNestedSplits, paramsDenseValues = inputs.paramsDenseValues, indices = inputs.indices;
      attrs.outputRaggedRank;
      var $paramsNestedSplits = paramsNestedSplits.map(function(t) {
        return backend.data.get(t.dataId).values;
      });
      var $paramsNestedSplitsShapes = paramsNestedSplits.map(function(t) {
        return t.shape;
      });
      var $paramsDenseValues = backend.data.get(paramsDenseValues.dataId).values;
      var $indices = backend.data.get(indices.dataId).values;
      var _a2 = __read(raggedGatherImpl($paramsNestedSplits, $paramsNestedSplitsShapes, $paramsDenseValues, paramsDenseValues.shape, paramsDenseValues.dtype, $indices, indices.shape), 3), outputNestedSplits = _a2[0], outputDenseValues = _a2[1], outputDenseValuesShape = _a2[2];
      var outputNestedSplitsTensors = outputNestedSplits.map(function(splits) {
        return backend.makeTensorInfo([splits.length], "int32", splits);
      });
      var outputDenseValuesTensor = backend.makeTensorInfo(outputDenseValuesShape, paramsDenseValues.dtype, outputDenseValues);
      return outputNestedSplitsTensors.concat([outputDenseValuesTensor]);
    }
    var raggedGatherConfig = {
      kernelName: tfjsCore.RaggedGather,
      backendName: "cpu",
      kernelFunc: raggedGather
    };
    function raggedRange(args) {
      var inputs = args.inputs, backend = args.backend;
      var starts = inputs.starts, limits = inputs.limits, deltas = inputs.deltas;
      var $starts = backend.data.get(starts.dataId).values;
      var $limits = backend.data.get(limits.dataId).values;
      var $deltas = backend.data.get(deltas.dataId).values;
      var _a2 = __read(raggedRangeImpl($starts, starts.shape, starts.dtype, $limits, limits.shape, $deltas, deltas.shape), 2), rtNestedSplitsData = _a2[0], rtDenseValuesData = _a2[1];
      var rtNestedSplits = backend.makeTensorInfo([rtNestedSplitsData.length], "int32", rtNestedSplitsData);
      var rtDenseValues = backend.makeTensorInfo([rtDenseValuesData.length], starts.dtype, rtDenseValuesData);
      return [rtNestedSplits, rtDenseValues];
    }
    var raggedRangeConfig = {
      kernelName: tfjsCore.RaggedRange,
      backendName: "cpu",
      kernelFunc: raggedRange
    };
    function raggedTensorToTensor(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var shape = inputs.shape, values = inputs.values, defaultValue = inputs.defaultValue, rowPartitionTensors = inputs.rowPartitionTensors;
      var rowPartitionTypes = attrs.rowPartitionTypes;
      var $shape = backend.data.get(shape.dataId).values;
      var $values = backend.data.get(values.dataId).values;
      var $defaultValue = backend.data.get(defaultValue.dataId).values;
      var $rowPartitionValues = rowPartitionTensors.map(function(t) {
        return backend.data.get(t.dataId).values;
      });
      var rowPartitionValuesShapes = rowPartitionTensors.map(function(t) {
        return t.shape;
      });
      var _a2 = __read(raggedTensorToTensorImpl($shape, shape.shape, $values, values.shape, values.dtype, $defaultValue, defaultValue.shape, $rowPartitionValues, rowPartitionValuesShapes, rowPartitionTypes), 2), outputShape = _a2[0], output = _a2[1];
      return backend.makeTensorInfo(outputShape, values.dtype, output);
    }
    var raggedTensorToTensorConfig = {
      kernelName: tfjsCore.RaggedTensorToTensor,
      backendName: "cpu",
      kernelFunc: raggedTensorToTensor
    };
    function range(args) {
      var backend = args.backend, attrs = args.attrs;
      var start = attrs.start, stop = attrs.stop, dtype = attrs.dtype, step2 = attrs.step;
      var values = rangeImpl(start, stop, step2, dtype);
      return backend.makeTensorInfo([values.length], dtype, values);
    }
    var rangeConfig = {
      kernelName: tfjsCore.Range,
      backendName: "cpu",
      kernelFunc: range
    };
    var reciprocal = unaryKernelFunc(tfjsCore.Reciprocal, function(xi) {
      return 1 / xi;
    });
    var reciprocalConfig = {
      kernelName: tfjsCore.Reciprocal,
      backendName: "cpu",
      kernelFunc: reciprocal
    };
    function resizeBilinear(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var images = inputs.images;
      var alignCorners = attrs.alignCorners, halfPixelCenters = attrs.halfPixelCenters, size = attrs.size;
      assertNotComplex(images, "resizeBilinear");
      var imagesStrides = tfjsCore.util.computeStrides(images.shape);
      var _a2 = __read(size, 2), newHeight = _a2[0], newWidth = _a2[1];
      var _b = __read(images.shape, 4), batch = _b[0], oldHeight = _b[1], oldWidth = _b[2], numChannels = _b[3];
      var xValues = backend.data.get(images.dataId).values;
      var result = new Float32Array(tfjsCore.util.sizeFromShape([batch, newHeight, newWidth, numChannels]));
      var effectiveInputSize = [
        alignCorners && newHeight > 1 ? oldHeight - 1 : oldHeight,
        alignCorners && newWidth > 1 ? oldWidth - 1 : oldWidth
      ];
      var effectiveOutputSize = [
        alignCorners && newHeight > 1 ? newHeight - 1 : newHeight,
        alignCorners && newWidth > 1 ? newWidth - 1 : newWidth
      ];
      var outputIdx = 0;
      var effectiveRowSizeRatio = effectiveInputSize[0] / effectiveOutputSize[0];
      var effectiveColSizeRatio = effectiveInputSize[1] / effectiveOutputSize[1];
      for (var b = 0; b < batch; b++) {
        for (var r = 0; r < newHeight; r++) {
          var sourceFracRow = void 0;
          if (halfPixelCenters) {
            sourceFracRow = effectiveRowSizeRatio * (r + 0.5) - 0.5;
          } else {
            sourceFracRow = effectiveRowSizeRatio * r;
          }
          var sourceRowFloor = Math.max(0, Math.floor(sourceFracRow));
          var rowFrac = sourceFracRow - sourceRowFloor;
          var sourceRowCeil = Math.min(oldHeight - 1, Math.ceil(sourceFracRow));
          var topRowOffset = b * imagesStrides[0] + sourceRowFloor * imagesStrides[1];
          var botRowOffset = b * imagesStrides[0] + sourceRowCeil * imagesStrides[1];
          for (var c = 0; c < newWidth; c++) {
            var sourceFracCol = void 0;
            if (halfPixelCenters) {
              sourceFracCol = effectiveColSizeRatio * (c + 0.5) - 0.5;
            } else {
              sourceFracCol = effectiveColSizeRatio * c;
            }
            var sourceColFloor = Math.max(0, Math.floor(sourceFracCol));
            var colFrac = sourceFracCol - sourceColFloor;
            var sourceColCeil = Math.min(oldWidth - 1, Math.ceil(sourceFracCol));
            var topLeftOffest = topRowOffset + sourceColFloor * imagesStrides[2];
            var botLeftOffset = botRowOffset + sourceColFloor * imagesStrides[2];
            var topRightOffset = topRowOffset + sourceColCeil * imagesStrides[2];
            var botRightOffest = botRowOffset + sourceColCeil * imagesStrides[2];
            for (var d = 0; d < numChannels; d++) {
              var topLeft = xValues[topLeftOffest + d];
              var bottomLeft = xValues[botLeftOffset + d];
              var topRight = xValues[topRightOffset + d];
              var bottomRight = xValues[botRightOffest + d];
              var top = topLeft + (topRight - topLeft) * colFrac;
              var bottom = bottomLeft + (bottomRight - bottomLeft) * colFrac;
              var newValue = top + (bottom - top) * rowFrac;
              result[outputIdx++] = newValue;
            }
          }
        }
      }
      return backend.makeTensorInfo([batch, newHeight, newWidth, numChannels], "float32", result);
    }
    var resizeBilinearConfig = {
      kernelName: tfjsCore.ResizeBilinear,
      backendName: "cpu",
      kernelFunc: resizeBilinear
    };
    function resizeBilinearGrad(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var images = inputs.images, dy = inputs.dy;
      var alignCorners = attrs.alignCorners;
      assertNotComplex([dy, images], "resizeBilinearGrad");
      var imagesStrides = tfjsCore.util.computeStrides(images.shape);
      var _a2 = __read(images.shape, 4), batch = _a2[0], xHeight = _a2[1], xWidth = _a2[2], depth = _a2[3];
      var _b = __read(dy.shape, 3), yHeight = _b[1], yWidth = _b[2];
      var output = new Float32Array(batch * xHeight * xWidth * depth);
      var effectiveXSize = [
        alignCorners && yHeight > 1 ? xHeight - 1 : xHeight,
        alignCorners && yWidth > 1 ? xWidth - 1 : xWidth
      ];
      var effectiveYSize = [
        alignCorners && yHeight > 1 ? yHeight - 1 : yHeight,
        alignCorners && yWidth > 1 ? yWidth - 1 : yWidth
      ];
      var heightScale = effectiveXSize[0] / effectiveYSize[0];
      var widthScale = effectiveXSize[1] / effectiveYSize[1];
      var dyValues = backend.data.get(dy.dataId).values;
      var offset = 0;
      for (var b = 0; b < batch; b++) {
        var bOffset = b * imagesStrides[0];
        for (var r = 0; r < yHeight; r++) {
          var dxR = r * heightScale;
          var topDxRIndex = Math.floor(dxR);
          var bottomDxRIndex = Math.min(Math.ceil(dxR), xHeight - 1);
          var topDxROffset = bOffset + topDxRIndex * imagesStrides[1];
          var bottomDxROffset = bOffset + bottomDxRIndex * imagesStrides[1];
          var dxRLerp = dxR - topDxRIndex;
          var inverseDxRLerp = 1 - dxRLerp;
          for (var c = 0; c < yWidth; c++) {
            var dxC = c * widthScale;
            var leftDxCIndex = Math.floor(dxC);
            var rightDxCIndex = Math.min(Math.ceil(dxC), xWidth - 1);
            var dxCLerp = dxC - leftDxCIndex;
            var inverseDxCLerp = 1 - dxCLerp;
            var topLeftRCOffset = topDxROffset + leftDxCIndex * imagesStrides[2];
            var topRightRCOffset = topDxROffset + rightDxCIndex * imagesStrides[2];
            var bottomLeftRCOffset = bottomDxROffset + leftDxCIndex * imagesStrides[2];
            var bottomRightRCOffset = bottomDxROffset + rightDxCIndex * imagesStrides[2];
            var inverseDxRLerpTimesInverseDxCLerp = inverseDxRLerp * inverseDxCLerp;
            var inverseDxRLerpTimesDxCLerp = inverseDxRLerp * dxCLerp;
            var dxRLerpTimesInverseDxCLerp = dxRLerp * inverseDxCLerp;
            var dxRLerpTimesDxCLerp = dxRLerp * dxCLerp;
            for (var d = 0; d < depth; d++) {
              var dyVal = dyValues[offset++];
              output[topLeftRCOffset + d] += dyVal * inverseDxRLerpTimesInverseDxCLerp;
              output[topRightRCOffset + d] += dyVal * inverseDxRLerpTimesDxCLerp;
              output[bottomLeftRCOffset + d] += dyVal * dxRLerpTimesInverseDxCLerp;
              output[bottomRightRCOffset + d] += dyVal * dxRLerpTimesDxCLerp;
            }
          }
        }
      }
      return backend.makeTensorInfo([batch, xWidth, xHeight, depth], "float32", output);
    }
    var resizeBilinearGradConfig = {
      kernelName: tfjsCore.ResizeBilinearGrad,
      backendName: "cpu",
      kernelFunc: resizeBilinearGrad
    };
    function resizeNearestNeighbor(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var images = inputs.images;
      var alignCorners = attrs.alignCorners, halfPixelCenters = attrs.halfPixelCenters, size = attrs.size;
      assertNotComplex(images, "resizeNearestNeighbor");
      var imagesStrides = tfjsCore.util.computeStrides(images.shape);
      var _a2 = __read(size, 2), newHeight = _a2[0], newWidth = _a2[1];
      var _b = __read(images.shape, 4), batch = _b[0], oldHeight = _b[1], oldWidth = _b[2], numChannels = _b[3];
      var xValues = backend.data.get(images.dataId).values;
      var output = new Float32Array(batch * newHeight * newWidth * numChannels);
      var effectiveInputSize = [
        alignCorners && newHeight > 1 ? oldHeight - 1 : oldHeight,
        alignCorners && newWidth > 1 ? oldWidth - 1 : oldWidth
      ];
      var effectiveOutputSize = [
        alignCorners && newHeight > 1 ? newHeight - 1 : newHeight,
        alignCorners && newWidth > 1 ? newWidth - 1 : newWidth
      ];
      var effectiveRowSizeRatio = effectiveInputSize[0] / effectiveOutputSize[0];
      var effectiveColSizeRatio = effectiveInputSize[1] / effectiveOutputSize[1];
      var outputOffset = 0;
      for (var b = 0; b < batch; b++) {
        var batchOffset = b * imagesStrides[0];
        for (var r = 0; r < newHeight; r++) {
          var sourceFracRow = halfPixelCenters ? effectiveRowSizeRatio * (r + 0.5) : effectiveRowSizeRatio * r;
          var sourceNearestRow = Math.min(oldHeight - 1, alignCorners ? Math.round(sourceFracRow) : Math.floor(sourceFracRow));
          if (halfPixelCenters) {
            sourceNearestRow = Math.max(0, sourceNearestRow);
          }
          var rowOffset = batchOffset + sourceNearestRow * imagesStrides[1];
          for (var c = 0; c < newWidth; c++) {
            var sourceFracCol = halfPixelCenters ? effectiveColSizeRatio * (c + 0.5) : effectiveColSizeRatio * c;
            var sourceNearestCol = Math.min(oldWidth - 1, alignCorners ? Math.round(sourceFracCol) : Math.floor(sourceFracCol));
            if (halfPixelCenters) {
              sourceNearestCol = Math.max(0, sourceNearestCol);
            }
            var colOffset = rowOffset + sourceNearestCol * imagesStrides[2];
            for (var d = 0; d < numChannels; d++) {
              var newVal = xValues[colOffset + d];
              output[outputOffset++] = newVal;
            }
          }
        }
      }
      return backend.makeTensorInfo([batch, newHeight, newWidth, numChannels], images.dtype, output);
    }
    var resizeNearestNeighborConfig = {
      kernelName: tfjsCore.ResizeNearestNeighbor,
      backendName: "cpu",
      kernelFunc: resizeNearestNeighbor
    };
    function resizeNearestNeighborGrad(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var images = inputs.images, dy = inputs.dy;
      var alignCorners = attrs.alignCorners;
      assertNotComplex([dy, images], "resizeNearestNeighborGrad");
      var imagesStrides = tfjsCore.util.computeStrides(images.shape);
      var dyStrides = tfjsCore.util.computeStrides(dy.shape);
      var _a2 = __read(images.shape, 4), batch = _a2[0], xHeight = _a2[1], xWidth = _a2[2], depth = _a2[3];
      var _b = __read(dy.shape, 3), yHeight = _b[1], yWidth = _b[2];
      var output = new Float32Array(batch * xHeight * xWidth * depth);
      var dyValues = backend.data.get(dy.dataId).values;
      var effectiveXSize = [
        alignCorners && yHeight > 1 ? xHeight - 1 : xHeight,
        alignCorners && yWidth > 1 ? xWidth - 1 : xWidth
      ];
      var effectiveYSize = [
        alignCorners && yHeight > 1 ? yHeight - 1 : yHeight,
        alignCorners && yWidth > 1 ? yWidth - 1 : yWidth
      ];
      var heightScale = effectiveXSize[0] / effectiveYSize[0];
      var widthScale = effectiveXSize[1] / effectiveYSize[1];
      var invHeightScale = 1 / heightScale;
      var invWidthScale = 1 / widthScale;
      var winHeight = Math.ceil(invHeightScale) * 2 + 2;
      var winWidth = Math.ceil(invWidthScale) * 2 + 2;
      for (var b = 0; b < batch; b++) {
        var batchOffset = b * imagesStrides[0];
        for (var r = 0; r < xHeight; r++) {
          var rowOffset = batchOffset + r * imagesStrides[1];
          var startRLerp = Math.floor(r * invHeightScale);
          var startDyR = Math.floor(startRLerp - winHeight / 2);
          for (var c = 0; c < xWidth; c++) {
            var colOffset = rowOffset + c * imagesStrides[2];
            var startCLerp = Math.floor(c * invWidthScale);
            var startDyC = Math.floor(startCLerp - winWidth / 2);
            for (var d = 0; d < depth; d++) {
              var accum = 0;
              for (var dyRIndex = 0; dyRIndex < winHeight; dyRIndex++) {
                var dyR = dyRIndex + startDyR;
                if (dyR < 0 || dyR >= yHeight) {
                  continue;
                }
                var dyROffset = batchOffset + dyR * dyStrides[1];
                var sourceFracRow = dyR * heightScale;
                var sourceNearestRow = Math.min(xHeight - 1, alignCorners ? Math.round(sourceFracRow) : Math.floor(sourceFracRow));
                if (r !== sourceNearestRow) {
                  continue;
                }
                for (var dyCIndex = 0; dyCIndex < winWidth; dyCIndex++) {
                  var dyC = dyCIndex + startDyC;
                  if (dyC < 0 || dyC >= yWidth) {
                    continue;
                  }
                  var dyCOffset = dyROffset + dyC * dyStrides[2];
                  var sourceFracCol = dyC * widthScale;
                  var sourceNearestCol = Math.min(xWidth - 1, alignCorners ? Math.round(sourceFracCol) : Math.floor(sourceFracCol));
                  if (c === sourceNearestCol) {
                    accum += dyValues[dyCOffset + d];
                  }
                }
              }
              output[colOffset + d] = accum;
            }
          }
        }
      }
      return backend.makeTensorInfo(images.shape, images.dtype, output);
    }
    var resizeNearestNeighborGradConfig = {
      kernelName: tfjsCore.ResizeNearestNeighborGrad,
      backendName: "cpu",
      kernelFunc: resizeNearestNeighborGrad
    };
    function reverse(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var dims = attrs.dims;
      assertNotComplex(x, "reverse");
      var xRank = x.shape.length;
      var $dims = tfjsCore.util.parseAxisParam(dims, x.shape);
      if (xRank === 0) {
        return identity({ inputs: { x }, backend });
      }
      var outBuf = new tfjsCore.TensorBuffer(x.shape, x.dtype);
      var xBuf = backend.bufferSync(x);
      var _loop_1 = function(i2) {
        var outLoc = outBuf.indexToLoc(i2);
        var inLoc = outLoc.slice();
        $dims.forEach(function(d) {
          return inLoc[d] = x.shape[d] - 1 - inLoc[d];
        });
        outBuf.set.apply(outBuf, __spreadArray([xBuf.get.apply(xBuf, __spreadArray([], __read(inLoc), false))], __read(outLoc), false));
      };
      for (var i = 0; i < outBuf.size; i++) {
        _loop_1(i);
      }
      return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);
    }
    var reverseConfig = {
      kernelName: tfjsCore.Reverse,
      backendName: "cpu",
      kernelFunc: reverse
    };
    var rotateWithOffsetConfig = {
      kernelName: tfjsCore.RotateWithOffset,
      backendName: "cpu",
      kernelFunc: function(_a2) {
        var inputs = _a2.inputs, attrs = _a2.attrs, backend = _a2.backend;
        var image = inputs.image;
        var radians = attrs.radians, fillValue = attrs.fillValue, center = attrs.center;
        var cpuBackend = backend;
        var output = tfjsCore.util.getTypedArrayFromDType(image.dtype, tfjsCore.util.sizeFromShape(image.shape));
        var _b = __read(image.shape, 4), batch = _b[0], imageHeight = _b[1], imageWidth = _b[2], numChannels = _b[3];
        var _c = __read(tfjsCore.backend_util.getImageCenter(center, imageHeight, imageWidth), 2), centerX = _c[0], centerY = _c[1];
        var fullOpacityValue = 255;
        var sinFactor = Math.sin(radians);
        var cosFactor = Math.cos(radians);
        var imageVals = cpuBackend.data.get(image.dataId).values;
        for (var batchIdx = 0; batchIdx < batch; batchIdx++) {
          var batchOffset = batchIdx * imageWidth * imageHeight * numChannels;
          for (var row = 0; row < imageHeight; row++) {
            var rowOffset = row * (imageWidth * numChannels);
            for (var col = 0; col < imageWidth; col++) {
              var colOffset = col * numChannels;
              for (var channel = 0; channel < numChannels; channel++) {
                var coords = [batch, row, col, channel];
                var x = coords[2];
                var y = coords[1];
                var coordX = (x - centerX) * cosFactor - (y - centerY) * sinFactor;
                var coordY = (x - centerX) * sinFactor + (y - centerY) * cosFactor;
                coordX = Math.round(coordX + centerX);
                coordY = Math.round(coordY + centerY);
                var outputValue = fillValue;
                if (typeof fillValue !== "number") {
                  if (channel === 3) {
                    outputValue = fullOpacityValue;
                  } else {
                    outputValue = fillValue[channel];
                  }
                }
                if (coordX >= 0 && coordX < imageWidth && coordY >= 0 && coordY < imageHeight) {
                  var rotatedRowOffset = coordY * (imageWidth * numChannels);
                  var rotatedColOffset = coordX * numChannels;
                  var imageIdx = batchOffset + rotatedRowOffset + rotatedColOffset + channel;
                  outputValue = imageVals[imageIdx];
                }
                var outIdx = batchOffset + rowOffset + colOffset + channel;
                output[outIdx] = outputValue;
              }
            }
          }
        }
        var dataId = cpuBackend.write(output, image.shape, image.dtype);
        return { dataId, shape: image.shape, dtype: image.dtype };
      }
    };
    var round = unaryKernelFunc(tfjsCore.Round, function(xi) {
      var base = Math.floor(xi);
      if (xi - base < 0.5) {
        return Math.floor(xi);
      } else if (xi - base > 0.5) {
        return Math.ceil(xi);
      } else {
        if (base % 2 === 0) {
          return base;
        } else {
          return base + 1;
        }
      }
    });
    var roundConfig = {
      kernelName: tfjsCore.Round,
      backendName: "cpu",
      kernelFunc: round
    };
    function scatterNd(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var indices = inputs.indices, updates = inputs.updates;
      var shape = attrs.shape;
      var _a2 = tfjsCore.backend_util.calculateShapes(updates, indices, shape), sliceRank = _a2.sliceRank, numUpdates = _a2.numUpdates, sliceSize = _a2.sliceSize, strides = _a2.strides, outputSize = _a2.outputSize;
      var sumDupeIndices = true;
      var indicesBuf = backend.bufferSync(indices);
      var updatesBuf = backend.bufferSync(updates);
      var outBuf = scatterImpl(indicesBuf, updatesBuf, shape, outputSize, sliceSize, numUpdates, sliceRank, strides, 0, sumDupeIndices);
      return backend.makeTensorInfo(shape, outBuf.dtype, outBuf.values);
    }
    var scatterNdConfig = {
      kernelName: tfjsCore.ScatterNd,
      backendName: "cpu",
      kernelFunc: scatterNd
    };
    function lowerBound(array, value) {
      var left = 0;
      var right = array.length;
      var mid = 0;
      while (left < right) {
        mid = Math.floor((left + right) / 2);
        if (array[mid] < value) {
          left = mid + 1;
        } else {
          right = mid;
        }
      }
      return right;
    }
    function upperBound(array, value) {
      var left = 0;
      var right = array.length;
      var mid = 0;
      while (left < right) {
        mid = Math.floor((left + right) / 2);
        if (array[mid] <= value) {
          left = mid + 1;
        } else {
          right = mid;
        }
      }
      return right;
    }
    function searchSortedImpl(sortedInputs, values, batchSize, numInputs, numValues, side) {
      var output = tfjsCore.util.getArrayFromDType("int32", batchSize * numValues);
      for (var b = 0; b < batchSize; ++b) {
        var sortedInputsSlice = sortedInputs.slice(b * numInputs, (b + 1) * numInputs);
        var outputOffset = b * numValues;
        for (var i = 0; i < numValues; ++i) {
          output[outputOffset + i] = side === "left" ? lowerBound(sortedInputsSlice, values[i + outputOffset]) : upperBound(sortedInputsSlice, values[i + outputOffset]);
        }
      }
      return output;
    }
    function searchSorted(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var sortedSequence = inputs.sortedSequence, values = inputs.values;
      var side = attrs.side;
      var $sortedSequence = backend.data.get(sortedSequence.dataId).values;
      var $values = backend.data.get(values.dataId).values;
      var output = searchSortedImpl($sortedSequence, $values, sortedSequence.shape[0], sortedSequence.shape[1], values.shape[1], side);
      return backend.makeTensorInfo(values.shape, "int32", output);
    }
    var searchSortedConfig = {
      kernelName: tfjsCore.SearchSorted,
      backendName: "cpu",
      kernelFunc: searchSorted
    };
    function select(args) {
      var inputs = args.inputs, backend = args.backend;
      var condition = inputs.condition, t = inputs.t, e = inputs.e;
      assertNotComplex([condition, t, e], "select");
      var conditionRank = condition.shape.length;
      var values = backend.data.get(condition.dataId).values;
      var tValues = backend.data.get(t.dataId).values;
      var eValues = backend.data.get(e.dataId).values;
      var resultDtype = tfjsCore.upcastType(t.dtype, e.dtype);
      var newValues = tfjsCore.util.makeZerosTypedArray(tfjsCore.util.sizeFromShape(t.shape), resultDtype);
      var index = 0;
      var offset = conditionRank === 0 || conditionRank > 1 || t.shape.length === 1 ? 1 : tfjsCore.util.sizeFromShape(t.shape.slice(1));
      for (var i = 0; i < values.length; i++) {
        for (var j = 0; j < offset; j++) {
          if (values[i] === 1) {
            newValues[index++] = tValues[i];
          } else {
            newValues[index++] = eValues[i];
          }
        }
      }
      return backend.makeTensorInfo(t.shape, resultDtype, newValues);
    }
    var selectConfig = {
      kernelName: tfjsCore.Select,
      backendName: "cpu",
      kernelFunc: select
    };
    var scaleAlpha = tfjsCore.backend_util.SELU_SCALEALPHA;
    var scale = tfjsCore.backend_util.SELU_SCALE;
    var selu = unaryKernelFunc(tfjsCore.Selu, function(xi) {
      if (xi >= 0) {
        return scale * xi;
      } else {
        return scaleAlpha * (Math.exp(xi) - 1);
      }
    });
    var seluConfig = {
      kernelName: tfjsCore.Selu,
      backendName: "cpu",
      kernelFunc: selu
    };
    var sign = unaryKernelFunc(tfjsCore.Sign, function(xi) {
      if (xi < 0) {
        return -1;
      } else if (xi > 0) {
        return 1;
      } else {
        return 0;
      }
    });
    var signConfig = {
      kernelName: tfjsCore.Sign,
      backendName: "cpu",
      kernelFunc: sign
    };
    var sin = unaryKernelFunc(tfjsCore.Sin, function(xi) {
      return Math.sin(xi);
    });
    var sinConfig = {
      kernelName: tfjsCore.Sin,
      backendName: "cpu",
      kernelFunc: sin
    };
    var sinh = unaryKernelFunc(tfjsCore.Sinh, function(xi) {
      return Math.sinh(xi);
    });
    var sinhConfig = {
      kernelName: tfjsCore.Sinh,
      backendName: "cpu",
      kernelFunc: sinh
    };
    var epsilon = 11920928955078125e-23;
    var threshold = Math.log(epsilon) + 2;
    var softplus = unaryKernelFunc(tfjsCore.Softplus, function(xi) {
      var tooLarge = xi > -threshold;
      var tooSmall = xi < threshold;
      var expX = Math.exp(xi);
      var result;
      if (tooSmall) {
        result = expX;
      } else if (tooLarge) {
        result = xi;
      } else {
        result = Math.log(1 + expX);
      }
      return result;
    });
    var softplusConfig = {
      kernelName: tfjsCore.Softplus,
      backendName: "cpu",
      kernelFunc: softplus
    };
    function spaceToBatchND(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var blockShape = attrs.blockShape, paddings = attrs.paddings;
      assertNotComplex([x], "spaceToBatchND");
      var prod2 = tfjsCore.util.sizeFromShape(blockShape);
      var completePaddings = [[0, 0]];
      completePaddings.push.apply(completePaddings, __spreadArray([], __read(paddings), false));
      for (var i = 1 + blockShape.length; i < x.shape.length; ++i) {
        completePaddings.push([0, 0]);
      }
      var paddedX = padV2Config.kernelFunc({
        inputs: { x },
        backend,
        attrs: { paddings: completePaddings, constantValue: 0 }
      });
      var reshapedPaddedShape = tfjsCore.backend_util.getReshaped(paddedX.shape, blockShape, prod2, false);
      var permutedReshapedPaddedPermutation = tfjsCore.backend_util.getPermuted(reshapedPaddedShape.length, blockShape.length, false);
      var flattenShape = tfjsCore.backend_util.getReshapedPermuted(paddedX.shape, blockShape, prod2, false);
      var reshapeInputs = { x: paddedX };
      var reshapeAttrs = { shape: reshapedPaddedShape };
      var paddedXReshaped = reshape({ inputs: reshapeInputs, backend, attrs: reshapeAttrs });
      var transposeInputs = { x: paddedXReshaped };
      var transposeAttrs = { perm: permutedReshapedPaddedPermutation };
      var paddedXT = transpose({ inputs: transposeInputs, backend, attrs: transposeAttrs });
      var resultReshapeInputs = { x: paddedXT };
      var resultReshapeAttrs = { shape: flattenShape };
      var result = reshape({ inputs: resultReshapeInputs, backend, attrs: resultReshapeAttrs });
      backend.disposeIntermediateTensorInfo(paddedX);
      backend.disposeIntermediateTensorInfo(paddedXReshaped);
      backend.disposeIntermediateTensorInfo(paddedXT);
      return result;
    }
    var spaceToBatchNDConfig = {
      kernelName: tfjsCore.SpaceToBatchND,
      backendName: "cpu",
      kernelFunc: spaceToBatchND
    };
    function sparseFillEmptyRows(args) {
      var inputs = args.inputs, backend = args.backend;
      var indices = inputs.indices, values = inputs.values, denseShape = inputs.denseShape, defaultValue = inputs.defaultValue;
      if (denseShape.shape.length !== 1) {
        throw new Error("Dense shape must be a vector, saw:\n        ".concat(denseShape.shape));
      }
      if (indices.shape.length !== 2) {
        throw new Error("Indices must be a matrix, saw:\n        ".concat(indices.shape));
      }
      if (values.shape.length !== 1) {
        throw new Error("Values must be a vector, saw:\n        ".concat(values.shape));
      }
      if (defaultValue.shape.length !== 0) {
        throw new Error("Default value must be a scalar, saw:\n        ".concat(defaultValue.shape));
      }
      var $indices = backend.data.get(indices.dataId).values;
      var $values = backend.data.get(values.dataId).values;
      var $denseShape = backend.data.get(denseShape.dataId).values;
      var $defaultValue = backend.data.get(defaultValue.dataId).values[0];
      var _a2 = __read(sparseFillEmptyRowsImpl($indices, indices.shape, indices.dtype, $values, values.dtype, $denseShape, $defaultValue), 5), outputIndices = _a2[0], outputIndicesShape = _a2[1], outputValues = _a2[2], emptyRowIndicator = _a2[3], reverseIndexMap = _a2[4];
      return [
        backend.makeTensorInfo(outputIndicesShape, indices.dtype, outputIndices),
        backend.makeTensorInfo([outputIndicesShape[0]], values.dtype, outputValues),
        backend.makeTensorInfo([emptyRowIndicator.length], "bool", new Uint8Array(emptyRowIndicator.map(function(value) {
          return Number(value);
        }))),
        backend.makeTensorInfo([reverseIndexMap.length], indices.dtype, new Int32Array(reverseIndexMap))
      ];
    }
    var sparseFillEmptyRowsConfig = {
      kernelName: tfjsCore.SparseFillEmptyRows,
      backendName: "cpu",
      kernelFunc: sparseFillEmptyRows
    };
    function sparseReshape(args) {
      var inputs = args.inputs, backend = args.backend;
      var inputIndices = inputs.inputIndices, inputShape = inputs.inputShape, newShape = inputs.newShape;
      if (inputIndices.shape.length !== 2) {
        throw new Error("Input indices should be a matrix but received shape\n        ".concat(inputIndices.shape));
      }
      if (inputShape.shape.length !== 1) {
        throw new Error("Input shape should be a vector but received shape\n        ".concat(inputShape.shape));
      }
      if (newShape.shape.length !== 1) {
        throw new Error("Target shape should be a vector but received shape ".concat(newShape.shape));
      }
      var $inputShape = Array.from(backend.data.get(inputShape.dataId).values);
      var $inputIndices = backend.data.get(inputIndices.dataId).values;
      var targetShape = Array.from(backend.data.get(newShape.dataId).values);
      var _a2 = __read(sparseReshapeImpl($inputIndices, inputIndices.shape, inputIndices.dtype, $inputShape, targetShape), 3), newIndices = _a2[0], indicesShape = _a2[1], outputShape = _a2[2];
      return [
        backend.makeTensorInfo(indicesShape, inputIndices.dtype, newIndices),
        backend.makeTensorInfo([outputShape.length], newShape.dtype, new Int32Array(outputShape))
      ];
    }
    var sparseReshapeConfig = {
      kernelName: tfjsCore.SparseReshape,
      backendName: "cpu",
      kernelFunc: sparseReshape
    };
    function sparseSegmentMean(args) {
      var inputs = args.inputs, backend = args.backend;
      var data = inputs.data, indices = inputs.indices, segmentIds = inputs.segmentIds;
      if (data.shape.length < 1) {
        throw new Error("Data should be at least 1 dimensional but received scalar");
      }
      if (indices.shape.length !== 1) {
        throw new Error("Indices should be a vector but received shape\n          ".concat(indices.shape));
      }
      if (segmentIds.shape.length !== 1) {
        throw new Error("Segment ids should be a vector but received shape\n          ".concat(segmentIds.shape));
      }
      if (indices.shape[0] !== segmentIds.shape[0]) {
        throw new Error("segmentIds and indices should have same size.");
      }
      var $data = backend.data.get(data.dataId).values;
      var $indices = backend.data.get(indices.dataId).values;
      var $segmentIds = backend.data.get(segmentIds.dataId).values;
      var _a2 = __read(sparseSegmentReductionImpl($data, data.shape, data.dtype, $indices, $segmentIds, true), 2), outputData = _a2[0], outputDataShape = _a2[1];
      return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);
    }
    var sparseSegmentMeanConfig = {
      kernelName: tfjsCore.SparseSegmentMean,
      backendName: "cpu",
      kernelFunc: sparseSegmentMean
    };
    function sparseSegmentSum(args) {
      var inputs = args.inputs, backend = args.backend;
      var data = inputs.data, indices = inputs.indices, segmentIds = inputs.segmentIds;
      if (data.shape.length < 1) {
        throw new Error("Data should be at least 1 dimensional but received scalar");
      }
      if (indices.shape.length !== 1) {
        throw new Error("Indices should be a vector but received shape\n         ".concat(indices.shape));
      }
      if (segmentIds.shape.length !== 1) {
        throw new Error("Segment ids should be a vector but received shape\n         ".concat(segmentIds.shape));
      }
      if (indices.shape[0] !== segmentIds.shape[0]) {
        throw new Error("segmentIds and indices should have same size.");
      }
      var $data = backend.data.get(data.dataId).values;
      var $indices = backend.data.get(indices.dataId).values;
      var $segmentIds = backend.data.get(segmentIds.dataId).values;
      var _a2 = __read(sparseSegmentReductionImpl($data, data.shape, data.dtype, $indices, $segmentIds), 2), outputData = _a2[0], outputDataShape = _a2[1];
      return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);
    }
    var sparseSegmentSumConfig = {
      kernelName: tfjsCore.SparseSegmentSum,
      backendName: "cpu",
      kernelFunc: sparseSegmentSum
    };
    function sparseToDense(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var sparseIndices = inputs.sparseIndices, sparseValues = inputs.sparseValues, defaultValue = inputs.defaultValue;
      var outputShape = attrs.outputShape;
      var _a2 = tfjsCore.backend_util.calculateShapes(sparseValues, sparseIndices, outputShape), sliceRank = _a2.sliceRank, numUpdates = _a2.numUpdates, sliceSize = _a2.sliceSize, strides = _a2.strides, outputSize = _a2.outputSize;
      var sumDupeIndices = false;
      var indicesBuf = backend.bufferSync(sparseIndices);
      var outBuf;
      switch (sparseValues.dtype) {
        case "bool": {
          var updatesBuf = backend.bufferSync(sparseValues);
          var $defaultValue = Boolean(backend.data.get(defaultValue.dataId).values[0]);
          outBuf = scatterImpl(indicesBuf, updatesBuf, outputShape, outputSize, sliceSize, numUpdates, sliceRank, strides, $defaultValue, sumDupeIndices);
          break;
        }
        case "float32": {
          var updatesBuf = backend.bufferSync(sparseValues);
          var $defaultValue = backend.data.get(defaultValue.dataId).values[0];
          outBuf = scatterImpl(indicesBuf, updatesBuf, outputShape, outputSize, sliceSize, numUpdates, sliceRank, strides, $defaultValue, sumDupeIndices);
          break;
        }
        case "int32": {
          var updatesBuf = backend.bufferSync(sparseValues);
          var $defaultValue = backend.data.get(defaultValue.dataId).values[0];
          outBuf = scatterImpl(indicesBuf, updatesBuf, outputShape, outputSize, sliceSize, numUpdates, sliceRank, strides, $defaultValue, sumDupeIndices);
          break;
        }
        case "string": {
          var updatesBuf = backend.bufferSync(sparseValues);
          var $defaultValue = tfjsCore.util.decodeString(backend.data.get(defaultValue.dataId).values[0]);
          outBuf = scatterImpl(indicesBuf, updatesBuf, outputShape, outputSize, sliceSize, numUpdates, sliceRank, strides, $defaultValue, sumDupeIndices);
          break;
        }
        default:
          throw new Error("Unsupported type ".concat(sparseValues.dtype));
      }
      return backend.makeTensorInfo(outputShape, outBuf.dtype, outBuf.values);
    }
    var sparseToDenseConfig = {
      kernelName: tfjsCore.SparseToDense,
      backendName: "cpu",
      kernelFunc: sparseToDense
    };
    function splitV(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var numOrSizeSplits = attrs.numOrSizeSplits, axis = attrs.axis;
      var $axis = tfjsCore.util.parseAxisParam(axis, x.shape)[0];
      var splitSizes = tfjsCore.backend_util.prepareSplitSize(x, numOrSizeSplits, $axis);
      var begin = new Array(x.shape.length).fill(0);
      var size = x.shape.slice();
      return splitSizes.map(function(s) {
        var sliceSize = __spreadArray([], __read(size), false);
        sliceSize[$axis] = s;
        var sliceT = slice({ inputs: { x }, backend, attrs: { begin, size: sliceSize } });
        begin[$axis] += s;
        return sliceT;
      });
    }
    var splitVConfig = {
      kernelName: tfjsCore.SplitV,
      backendName: "cpu",
      kernelFunc: splitV
    };
    var squareConfig = {
      kernelName: tfjsCore.Square,
      backendName: "cpu",
      kernelFunc: function(_a2) {
        var inputs = _a2.inputs, backend = _a2.backend;
        var x = inputs.x;
        var cpuBackend = backend;
        assertNotComplex(x, "square");
        var values = cpuBackend.data.get(x.dataId).values;
        var newValues = new Float32Array(values.length);
        for (var i = 0; i < values.length; ++i) {
          var value = values[i];
          newValues[i] = value * value;
        }
        var dataId = cpuBackend.write(newValues, x.shape, x.dtype);
        return { dataId, shape: x.shape, dtype: x.dtype };
      }
    };
    var step = unaryKernelFunc(tfjsCore.Step, function(xi, attrs) {
      var stepAttrs = attrs;
      if (isNaN(xi)) {
        return NaN;
      } else {
        return xi > 0 ? 1 : stepAttrs.alpha;
      }
    });
    var stepConfig = {
      kernelName: tfjsCore.Step,
      backendName: "cpu",
      kernelFunc: step
    };
    function stridedSlice(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var begin = attrs.begin, end = attrs.end, strides = attrs.strides, beginMask = attrs.beginMask, endMask = attrs.endMask, ellipsisMask = attrs.ellipsisMask, newAxisMask = attrs.newAxisMask, shrinkAxisMask = attrs.shrinkAxisMask;
      assertNotComplex(x, "stridedSlice");
      var _a2 = tfjsCore.slice_util.sliceInfo(x.shape, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask), finalShapeSparse = _a2.finalShapeSparse, finalShape = _a2.finalShape, isIdentity = _a2.isIdentity, sliceDim0 = _a2.sliceDim0, isSimpleSlice = _a2.isSimpleSlice, $begin = _a2.begin, $end = _a2.end, $strides = _a2.strides;
      var result;
      if (isIdentity) {
        result = reshape({ inputs: { x }, backend, attrs: { shape: finalShape } });
      } else if (sliceDim0 || isSimpleSlice) {
        tfjsCore.util.assert(x.shape.length >= 1, function() {
          return "Input must have rank at least 1, got: ".concat(x.shape.length);
        });
        var size = tfjsCore.slice_util.computeOutShape($begin, $end, $strides);
        var sliced = slice({ inputs: { x }, backend, attrs: { begin: $begin, size } });
        result = reshape({ inputs: { x: sliced }, backend, attrs: { shape: finalShape } });
        backend.disposeIntermediateTensorInfo(sliced);
      } else {
        var xBuf = backend.bufferSync(x);
        var outBuf = stridedSliceImpl(finalShapeSparse, xBuf, $strides, $begin);
        result = backend.makeTensorInfo(finalShape, outBuf.dtype, outBuf.values);
      }
      return result;
    }
    var stridedSliceConfig = {
      kernelName: tfjsCore.StridedSlice,
      backendName: "cpu",
      kernelFunc: stridedSlice
    };
    function stringNGrams(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var separator = attrs.separator, nGramWidths = attrs.nGramWidths, leftPad = attrs.leftPad, rightPad = attrs.rightPad, padWidth = attrs.padWidth, preserveShortSequences = attrs.preserveShortSequences;
      var data = inputs.data, dataSplits = inputs.dataSplits;
      var $data = backend.data.get(data.dataId).values;
      var $dataSplits = backend.data.get(dataSplits.dataId).values;
      var _a2 = __read(stringNGramsImpl($data, $dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences), 2), nGrams = _a2[0], nGramsSplits = _a2[1];
      return [
        backend.makeTensorInfo([nGrams.length], "string", nGrams),
        backend.makeTensorInfo(dataSplits.shape, "int32", nGramsSplits)
      ];
    }
    var stringNGramsConfig = {
      kernelName: tfjsCore.StringNGrams,
      backendName: "cpu",
      kernelFunc: stringNGrams
    };
    function stringSplit(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var skipEmpty = attrs.skipEmpty;
      var input = inputs.input, delimiter = inputs.delimiter;
      if (input.dtype !== "string") {
        throw new Error("Input must be of datatype string");
      }
      if (input.shape.length !== 1) {
        throw new Error("Input must be a vector, got shape: ".concat(input.shape));
      }
      if (delimiter.shape.length !== 0) {
        throw new Error("Delimiter must be a scalar, got shape: ".concat(delimiter.shape));
      }
      var $input = backend.data.get(input.dataId).values;
      var $delimiter = backend.data.get(delimiter.dataId).values[0];
      var _a2 = __read(stringSplitImpl($input, $delimiter, skipEmpty), 3), indices = _a2[0], values = _a2[1], shape = _a2[2];
      var outputSize = values.length;
      return [
        backend.makeTensorInfo([outputSize, 2], "int32", indices),
        backend.makeTensorInfo([outputSize], "string", values),
        backend.makeTensorInfo([2], "int32", new Int32Array(shape))
      ];
    }
    var stringSplitConfig = {
      kernelName: tfjsCore.StringSplit,
      backendName: "cpu",
      kernelFunc: stringSplit
    };
    function stringToHashBucketFast(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var numBuckets = attrs.numBuckets;
      var input = inputs.input;
      if (input.dtype !== "string") {
        throw new Error("Input must be of datatype string");
      }
      if (numBuckets <= 0) {
        throw new Error("Number of buckets must be at least 1");
      }
      var $input = backend.data.get(input.dataId).values;
      var output = stringToHashBucketFastImpl($input, numBuckets);
      return backend.makeTensorInfo(input.shape, "int32", output);
    }
    var stringToHashBucketFastConfig = {
      kernelName: tfjsCore.StringToHashBucketFast,
      backendName: "cpu",
      kernelFunc: stringToHashBucketFast
    };
    var tan = unaryKernelFunc(tfjsCore.Tan, function(xi) {
      return Math.tan(xi);
    });
    var tanConfig = {
      kernelName: tfjsCore.Tan,
      backendName: "cpu",
      kernelFunc: tan
    };
    var tanh = unaryKernelFunc(tfjsCore.Tanh, function(xi) {
      return Math.tanh(xi);
    });
    var tanhConfig = {
      kernelName: tfjsCore.Tanh,
      backendName: "cpu",
      kernelFunc: tanh
    };
    function tensorScatterUpdate(args) {
      var inputs = args.inputs, backend = args.backend;
      var tensor = inputs.tensor, indices = inputs.indices, updates = inputs.updates;
      var _a2 = tfjsCore.backend_util.calculateShapes(updates, indices, tensor.shape), sliceRank = _a2.sliceRank, numUpdates = _a2.numUpdates, sliceSize = _a2.sliceSize, strides = _a2.strides, outputSize = _a2.outputSize;
      var sumDupeIndices = false;
      var indicesBuf = backend.bufferSync(indices);
      var updatesBuf = backend.bufferSync(updates);
      var tensorBuf = backend.bufferSync(tensor);
      var outBuf = scatterImpl(indicesBuf, updatesBuf, tensor.shape, outputSize, sliceSize, numUpdates, sliceRank, strides, tensorBuf, sumDupeIndices);
      return backend.makeTensorInfo(tensor.shape, outBuf.dtype, outBuf.values);
    }
    var tensorScatterUpdateConfig = {
      kernelName: tfjsCore.TensorScatterUpdate,
      backendName: "cpu",
      kernelFunc: tensorScatterUpdate
    };
    function tile(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var reps = attrs.reps;
      assertNotComplex(x, "tile");
      var outBuf = tileImpl(backend.bufferSync(x), reps);
      return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);
    }
    var tileConfig = {
      kernelName: tfjsCore.Tile,
      backendName: "cpu",
      kernelFunc: tile
    };
    function topK(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var k = attrs.k, sorted = attrs.sorted;
      assertNotComplex(x, "topk");
      var xVals = backend.data.get(x.dataId).values;
      var _a2 = __read(topKImpl(xVals, x.shape, x.dtype, k, sorted), 2), allTopKVals = _a2[0], allTopKIndices = _a2[1];
      return [
        backend.makeTensorInfo(allTopKVals.shape, allTopKVals.dtype, allTopKVals.values),
        backend.makeTensorInfo(allTopKIndices.shape, allTopKIndices.dtype, allTopKIndices.values)
      ];
    }
    var topKConfig = {
      kernelName: tfjsCore.TopK,
      backendName: "cpu",
      kernelFunc: topK
    };
    function transform(args) {
      var inputs = args.inputs, attrs = args.attrs, backend = args.backend;
      var image = inputs.image, transforms = inputs.transforms;
      var interpolation = attrs.interpolation, fillMode = attrs.fillMode, fillValue = attrs.fillValue, outputShape = attrs.outputShape;
      var _a2 = __read(image.shape, 4), batch = _a2[0], imageHeight = _a2[1], imageWidth = _a2[2], numChannels = _a2[3];
      var _b = __read(outputShape != null ? outputShape : [imageHeight, imageWidth], 2), outHeight = _b[0], outWidth = _b[1];
      var outShape = [batch, outHeight, outWidth, numChannels];
      var inStrides = tfjsCore.util.computeStrides(image.shape);
      var batchInStride = inStrides[0];
      var rowInStride = inStrides[1];
      var colInStride = inStrides[2];
      var outStrides = tfjsCore.util.computeStrides(outShape);
      var batchOutStride = outStrides[0];
      var rowOutStride = outStrides[1];
      var colOutStride = outStrides[2];
      var outVals = tfjsCore.util.getTypedArrayFromDType(image.dtype, tfjsCore.util.sizeFromShape(outShape));
      outVals.fill(fillValue);
      var imageVals = backend.data.get(image.dataId).values;
      var transformVals = backend.data.get(transforms.dataId).values;
      for (var b = 0; b < batch; ++b) {
        var transform_1 = transforms.shape[0] === 1 ? transformVals : transformVals.subarray(b * 8, b * 8 + 8);
        for (var outY = 0; outY < outHeight; ++outY) {
          for (var outX = 0; outX < outWidth; ++outX) {
            for (var channel = 0; channel < numChannels; ++channel) {
              var val = void 0;
              var projection = transform_1[6] * outX + transform_1[7] * outY + 1;
              if (projection === 0) {
                continue;
              }
              var inX = (transform_1[0] * outX + transform_1[1] * outY + transform_1[2]) / projection;
              var inY = (transform_1[3] * outX + transform_1[4] * outY + transform_1[5]) / projection;
              var x = mapCoord(inX, imageWidth, fillMode);
              var y = mapCoord(inY, imageHeight, fillMode);
              switch (interpolation) {
                case "nearest":
                  val = nearestInterpolation(imageVals, imageHeight, imageWidth, batchInStride, rowInStride, colInStride, b, y, x, channel, fillValue);
                  break;
                case "bilinear":
                  val = bilinearInterpolation(imageVals, imageHeight, imageWidth, batchInStride, rowInStride, colInStride, b, y, x, channel, fillValue);
                  break;
                default:
                  throw new Error("Error in Transform: Expect 'nearest' or " + "'bilinear', but got ".concat(interpolation));
              }
              var ind = b * batchOutStride + outY * rowOutStride + outX * colOutStride + channel;
              outVals[ind] = val;
            }
          }
        }
        return backend.makeTensorInfo(outShape, image.dtype, outVals);
      }
      var dataId = backend.write(outVals, outShape, image.dtype);
      return { dataId, shape: image.shape, dtype: image.dtype };
    }
    var transformConfig = {
      kernelName: tfjsCore.Transform,
      backendName: "cpu",
      kernelFunc: transform
    };
    function mapCoord(outCoord, len, mode) {
      switch (mode) {
        case "reflect":
          return mapCoordReflect(outCoord, len);
        case "wrap":
          return mapCoordWrap(outCoord, len);
        case "nearest":
          return mapCoordNearest(outCoord, len);
        case "constant":
        default:
          return mapCoordConstant(outCoord);
      }
    }
    function mapCoordReflect(outCoord, len) {
      var inCoord = outCoord;
      if (inCoord < 0) {
        if (len <= 1) {
          inCoord = 0;
        } else {
          var sz2 = 2 * len;
          if (inCoord < sz2) {
            inCoord = sz2 * Math.trunc(-inCoord / sz2) + inCoord;
          }
          inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1;
        }
      } else if (inCoord > len - 1) {
        if (len <= 1) {
          inCoord = 0;
        } else {
          var sz2 = 2 * len;
          inCoord -= sz2 * Math.trunc(inCoord / sz2);
          if (inCoord >= len) {
            inCoord = sz2 - inCoord - 1;
          }
        }
      }
      return tfjsCore.util.clamp(0, inCoord, len - 1);
    }
    function mapCoordWrap(outCoord, len) {
      var inCoord = outCoord;
      if (inCoord < 0) {
        if (len <= 1) {
          inCoord = 0;
        } else {
          var sz = len - 1;
          inCoord += len * (Math.trunc(-inCoord / sz) + 1);
        }
      } else if (inCoord > len - 1) {
        if (len <= 1) {
          inCoord = 0;
        } else {
          var sz = len - 1;
          inCoord -= len * Math.trunc(inCoord / sz);
        }
      }
      return tfjsCore.util.clamp(0, inCoord, len - 1);
    }
    function mapCoordConstant(outCoord, len) {
      return outCoord;
    }
    function mapCoordNearest(outCoord, len) {
      return tfjsCore.util.clamp(0, outCoord, len - 1);
    }
    function readWithFillValue(imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride, batch, y, x, channel, fillValue) {
      var ind = batch * batchStride + y * rowStride + x * colStride + channel;
      if (0 <= y && y < imageHeight && 0 <= x && x < imageWidth) {
        return imageVals[ind];
      } else {
        return fillValue;
      }
    }
    function nearestInterpolation(imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride, batch, y, x, channel, fillValue) {
      var $y = Math.round(y);
      var $x = Math.round(x);
      return readWithFillValue(imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride, batch, $y, $x, channel, fillValue);
    }
    function bilinearInterpolation(imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride, batch, y, x, channel, fillValue) {
      var yFloor = Math.floor(y);
      var xFloor = Math.floor(x);
      var yCeil = yFloor + 1;
      var xCeil = xFloor + 1;
      var valueYFloor = (xCeil - x) * readWithFillValue(imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride, batch, yFloor, xFloor, channel, fillValue) + (x - xFloor) * readWithFillValue(imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride, batch, yFloor, xCeil, channel, fillValue);
      var valueYCeil = (xCeil - x) * readWithFillValue(imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride, batch, yCeil, xFloor, channel, fillValue) + (x - xFloor) * readWithFillValue(imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride, batch, yCeil, xCeil, channel, fillValue);
      return (yCeil - y) * valueYFloor + (y - yFloor) * valueYCeil;
    }
    function unique(args) {
      var inputs = args.inputs, attrs = args.attrs, backend = args.backend;
      var axis = attrs.axis;
      var x = inputs.x;
      assertNotComplex(x, "unique");
      var values = backend.data.get(x.dataId).values;
      var _a2 = uniqueImpl(values, axis, x.shape, x.dtype), outputValues = _a2.outputValues, outputShape = _a2.outputShape, indices = _a2.indices;
      return [
        backend.makeTensorInfo(outputShape, x.dtype, outputValues),
        backend.makeTensorInfo([indices.length], "int32", indices)
      ];
    }
    var uniqueConfig = {
      kernelName: tfjsCore.Unique,
      backendName: "cpu",
      kernelFunc: unique
    };
    function unpack(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var value = inputs.value;
      var axis = attrs.axis;
      if (axis < 0) {
        axis += value.shape.length;
      }
      var valueRank = value.shape.length;
      var num = value.shape[axis];
      var outShape = new Array(valueRank - 1);
      var outIndex = 0;
      for (var i = 0; i < valueRank; i++) {
        if (i !== axis) {
          outShape[outIndex++] = value.shape[i];
        }
      }
      var begin = new Array(valueRank).fill(0);
      var size = value.shape.slice();
      size[axis] = 1;
      var res = new Array(num);
      for (var i = 0; i < res.length; i++) {
        begin[axis] = i;
        var tempRes = slice({ inputs: { x: value }, backend, attrs: { begin, size } });
        res[i] = reshape({ inputs: { x: tempRes }, backend, attrs: { shape: outShape } });
        backend.disposeIntermediateTensorInfo(tempRes);
      }
      return res;
    }
    var unpackConfig = {
      kernelName: tfjsCore.Unpack,
      backendName: "cpu",
      kernelFunc: unpack
    };
    function unsortedSegmentSum(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, segmentIds = inputs.segmentIds;
      var numSegments = attrs.numSegments;
      assertNotComplex(x, "unsortedSegmentSum");
      var xRank = x.shape.length;
      var segmentIdsRank = segmentIds.shape.length;
      var res = [];
      var intermediates = [];
      var numIters = xRank - segmentIdsRank;
      var $segmentIds = segmentIds;
      for (var i = 0; i < numIters; ++i) {
        var expanded = expandDims({ inputs: { input: $segmentIds }, backend, attrs: { dim: i + 1 } });
        $segmentIds = expanded;
        intermediates.push(expanded);
      }
      for (var i = 0; i < numSegments; ++i) {
        var scalarValue = tfjsCore.util.createScalarValue(i, "int32");
        var segmentId = backend.makeTensorInfo([], "int32", scalarValue);
        var mask = equal({ inputs: { a: segmentId, b: $segmentIds }, backend });
        var maskCasted = cast({ inputs: { x: mask }, backend, attrs: { dtype: "float32" } });
        var mul = multiply({ inputs: { a: maskCasted, b: x }, backend });
        var sumTensorInfo = sum({ inputs: { x: mul }, backend, attrs: { axis: 0, keepDims: false } });
        res.push(sumTensorInfo);
        intermediates.push(segmentId);
        intermediates.push(mask);
        intermediates.push(maskCasted);
        intermediates.push(mul);
        intermediates.push(sumTensorInfo);
      }
      var result = pack({ inputs: res, backend, attrs: { axis: 0 } });
      intermediates.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return result;
    }
    var unsortedSegmentSumConfig = {
      kernelName: tfjsCore.UnsortedSegmentSum,
      backendName: "cpu",
      kernelFunc: unsortedSegmentSum
    };
    var e_1;
    var _a;
    var kernelConfigs = [
      _fusedMatMulConfig,
      absConfig,
      acosConfig,
      acoshConfig,
      addConfig,
      addNConfig,
      allConfig,
      anyConfig,
      argMaxConfig,
      argMinConfig,
      asinConfig,
      asinhConfig,
      atanConfig,
      atan2Config,
      atanhConfig,
      avgPoolConfig,
      avgPool3DConfig,
      avgPool3DGradConfig,
      avgPoolGradConfig,
      batchMatMulConfig,
      batchNormConfig,
      batchToSpaceNDConfig,
      bincountConfig,
      bitwiseAndConfig,
      broadcastArgsConfig,
      castConfig,
      ceilConfig,
      clipByValueConfig,
      complexConfig,
      complexAbsConfig,
      concatConfig,
      conv2DConfig,
      conv2DBackpropFilterConfig,
      conv2DBackpropInputConfig,
      conv3DConfig,
      conv3DBackpropFilterV2Config,
      conv3DBackpropInputV2Config,
      cosConfig,
      coshConfig,
      cropAndResizeConfig,
      cumprodConfig,
      cumsumConfig,
      denseBincountConfig,
      depthToSpaceConfig,
      depthwiseConv2dNativeConfig,
      depthwiseConv2dNativeBackpropFilterConfig,
      depthwiseConv2dNativeBackpropInputConfig,
      diagConfig,
      dilation2DConfig,
      dilation2DBackpropFilterConfig,
      dilation2DBackpropInputConfig,
      drawConfig,
      einsumConfig,
      eluConfig,
      eluGradConfig,
      equalConfig,
      erfConfig,
      expConfig,
      expandDimsConfig,
      expm1Config,
      fftConfig,
      fillConfig,
      flipLeftRightConfig,
      floorConfig,
      floorDivConfig,
      fusedConv2DConfig,
      fusedDepthwiseConv2DConfig,
      gatherNdConfig,
      gatherV2Config,
      greaterConfig,
      greaterEqualConfig,
      identityConfig,
      ifftConfig,
      imagConfig,
      isFiniteConfig,
      isInfConfig,
      isNaNConfig,
      leakyReluConfig,
      lessConfig,
      lessEqualConfig,
      linSpaceConfig,
      logConfig,
      log1pConfig,
      logicalAndConfig,
      logicalNotConfig,
      logicalOrConfig,
      LRNConfig,
      LRNGradConfig,
      maxConfig,
      maximumConfig,
      maxPoolConfig,
      maxPool3DConfig,
      maxPool3DGradConfig,
      maxPoolGradConfig,
      maxPoolWithArgmaxConfig,
      meanConfig,
      minConfig,
      minimumConfig,
      mirrorPadConfig,
      modConfig,
      multinomialConfig,
      multiplyConfig,
      negConfig,
      nonMaxSuppressionV3Config,
      nonMaxSuppressionV4Config,
      nonMaxSuppressionV5Config,
      notEqualConfig,
      oneHotConfig,
      onesLikeConfig,
      packConfig,
      padV2Config,
      powConfig,
      preluConfig,
      prodConfig,
      raggedGatherConfig,
      raggedRangeConfig,
      raggedTensorToTensorConfig,
      rangeConfig,
      realConfig,
      realDivConfig,
      reciprocalConfig,
      reluConfig,
      relu6Config,
      reshapeConfig,
      resizeBilinearConfig,
      resizeBilinearGradConfig,
      resizeNearestNeighborConfig,
      resizeNearestNeighborGradConfig,
      reverseConfig,
      rotateWithOffsetConfig,
      roundConfig,
      rsqrtConfig,
      scatterNdConfig,
      searchSortedConfig,
      selectConfig,
      seluConfig,
      sigmoidConfig,
      signConfig,
      sinConfig,
      sinhConfig,
      sliceConfig,
      softmaxConfig,
      softplusConfig,
      spaceToBatchNDConfig,
      sparseFillEmptyRowsConfig,
      sparseReshapeConfig,
      sparseSegmentMeanConfig,
      sparseSegmentSumConfig,
      sparseToDenseConfig,
      splitVConfig,
      sqrtConfig,
      squareConfig,
      squaredDifferenceConfig,
      staticRegexReplaceConfig,
      stepConfig,
      stridedSliceConfig,
      stringNGramsConfig,
      stringSplitConfig,
      stringToHashBucketFastConfig,
      subConfig,
      sumConfig,
      tanConfig,
      tanhConfig,
      tensorScatterUpdateConfig,
      tileConfig,
      topKConfig,
      transformConfig,
      transposeConfig,
      uniqueConfig,
      unpackConfig,
      unsortedSegmentSumConfig,
      zerosLikeConfig
    ];
    try {
      for (kernelConfigs_1 = __values(kernelConfigs), kernelConfigs_1_1 = kernelConfigs_1.next(); !kernelConfigs_1_1.done; kernelConfigs_1_1 = kernelConfigs_1.next()) {
        kernelConfig = kernelConfigs_1_1.value;
        tfjsCore.registerKernel(kernelConfig);
      }
    } catch (e_1_1) {
      e_1 = { error: e_1_1 };
    } finally {
      try {
        if (kernelConfigs_1_1 && !kernelConfigs_1_1.done && (_a = kernelConfigs_1.return)) _a.call(kernelConfigs_1);
      } finally {
        if (e_1) throw e_1.error;
      }
    }
    var kernelConfig;
    var kernelConfigs_1;
    var kernelConfigs_1_1;
    exports2.MathBackendCPU = MathBackendCPU;
    exports2.shared = shared;
    exports2.version_cpu = version;
  }
});

// node_modules/@tensorflow/tfjs-backend-webgl/dist/tf-backend-webgl.node.js
var require_tf_backend_webgl_node = __commonJS({
  "node_modules/@tensorflow/tfjs-backend-webgl/dist/tf-backend-webgl.node.js"(exports2) {
    "use strict";
    var tf = require_tf_core_node();
    function _interopNamespaceDefault(e) {
      var n = /* @__PURE__ */ Object.create(null);
      if (e) {
        Object.keys(e).forEach(function(k) {
          if (k !== "default") {
            var d = Object.getOwnPropertyDescriptor(e, k);
            Object.defineProperty(n, k, d.get ? d : {
              enumerable: true,
              get: function() {
                return e[k];
              }
            });
          }
        });
      }
      n.default = e;
      return n;
    }
    var tf__namespace = /* @__PURE__ */ _interopNamespaceDefault(tf);
    var extendStatics = function(d, b) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
        d2.__proto__ = b2;
      } || function(d2, b2) {
        for (var p in b2)
          if (Object.prototype.hasOwnProperty.call(b2, p))
            d2[p] = b2[p];
      };
      return extendStatics(d, b);
    };
    function __extends(d, b) {
      if (typeof b !== "function" && b !== null)
        throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
      extendStatics(d, b);
      function __() {
        this.constructor = d;
      }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }
    function __awaiter(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step2(generator.next(value));
          } catch (e) {
            reject(e);
          }
        }
        function rejected(value) {
          try {
            step2(generator["throw"](value));
          } catch (e) {
            reject(e);
          }
        }
        function step2(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step2((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    }
    function __generator(thisArg, body) {
      var _ = { label: 0, sent: function() {
        if (t[0] & 1)
          throw t[1];
        return t[1];
      }, trys: [], ops: [] }, f, y, t, g;
      return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
        return this;
      }), g;
      function verb(n) {
        return function(v) {
          return step2([n, v]);
        };
      }
      function step2(op) {
        if (f)
          throw new TypeError("Generator is already executing.");
        while (_)
          try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
              return t;
            if (y = 0, t)
              op = [op[0] & 2, t.value];
            switch (op[0]) {
              case 0:
              case 1:
                t = op;
                break;
              case 4:
                _.label++;
                return { value: op[1], done: false };
              case 5:
                _.label++;
                y = op[1];
                op = [0];
                continue;
              case 7:
                op = _.ops.pop();
                _.trys.pop();
                continue;
              default:
                if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                  _ = 0;
                  continue;
                }
                if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                  _.label = op[1];
                  break;
                }
                if (op[0] === 6 && _.label < t[1]) {
                  _.label = t[1];
                  t = op;
                  break;
                }
                if (t && _.label < t[2]) {
                  _.label = t[2];
                  _.ops.push(op);
                  break;
                }
                if (t[2])
                  _.ops.pop();
                _.trys.pop();
                continue;
            }
            op = body.call(thisArg, _);
          } catch (e) {
            op = [6, e];
            y = 0;
          } finally {
            f = t = 0;
          }
        if (op[0] & 5)
          throw op[1];
        return { value: op[0] ? op[1] : void 0, done: true };
      }
    }
    function __values(o) {
      var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
      if (m)
        return m.call(o);
      if (o && typeof o.length === "number")
        return {
          next: function() {
            if (o && i >= o.length)
              o = void 0;
            return { value: o && o[i++], done: !o };
          }
        };
      throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    }
    function __read(o, n) {
      var m = typeof Symbol === "function" && o[Symbol.iterator];
      if (!m)
        return o;
      var i = m.call(o), r, ar = [], e;
      try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
          ar.push(r.value);
      } catch (error) {
        e = { error };
      } finally {
        try {
          if (r && !r.done && (m = i["return"]))
            m.call(i);
        } finally {
          if (e)
            throw e.error;
        }
      }
      return ar;
    }
    function __spreadArray(to, from, pack2) {
      if (pack2 || arguments.length === 2)
        for (var i = 0, l = from.length, ar; i < l; i++) {
          if (ar || !(i in from)) {
            if (!ar)
              ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
          }
        }
      return to.concat(ar || Array.prototype.slice.call(from));
    }
    var contexts = {};
    var WEBGL_ATTRIBUTES = {
      alpha: false,
      antialias: false,
      premultipliedAlpha: false,
      preserveDrawingBuffer: false,
      depth: false,
      stencil: false,
      failIfMajorPerformanceCaveat: true
    };
    function setWebGLContext(webGLVersion, gl) {
      contexts[webGLVersion] = gl;
    }
    function getWebGLContext(webGLVersion, customCanvas) {
      if (!(webGLVersion in contexts) || customCanvas != null) {
        var newCtx = getWebGLRenderingContext(webGLVersion, customCanvas);
        if (newCtx !== null) {
          contexts[webGLVersion] = newCtx;
        } else {
          console.log("Could not get context for WebGL version", webGLVersion);
          return null;
        }
      }
      var gl = contexts[webGLVersion];
      if (gl == null || gl.isContextLost()) {
        delete contexts[webGLVersion];
        return getWebGLContext(webGLVersion);
      }
      gl.disable(gl.DEPTH_TEST);
      gl.disable(gl.STENCIL_TEST);
      gl.disable(gl.BLEND);
      gl.disable(gl.DITHER);
      gl.disable(gl.POLYGON_OFFSET_FILL);
      gl.disable(gl.SAMPLE_COVERAGE);
      gl.enable(gl.SCISSOR_TEST);
      gl.enable(gl.CULL_FACE);
      gl.cullFace(gl.BACK);
      return contexts[webGLVersion];
    }
    function createCanvas(webGLVersion) {
      if (!tf.env().getBool("IS_SAFARI") && typeof OffscreenCanvas !== "undefined" && webGLVersion === 2) {
        return new OffscreenCanvas(300, 150);
      } else if (typeof document !== "undefined") {
        return document.createElement("canvas");
      } else {
        throw new Error("Cannot create a canvas in this context");
      }
    }
    function getWebGLRenderingContext(webGLVersion, customCanvas) {
      if (webGLVersion !== 1 && webGLVersion !== 2) {
        throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");
      }
      var canvas = customCanvas == null ? createCanvas(webGLVersion) : customCanvas;
      canvas.addEventListener("webglcontextlost", function(ev) {
        ev.preventDefault();
        delete contexts[webGLVersion];
      }, false);
      if (tf.env().getBool("SOFTWARE_WEBGL_ENABLED")) {
        WEBGL_ATTRIBUTES.failIfMajorPerformanceCaveat = false;
      }
      if (webGLVersion === 1) {
        return (
          // tslint:disable-next-line
          canvas.getContext("webgl", WEBGL_ATTRIBUTES) || canvas.getContext("experimental-webgl", WEBGL_ATTRIBUTES)
        );
      }
      return canvas.getContext("webgl2", WEBGL_ATTRIBUTES);
    }
    var PackingScheme;
    (function(PackingScheme2) {
      PackingScheme2[PackingScheme2["DENSE"] = 0] = "DENSE";
      PackingScheme2[PackingScheme2["SHARED_BATCH"] = 1] = "SHARED_BATCH";
    })(PackingScheme || (PackingScheme = {}));
    var TextureUsage;
    (function(TextureUsage2) {
      TextureUsage2[TextureUsage2["RENDER"] = 0] = "RENDER";
      TextureUsage2[TextureUsage2["UPLOAD"] = 1] = "UPLOAD";
      TextureUsage2[TextureUsage2["PIXELS"] = 2] = "PIXELS";
      TextureUsage2[TextureUsage2["DOWNLOAD"] = 3] = "DOWNLOAD";
    })(TextureUsage || (TextureUsage = {}));
    var PhysicalTextureType;
    (function(PhysicalTextureType2) {
      PhysicalTextureType2[PhysicalTextureType2["UNPACKED_FLOAT16"] = 0] = "UNPACKED_FLOAT16";
      PhysicalTextureType2[PhysicalTextureType2["UNPACKED_FLOAT32"] = 1] = "UNPACKED_FLOAT32";
      PhysicalTextureType2[PhysicalTextureType2["PACKED_4X1_UNSIGNED_BYTE"] = 2] = "PACKED_4X1_UNSIGNED_BYTE";
      PhysicalTextureType2[PhysicalTextureType2["PACKED_2X2_FLOAT32"] = 3] = "PACKED_2X2_FLOAT32";
      PhysicalTextureType2[PhysicalTextureType2["PACKED_2X2_FLOAT16"] = 4] = "PACKED_2X2_FLOAT16";
    })(PhysicalTextureType || (PhysicalTextureType = {}));
    function getUnpackedMatrixTextureShapeWidthHeight(rows, columns) {
      return [columns, rows];
    }
    function getUnpackedArraySizeFromMatrixSize(matrixSize, channelsPerTexture) {
      return matrixSize * channelsPerTexture;
    }
    function getDenseTexShape(shape) {
      var size = tf.util.sizeFromShape(shape);
      var texelsNeeded = Math.ceil(size / 4);
      return tf.util.sizeToSquarishShape(texelsNeeded);
    }
    function getPackedMatrixTextureShapeWidthHeight(rows, columns) {
      return [
        Math.max(1, Math.ceil(columns / 2)),
        Math.max(1, Math.ceil(rows / 2))
      ];
    }
    function getPackedRGBAArraySizeFromMatrixShape(rows, columns) {
      var _a2 = __read(getPackedMatrixTextureShapeWidthHeight(rows, columns), 2), w = _a2[0], h = _a2[1];
      return w * h * 4;
    }
    function getTextureConfig(gl, textureHalfFloatExtension) {
      var glany = gl;
      var internalFormatFloat;
      var internalFormatHalfFloat;
      var internalFormatPackedHalfFloat;
      var internalFormatPackedFloat;
      var textureFormatFloat;
      var downloadTextureFormat;
      var downloadUnpackNumChannels;
      var defaultNumChannels;
      var textureTypeHalfFloat;
      var textureTypeFloat;
      if (tf.env().getNumber("WEBGL_VERSION") === 2) {
        internalFormatFloat = glany.R32F;
        internalFormatHalfFloat = glany.R16F;
        internalFormatPackedHalfFloat = glany.RGBA16F;
        internalFormatPackedFloat = glany.RGBA32F;
        textureFormatFloat = glany.RED;
        downloadUnpackNumChannels = 4;
        defaultNumChannels = 1;
        textureTypeHalfFloat = glany.HALF_FLOAT;
        textureTypeFloat = glany.FLOAT;
        downloadTextureFormat = glany.RGBA8;
      } else {
        internalFormatFloat = gl.RGBA;
        internalFormatHalfFloat = gl.RGBA;
        internalFormatPackedHalfFloat = gl.RGBA;
        internalFormatPackedFloat = glany.RGBA;
        textureFormatFloat = gl.RGBA;
        downloadUnpackNumChannels = 4;
        defaultNumChannels = 4;
        textureTypeHalfFloat = textureHalfFloatExtension != null ? textureHalfFloatExtension.HALF_FLOAT_OES : null;
        textureTypeFloat = gl.FLOAT;
        downloadTextureFormat = gl.RGBA;
      }
      return {
        internalFormatFloat,
        internalFormatHalfFloat,
        internalFormatPackedHalfFloat,
        internalFormatPackedFloat,
        textureFormatFloat,
        downloadTextureFormat,
        downloadUnpackNumChannels,
        defaultNumChannels,
        textureTypeHalfFloat,
        textureTypeFloat
      };
    }
    function callAndCheck(gl, func) {
      var returnValue = func();
      if (tf.env().getBool("DEBUG")) {
        checkWebGLError(gl);
      }
      return returnValue;
    }
    function checkWebGLError(gl) {
      var error = gl.getError();
      if (error !== gl.NO_ERROR) {
        throw new Error("WebGL Error: " + getWebGLErrorMessage(gl, error));
      }
    }
    var MIN_FLOAT16 = 596e-10;
    var MAX_FLOAT16 = 65504;
    function canBeRepresented(num) {
      if (tf.env().getBool("WEBGL_RENDER_FLOAT32_ENABLED") || num === 0 || MIN_FLOAT16 < Math.abs(num) && Math.abs(num) < MAX_FLOAT16) {
        return true;
      }
      return false;
    }
    function getWebGLErrorMessage(gl, status) {
      switch (status) {
        case gl.NO_ERROR:
          return "NO_ERROR";
        case gl.INVALID_ENUM:
          return "INVALID_ENUM";
        case gl.INVALID_VALUE:
          return "INVALID_VALUE";
        case gl.INVALID_OPERATION:
          return "INVALID_OPERATION";
        case gl.INVALID_FRAMEBUFFER_OPERATION:
          return "INVALID_FRAMEBUFFER_OPERATION";
        case gl.OUT_OF_MEMORY:
          return "OUT_OF_MEMORY";
        case gl.CONTEXT_LOST_WEBGL:
          return "CONTEXT_LOST_WEBGL";
        default:
          return "Unknown error code ".concat(status);
      }
    }
    function getExtensionOrThrow(gl, extensionName) {
      return throwIfNull(gl, function() {
        return gl.getExtension(extensionName);
      }, 'Extension "' + extensionName + '" not supported on this browser.');
    }
    function createVertexShader$1(gl, vertexShaderSource) {
      var vertexShader = throwIfNull(gl, function() {
        return gl.createShader(gl.VERTEX_SHADER);
      }, "Unable to create vertex WebGLShader.");
      callAndCheck(gl, function() {
        return gl.shaderSource(vertexShader, vertexShaderSource);
      });
      callAndCheck(gl, function() {
        return gl.compileShader(vertexShader);
      });
      if (gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS) === false) {
        console.log(gl.getShaderInfoLog(vertexShader));
        throw new Error("Failed to compile vertex shader.");
      }
      return vertexShader;
    }
    function createFragmentShader(gl, fragmentShaderSource) {
      var fragmentShader = throwIfNull(gl, function() {
        return gl.createShader(gl.FRAGMENT_SHADER);
      }, "Unable to create fragment WebGLShader.");
      callAndCheck(gl, function() {
        return gl.shaderSource(fragmentShader, fragmentShaderSource);
      });
      callAndCheck(gl, function() {
        return gl.compileShader(fragmentShader);
      });
      if (tf.env().get("ENGINE_COMPILE_ONLY")) {
        return fragmentShader;
      }
      if (gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS) === false) {
        logShaderSourceAndInfoLog(fragmentShaderSource, gl.getShaderInfoLog(fragmentShader));
        throw new Error("Failed to compile fragment shader.");
      }
      return fragmentShader;
    }
    var lineNumberRegex = /ERROR: [0-9]+:([0-9]+):/g;
    function logShaderSourceAndInfoLog(shaderSource, shaderInfoLog) {
      var lineNumberRegexResult = lineNumberRegex.exec(shaderInfoLog);
      if (lineNumberRegexResult == null) {
        console.log("Couldn't parse line number in error: ".concat(shaderInfoLog));
        console.log(shaderSource);
        return;
      }
      var lineNumber = +lineNumberRegexResult[1];
      var shaderLines = shaderSource.split("\n");
      var pad = shaderLines.length.toString().length + 2;
      var linesWithLineNumbers = shaderLines.map(function(line, lineNumber2) {
        return tf.util.rightPad((lineNumber2 + 1).toString(), pad) + line;
      });
      var maxLineLength = 0;
      for (var i = 0; i < linesWithLineNumbers.length; i++) {
        maxLineLength = Math.max(linesWithLineNumbers[i].length, maxLineLength);
      }
      var beforeErrorLines = linesWithLineNumbers.slice(0, lineNumber - 1);
      var errorLine = linesWithLineNumbers.slice(lineNumber - 1, lineNumber);
      var afterErrorLines = linesWithLineNumbers.slice(lineNumber);
      console.log(beforeErrorLines.join("\n"));
      console.log(shaderInfoLog.split("\n")[0]);
      console.log("%c ".concat(tf.util.rightPad(errorLine[0], maxLineLength)), "border:1px solid red; background-color:#e3d2d2; color:#a61717");
      console.log(afterErrorLines.join("\n"));
    }
    function createProgram(gl) {
      return throwIfNull(gl, function() {
        return gl.createProgram();
      }, "Unable to create WebGLProgram.");
    }
    function linkProgram(gl, program) {
      callAndCheck(gl, function() {
        return gl.linkProgram(program);
      });
      if (tf.env().get("ENGINE_COMPILE_ONLY")) {
        return;
      }
      if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
        console.log(gl.getProgramInfoLog(program));
        throw new Error("Failed to link vertex and fragment shaders.");
      }
    }
    function validateProgram(gl, program) {
      callAndCheck(gl, function() {
        return gl.validateProgram(program);
      });
      if (gl.getProgramParameter(program, gl.VALIDATE_STATUS) === false) {
        console.log(gl.getProgramInfoLog(program));
        throw new Error("Shader program validation failed.");
      }
    }
    function createStaticVertexBuffer(gl, data) {
      var buffer = throwIfNull(gl, function() {
        return gl.createBuffer();
      }, "Unable to create WebGLBuffer");
      callAndCheck(gl, function() {
        return gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
      });
      callAndCheck(gl, function() {
        return gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
      });
      return buffer;
    }
    function createStaticIndexBuffer(gl, data) {
      var buffer = throwIfNull(gl, function() {
        return gl.createBuffer();
      }, "Unable to create WebGLBuffer");
      callAndCheck(gl, function() {
        return gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer);
      });
      callAndCheck(gl, function() {
        return gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data, gl.STATIC_DRAW);
      });
      return buffer;
    }
    function getNumChannels() {
      if (tf.env().getNumber("WEBGL_VERSION") === 2) {
        return 1;
      }
      return 4;
    }
    function createTexture(gl) {
      return throwIfNull(gl, function() {
        return gl.createTexture();
      }, "Unable to create WebGLTexture.");
    }
    function validateTextureSize(width, height) {
      var maxTextureSize = tf.env().getNumber("WEBGL_MAX_TEXTURE_SIZE");
      if (width <= 0 || height <= 0) {
        var requested = "[".concat(width, "x").concat(height, "]");
        throw new Error("Requested texture size " + requested + " is invalid.");
      }
      if (width > maxTextureSize || height > maxTextureSize) {
        var requested = "[".concat(width, "x").concat(height, "]");
        var max2 = "[".concat(maxTextureSize, "x").concat(maxTextureSize, "]");
        throw new Error("Requested texture size " + requested + " greater than WebGL maximum on this browser / GPU " + max2 + ".");
      }
    }
    function createFramebuffer(gl) {
      return throwIfNull(gl, function() {
        return gl.createFramebuffer();
      }, "Unable to create WebGLFramebuffer.");
    }
    function bindVertexBufferToProgramAttribute(gl, program, attribute, buffer, arrayEntriesPerItem, itemStrideInBytes, itemOffsetInBytes) {
      var loc = gl.getAttribLocation(program, attribute);
      if (loc === -1) {
        return false;
      }
      callAndCheck(gl, function() {
        return gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
      });
      callAndCheck(gl, function() {
        return gl.vertexAttribPointer(loc, arrayEntriesPerItem, gl.FLOAT, false, itemStrideInBytes, itemOffsetInBytes);
      });
      callAndCheck(gl, function() {
        return gl.enableVertexAttribArray(loc);
      });
      return true;
    }
    function bindTextureUnit(gl, texture, textureUnit) {
      validateTextureUnit(gl, textureUnit);
      callAndCheck(gl, function() {
        return gl.activeTexture(gl.TEXTURE0 + textureUnit);
      });
      callAndCheck(gl, function() {
        return gl.bindTexture(gl.TEXTURE_2D, texture);
      });
    }
    function unbindTextureUnit(gl, textureUnit) {
      validateTextureUnit(gl, textureUnit);
      callAndCheck(gl, function() {
        return gl.activeTexture(gl.TEXTURE0 + textureUnit);
      });
      callAndCheck(gl, function() {
        return gl.bindTexture(gl.TEXTURE_2D, null);
      });
    }
    function getProgramUniformLocationOrThrow(gl, program, uniformName) {
      return throwIfNull(gl, function() {
        return gl.getUniformLocation(program, uniformName);
      }, 'uniform "' + uniformName + '" not present in program.');
    }
    function getProgramUniformLocation(gl, program, uniformName) {
      return gl.getUniformLocation(program, uniformName);
    }
    function bindTextureToProgramUniformSampler(gl, texture, uniformSamplerLocation, textureUnit) {
      callAndCheck(gl, function() {
        return bindTextureUnit(gl, texture, textureUnit);
      });
      callAndCheck(gl, function() {
        return gl.uniform1i(uniformSamplerLocation, textureUnit);
      });
    }
    function bindCanvasToFramebuffer(gl) {
      callAndCheck(gl, function() {
        return gl.bindFramebuffer(gl.FRAMEBUFFER, null);
      });
      callAndCheck(gl, function() {
        return gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
      });
      callAndCheck(gl, function() {
        return gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
      });
    }
    function bindColorTextureToFramebuffer(gl, texture, framebuffer) {
      callAndCheck(gl, function() {
        return gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
      });
      callAndCheck(gl, function() {
        return gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
      });
    }
    function unbindColorTextureFromFramebuffer(gl, framebuffer) {
      callAndCheck(gl, function() {
        return gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
      });
      callAndCheck(gl, function() {
        return gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, null, 0);
      });
    }
    function validateFramebuffer(gl) {
      var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
      if (status !== gl.FRAMEBUFFER_COMPLETE) {
        throw new Error("Error binding framebuffer: " + getFramebufferErrorMessage(gl, status));
      }
    }
    function getFramebufferErrorMessage(gl, status) {
      switch (status) {
        case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
          return "FRAMEBUFFER_INCOMPLETE_ATTACHMENT";
        case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
          return "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";
        case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
          return "FRAMEBUFFER_INCOMPLETE_DIMENSIONS";
        case gl.FRAMEBUFFER_UNSUPPORTED:
          return "FRAMEBUFFER_UNSUPPORTED";
        default:
          return "unknown error ".concat(status);
      }
    }
    function throwIfNull(gl, returnTOrNull, failureMessage) {
      var tOrNull = callAndCheck(gl, function() {
        return returnTOrNull();
      });
      if (tOrNull == null) {
        throw new Error(failureMessage);
      }
      return tOrNull;
    }
    function validateTextureUnit(gl, textureUnit) {
      var maxTextureUnit = gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1;
      var glTextureUnit = textureUnit + gl.TEXTURE0;
      if (glTextureUnit < gl.TEXTURE0 || glTextureUnit > maxTextureUnit) {
        var textureUnitRange = "[gl.TEXTURE0, gl.TEXTURE".concat(maxTextureUnit, "]");
        throw new Error("textureUnit must be in ".concat(textureUnitRange, "."));
      }
    }
    function getBatchDim(shape, dimsToSkip) {
      if (dimsToSkip === void 0) {
        dimsToSkip = 2;
      }
      return tf.util.sizeFromShape(shape.slice(0, shape.length - dimsToSkip));
    }
    function getRowsCols(shape) {
      if (shape.length === 0) {
        throw Error("Cannot get rows and columns of an empty shape array.");
      }
      return [
        shape.length > 1 ? shape[shape.length - 2] : 1,
        shape[shape.length - 1]
      ];
    }
    function getShapeAs3D(shape) {
      var shapeAs3D = [1, 1, 1];
      var isScalar = shape.length === 0 || shape.length === 1 && shape[0] === 1;
      if (!isScalar) {
        shapeAs3D = __spreadArray([getBatchDim(shape)], __read(getRowsCols(shape)), false);
      }
      return shapeAs3D;
    }
    function getTextureShapeFromLogicalShape(logShape, isPacked) {
      var _a2;
      if (isPacked === void 0) {
        isPacked = false;
      }
      var maxTexSize = tf.env().getNumber("WEBGL_MAX_TEXTURE_SIZE");
      var maxSizeForNarrowTex = tf.env().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");
      if (maxSizeForNarrowTex === Infinity && tf.env().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")) {
        maxSizeForNarrowTex = maxTexSize / 2;
      }
      if (isPacked) {
        maxTexSize = maxTexSize * 2;
        maxSizeForNarrowTex = maxSizeForNarrowTex * 2;
        logShape = logShape.map(function(d, i) {
          return i >= logShape.length - 2 ? tf.util.nearestLargerEven(logShape[i]) : logShape[i];
        });
        if (logShape.length === 1) {
          logShape = [2, logShape[0]];
        }
      }
      if (logShape.length !== 2) {
        var squeezeResult = tf.util.squeezeShape(logShape);
        logShape = squeezeResult.newShape;
      }
      var size = tf.util.sizeFromShape(logShape);
      var textureShape = null;
      if (logShape.length <= 1 && size <= maxTexSize) {
        textureShape = [1, size];
      } else if (logShape.length === 2 && logShape[0] <= maxTexSize && logShape[1] <= maxTexSize) {
        textureShape = logShape;
      } else if (logShape.length === 3 && logShape[0] * logShape[1] <= maxTexSize && logShape[2] <= maxTexSize) {
        textureShape = [logShape[0] * logShape[1], logShape[2]];
      } else if (logShape.length === 3 && logShape[0] <= maxTexSize && logShape[1] * logShape[2] <= maxTexSize) {
        textureShape = [logShape[0], logShape[1] * logShape[2]];
      } else if (logShape.length === 4 && logShape[0] * logShape[1] * logShape[2] <= maxTexSize && logShape[3] <= maxTexSize) {
        textureShape = [logShape[0] * logShape[1] * logShape[2], logShape[3]];
      } else if (logShape.length === 4 && logShape[0] <= maxTexSize && logShape[1] * logShape[2] * logShape[3] <= maxTexSize) {
        textureShape = [logShape[0], logShape[1] * logShape[2] * logShape[3]];
      }
      var isLongNarrowTex = textureShape != null && Math.max.apply(Math, __spreadArray([], __read(textureShape), false)) > maxSizeForNarrowTex && Math.min.apply(Math, __spreadArray([], __read(textureShape), false)) <= (isPacked ? 2 : 1) && Math.min.apply(Math, __spreadArray([], __read(textureShape), false)) > 0;
      if (textureShape == null || isLongNarrowTex) {
        if (isPacked) {
          var batchDim = getBatchDim(logShape);
          var rows = 2, cols = 2;
          if (logShape.length) {
            _a2 = __read(getRowsCols(logShape), 2), rows = _a2[0], cols = _a2[1];
          }
          size = batchDim * (rows / 2) * (cols / 2);
          textureShape = tf.util.sizeToSquarishShape(size).map(function(d) {
            return d * 2;
          });
        } else {
          textureShape = tf.util.sizeToSquarishShape(size);
        }
      }
      return textureShape;
    }
    function isEven(n) {
      return n % 2 === 0;
    }
    function isReshapeFree(shape1, shape2) {
      shape1 = shape1.slice(-2);
      shape2 = shape2.slice(-2);
      if (tf.util.arraysEqual(shape1, shape2)) {
        return true;
      }
      if (!shape1.length || !shape2.length) {
        return true;
      }
      if (shape1[0] === 0 || shape1[1] === 0 || shape2[0] === 0 || shape2[1] === 0) {
        return true;
      }
      if (shape1.length !== shape2.length) {
        var shape1Cols = shape1[shape1.length - 1];
        var shape2Cols = shape2[shape2.length - 1];
        if (shape1Cols === shape2Cols) {
          return true;
        }
        if (isEven(shape1Cols) && isEven(shape2Cols) && (shape1[0] === 1 || shape2[0] === 1)) {
          return true;
        }
      }
      return shape1[1] === shape2[1] && isEven(shape1[0]) && isEven(shape2[0]);
    }
    var MAX_TEXTURE_SIZE;
    var MAX_TEXTURES_IN_SHADER;
    function getWebGLMaxTextureSize(webGLVersion) {
      if (MAX_TEXTURE_SIZE == null) {
        var gl = getWebGLContext(webGLVersion);
        MAX_TEXTURE_SIZE = gl.getParameter(gl.MAX_TEXTURE_SIZE);
      }
      return MAX_TEXTURE_SIZE;
    }
    function resetMaxTextureSize() {
      MAX_TEXTURE_SIZE = null;
    }
    function resetMaxTexturesInShader() {
      MAX_TEXTURES_IN_SHADER = null;
    }
    function getMaxTexturesInShader(webGLVersion) {
      if (MAX_TEXTURES_IN_SHADER == null) {
        var gl = getWebGLContext(webGLVersion);
        MAX_TEXTURES_IN_SHADER = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
      }
      return Math.min(16, MAX_TEXTURES_IN_SHADER);
    }
    function getWebGLDisjointQueryTimerVersion(webGLVersion) {
      if (webGLVersion === 0) {
        return 0;
      }
      var queryTimerVersion;
      var gl = getWebGLContext(webGLVersion);
      if (hasExtension(gl, "EXT_disjoint_timer_query_webgl2") && webGLVersion === 2) {
        queryTimerVersion = 2;
      } else if (hasExtension(gl, "EXT_disjoint_timer_query")) {
        queryTimerVersion = 1;
      } else {
        queryTimerVersion = 0;
      }
      return queryTimerVersion;
    }
    function hasExtension(gl, extensionName) {
      var ext = gl.getExtension(extensionName);
      return ext != null;
    }
    function isWebGLVersionEnabled(webGLVersion) {
      try {
        var gl = getWebGLContext(webGLVersion);
        if (gl != null) {
          return true;
        }
      } catch (e) {
        console.log("Error when getting WebGL context: ", e);
        return false;
      }
      return false;
    }
    function isCapableOfRenderingToFloatTexture(webGLVersion) {
      if (webGLVersion === 0) {
        return false;
      }
      var gl = getWebGLContext(webGLVersion);
      if (webGLVersion === 1) {
        if (!hasExtension(gl, "OES_texture_float")) {
          return false;
        }
      } else {
        if (!hasExtension(gl, "EXT_color_buffer_float")) {
          return false;
        }
      }
      var isFrameBufferComplete = createFloatTextureAndBindToFramebuffer(gl);
      return isFrameBufferComplete;
    }
    function isDownloadFloatTextureEnabled(webGLVersion) {
      if (webGLVersion === 0) {
        return false;
      }
      var gl = getWebGLContext(webGLVersion);
      if (webGLVersion === 1) {
        if (!hasExtension(gl, "OES_texture_float")) {
          return false;
        }
        if (!hasExtension(gl, "WEBGL_color_buffer_float")) {
          return false;
        }
      } else {
        if (hasExtension(gl, "EXT_color_buffer_float")) {
          return createFloatTextureAndBindToFramebuffer(gl);
        }
        var COLOR_BUFFER_HALF_FLOAT = "EXT_color_buffer_half_float";
        if (hasExtension(gl, COLOR_BUFFER_HALF_FLOAT)) {
          var textureHalfFloatExtension = gl.getExtension(COLOR_BUFFER_HALF_FLOAT);
          return createHalfFloatTextureAndBindToFramebuffer(gl, textureHalfFloatExtension);
        }
        return false;
      }
      var isFrameBufferComplete = createFloatTextureAndBindToFramebuffer(gl);
      return isFrameBufferComplete;
    }
    function createFloatTextureAndBindToFramebuffer(gl) {
      var texConfig = getTextureConfig(gl);
      var texture = gl.createTexture();
      gl.bindTexture(gl.TEXTURE_2D, texture);
      var width = 1;
      var height = 1;
      gl.texImage2D(gl.TEXTURE_2D, 0, texConfig.internalFormatFloat, width, height, 0, texConfig.textureFormatFloat, texConfig.textureTypeFloat, null);
      var frameBuffer = gl.createFramebuffer();
      gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
      gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
      var isFrameBufferComplete = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
      gl.bindTexture(gl.TEXTURE_2D, null);
      gl.bindFramebuffer(gl.FRAMEBUFFER, null);
      gl.deleteTexture(texture);
      gl.deleteFramebuffer(frameBuffer);
      return isFrameBufferComplete;
    }
    function createHalfFloatTextureAndBindToFramebuffer(gl, textureHalfFloatExtension) {
      var texConfig = getTextureConfig(gl, textureHalfFloatExtension);
      var texture = gl.createTexture();
      gl.bindTexture(gl.TEXTURE_2D, texture);
      var width = 1;
      var height = 1;
      gl.texImage2D(gl.TEXTURE_2D, 0, texConfig.internalFormatHalfFloat, width, height, 0, texConfig.textureFormatFloat, texConfig.textureTypeHalfFloat, null);
      var frameBuffer = gl.createFramebuffer();
      gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
      gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
      var isFrameBufferComplete = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
      gl.bindTexture(gl.TEXTURE_2D, null);
      gl.bindFramebuffer(gl.FRAMEBUFFER, null);
      gl.deleteTexture(texture);
      gl.deleteFramebuffer(frameBuffer);
      return isFrameBufferComplete;
    }
    function isWebGLFenceEnabled(webGLVersion) {
      if (webGLVersion !== 2) {
        return false;
      }
      var gl = getWebGLContext(webGLVersion);
      var isEnabled = gl.fenceSync != null;
      return isEnabled;
    }
    function assertNotComplex(tensor, opName) {
      if (!Array.isArray(tensor)) {
        tensor = [tensor];
      }
      tensor.forEach(function(t) {
        if (t != null) {
          tf.util.assert(t.dtype !== "complex64", function() {
            return "".concat(opName, " does not support complex64 tensors ") + "in the WebGL backend.";
          });
        }
      });
    }
    var webgl_util = {
      __proto__: null,
      assertNotComplex,
      bindCanvasToFramebuffer,
      bindColorTextureToFramebuffer,
      bindTextureToProgramUniformSampler,
      bindTextureUnit,
      bindVertexBufferToProgramAttribute,
      callAndCheck,
      canBeRepresented,
      createFragmentShader,
      createFramebuffer,
      createProgram,
      createStaticIndexBuffer,
      createStaticVertexBuffer,
      createTexture,
      createVertexShader: createVertexShader$1,
      getBatchDim,
      getExtensionOrThrow,
      getFramebufferErrorMessage,
      getMaxTexturesInShader,
      getNumChannels,
      getProgramUniformLocation,
      getProgramUniformLocationOrThrow,
      getRowsCols,
      getShapeAs3D,
      getTextureShapeFromLogicalShape,
      getWebGLDisjointQueryTimerVersion,
      getWebGLErrorMessage,
      getWebGLMaxTextureSize,
      hasExtension,
      isCapableOfRenderingToFloatTexture,
      isDownloadFloatTextureEnabled,
      isReshapeFree,
      isWebGLFenceEnabled,
      isWebGLVersionEnabled,
      linkProgram,
      logShaderSourceAndInfoLog,
      resetMaxTextureSize,
      resetMaxTexturesInShader,
      unbindColorTextureFromFramebuffer,
      unbindTextureUnit,
      validateFramebuffer,
      validateProgram,
      validateTextureSize
    };
    var ENV = tf.env();
    ENV.registerFlag("HAS_WEBGL", function() {
      return ENV.getNumber("WEBGL_VERSION") > 0;
    });
    ENV.registerFlag("WEBGL_VERSION", function() {
      if (isWebGLVersionEnabled(2)) {
        return 2;
      } else if (isWebGLVersionEnabled(1)) {
        return 1;
      }
      return 0;
    });
    ENV.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS", function() {
      return false;
    });
    ENV.registerFlag("WEBGL_BUFFER_SUPPORTED", function() {
      return ENV.get("WEBGL_VERSION") === 2;
    });
    ENV.registerFlag("WEBGL_CPU_FORWARD", function() {
      return true;
    });
    ENV.registerFlag("WEBGL_FORCE_F16_TEXTURES", function() {
      return false;
    });
    ENV.registerFlag("WEBGL_PACK", function() {
      return ENV.getBool("HAS_WEBGL");
    });
    ENV.registerFlag("WEBGL_PACK_NORMALIZATION", function() {
      return ENV.getBool("WEBGL_PACK");
    });
    ENV.registerFlag("WEBGL_PACK_CLIP", function() {
      return ENV.getBool("WEBGL_PACK");
    });
    ENV.registerFlag("WEBGL_PACK_DEPTHWISECONV", function() {
      return ENV.getBool("WEBGL_PACK");
    });
    ENV.registerFlag("WEBGL_PACK_BINARY_OPERATIONS", function() {
      return ENV.getBool("WEBGL_PACK");
    });
    ENV.registerFlag("WEBGL_PACK_UNARY_OPERATIONS", function() {
      return ENV.getBool("WEBGL_PACK");
    });
    ENV.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS", function() {
      return ENV.getBool("WEBGL_PACK");
    });
    ENV.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS", function() {
      return ENV.getBool("WEBGL_PACK");
    });
    ENV.registerFlag("WEBGL_PACK_REDUCE", function() {
      return ENV.getBool("WEBGL_PACK");
    });
    ENV.registerFlag("WEBGL_LAZILY_UNPACK", function() {
      return ENV.getBool("WEBGL_PACK");
    });
    ENV.registerFlag("WEBGL_CONV_IM2COL", function() {
      return ENV.getBool("WEBGL_PACK");
    });
    ENV.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE", function() {
      return ENV.getBool("WEBGL_PACK");
    });
    ENV.registerFlag("WEBGL_MAX_TEXTURE_SIZE", function() {
      return getWebGLMaxTextureSize(ENV.getNumber("WEBGL_VERSION"));
    });
    ENV.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER", function() {
      return getMaxTexturesInShader(ENV.getNumber("WEBGL_VERSION"));
    });
    ENV.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION", function() {
      var webGLVersion = ENV.getNumber("WEBGL_VERSION");
      if (webGLVersion === 0) {
        return 0;
      }
      return getWebGLDisjointQueryTimerVersion(webGLVersion);
    });
    ENV.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE", function() {
      return ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") > 0 && !tf.device_util.isMobile();
    });
    ENV.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE", function() {
      return isCapableOfRenderingToFloatTexture(ENV.getNumber("WEBGL_VERSION"));
    });
    ENV.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED", function() {
      return ENV.getBool("WEBGL_FORCE_F16_TEXTURES") ? false : ENV.getBool("WEBGL_RENDER_FLOAT32_CAPABLE");
    });
    ENV.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED", function() {
      return isDownloadFloatTextureEnabled(ENV.getNumber("WEBGL_VERSION"));
    });
    ENV.registerFlag("WEBGL_FENCE_API_ENABLED", function() {
      return isWebGLFenceEnabled(ENV.getNumber("WEBGL_VERSION"));
    });
    ENV.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM", function() {
      var useUniforms = ENV.getBool("WEBGL_RENDER_FLOAT32_ENABLED");
      return useUniforms ? 4 : 0;
    });
    ENV.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD", function() {
      return -1;
    }, function(threshold) {
      if (!(typeof threshold === "number")) {
        throw new Error("WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but " + "got ".concat(threshold, "."));
      }
      if (threshold < 0 && threshold !== -1) {
        throw new Error("WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never " + "delete) or at least 0, but got ".concat(threshold, "."));
      }
    });
    ENV.registerFlag("WEBGL_FLUSH_THRESHOLD", function() {
      return tf.device_util.isMobile() ? 1 : -1;
    }, function(threshold) {
      if (!(typeof threshold === "number")) {
        throw new Error("WEBGL_FLUSH_THRESHOLD must be a number but got " + "".concat(threshold, "."));
      }
      if (threshold < 0 && threshold !== -1) {
        throw new Error("WEBGL_FLUSH_THRESHOLD must be -1 (indicating never " + "manual flush) or at least 0, but got ".concat(threshold, "."));
      }
    });
    ENV.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD", function() {
      return 128;
    });
    ENV.registerFlag("WEBGL_USE_SHAPES_UNIFORMS", function() {
      return false;
    });
    ENV.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD", function() {
      return 1e5;
    });
    ENV.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD", function() {
      return 128;
    });
    ENV.registerFlag("WEBGL_EXP_CONV", function() {
      return false;
    });
    ENV.registerFlag("SOFTWARE_WEBGL_ENABLED", function() {
      return ENV.getBool("IS_TEST");
    });
    ENV.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE", function() {
      return Infinity;
    });
    ENV.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE", function() {
      return false;
    });
    ENV.registerFlag("WEBGL2_ISNAN_CUSTOM", function() {
      return false;
    });
    ENV.registerFlag("ENGINE_COMPILE_ONLY", function() {
      return false;
    });
    function getGlslDifferences() {
      var version2;
      var attribute;
      var varyingVs;
      var varyingFs;
      var texture2D;
      var output;
      var defineOutput;
      var defineSpecialNaN;
      var defineSpecialInf;
      var defineRound;
      if (tf.env().getNumber("WEBGL_VERSION") === 2) {
        version2 = "#version 300 es";
        attribute = "in";
        varyingVs = "out";
        varyingFs = "in";
        texture2D = "texture";
        output = "outputColor";
        defineOutput = "out vec4 outputColor;";
        defineSpecialNaN = tf.env().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    " : "";
        defineSpecialInf = "";
        defineRound = "\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    ";
      } else {
        version2 = "";
        attribute = "attribute";
        varyingVs = "varying";
        varyingFs = "varying";
        texture2D = "texture2D";
        output = "gl_FragColor";
        defineOutput = "";
        defineSpecialNaN = "\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    ";
        defineSpecialInf = "\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    ";
        defineRound = "\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    ";
      }
      return {
        version: version2,
        attribute,
        varyingVs,
        varyingFs,
        texture2D,
        output,
        defineOutput,
        defineSpecialNaN,
        defineSpecialInf,
        defineRound
      };
    }
    function getLogicalCoordinatesFromFlatIndex(coords2, shape, index) {
      if (index === void 0) {
        index = "index";
      }
      var strides = tf.util.computeStrides(shape);
      return strides.map(function(stride, i) {
        var line1 = "int ".concat(coords2[i], " = ").concat(index, " / ").concat(stride);
        var line2 = i === strides.length - 1 ? "int ".concat(coords2[i + 1], " = ").concat(index, " - ").concat(coords2[i], " * ").concat(stride) : "index -= ".concat(coords2[i], " * ").concat(stride);
        return "".concat(line1, "; ").concat(line2, ";");
      }).join("");
    }
    function getOutputLogicalCoordinatesFromFlatIndexByUniform(coords2, shape, index) {
      if (index === void 0) {
        index = "index";
      }
      var strides = tf.util.computeStrides(shape);
      return strides.map(function(_, i) {
        var line1 = "int ".concat(coords2[i], " = ").concat(index, " / outShapeStrides[").concat(i, "]");
        var line2 = i === strides.length - 1 ? "int ".concat(coords2[i + 1], " = ").concat(index, " - ").concat(coords2[i], " * outShapeStrides[").concat(i, "]") : "index -= ".concat(coords2[i], " * outShapeStrides[").concat(i, "]");
        return "".concat(line1, "; ").concat(line2, ";");
      }).join("");
    }
    function symbolicallyComputeStrides(indicesArr, variableName) {
      var numCoords = indicesArr.length;
      var shape = indicesArr.map(function(d) {
        return "".concat(variableName, "[").concat(d, "]");
      });
      var strides = new Array(numCoords - 1);
      strides[numCoords - 2] = shape[numCoords - 1];
      for (var i = numCoords - 3; i >= 0; --i) {
        strides[i] = "(".concat(strides[i + 1], " * ").concat(shape[i + 1], ")");
      }
      return strides;
    }
    function getLogicalCoordinatesFromFlatIndexByUniform(coords2, variableName, index) {
      if (index === void 0) {
        index = "index";
      }
      var indicesArray = coords2.map(function(_, i) {
        return i;
      });
      var strides = symbolicallyComputeStrides(indicesArray, variableName);
      return strides.map(function(_, i) {
        var line1 = "int ".concat(coords2[i], " = ").concat(index, " / ").concat(strides[i]);
        var line2 = i === strides.length - 1 ? "int ".concat(coords2[i + 1], " = ").concat(index, " - ").concat(coords2[i], " * ").concat(strides[i]) : "index -= ".concat(coords2[i], " * ").concat(strides[i]);
        return "".concat(line1, "; ").concat(line2, ";");
      }).join("");
    }
    function getFlatIndexFrom3D(shape) {
      var strides = tf.util.computeStrides(shape).map(function(d) {
        return d.toString();
      });
      return "\n  int getFlatIndex(ivec3 coords) {\n    return coords.x * ".concat(strides[0], " + coords.y * ").concat(strides[1], " + coords.z;\n  }\n");
    }
    function getFlatIndexFrom3DOutput() {
      return "\n  int getFlatIndex(ivec3 coords) {\n    return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n  }\n";
    }
    var ENCODE_FLOAT_SNIPPET = "\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";
    var getBroadcastDims = tf.backend_util.getBroadcastDims;
    function makeShader(inputsInfo, outputShape, program) {
      var prefixSnippets = [];
      inputsInfo.forEach(function(x) {
        var size = tf.util.sizeFromShape(x.shapeInfo.logicalShape);
        if (x.shapeInfo.isUniform) {
          prefixSnippets.push("uniform float ".concat(x.name).concat(size > 1 ? "[".concat(size, "]") : "", ";"));
        } else {
          prefixSnippets.push("uniform sampler2D ".concat(x.name, ";"));
          prefixSnippets.push("uniform int offset".concat(x.name, ";"));
        }
        if (program.enableShapeUniforms) {
          var uniformShape = getUniformInfoFromShape(program.packedInputs, x.shapeInfo.logicalShape, x.shapeInfo.texShape).uniformShape;
          switch (uniformShape.length) {
            case 1:
              prefixSnippets.push("uniform int ".concat(x.name, "Shape;"));
              break;
            case 2:
              prefixSnippets.push("uniform ivec2 ".concat(x.name, "Shape;"));
              break;
            case 3:
              prefixSnippets.push("uniform ivec3 ".concat(x.name, "Shape;"));
              break;
            case 4:
              prefixSnippets.push("uniform ivec4 ".concat(x.name, "Shape;"));
              break;
          }
          prefixSnippets.push("uniform ivec2 ".concat(x.name, "TexShape;"));
        }
      });
      if (program.enableShapeUniforms) {
        switch (outputShape.logicalShape.length) {
          case 1:
            prefixSnippets.push("uniform int outShape;");
            break;
          case 2:
            prefixSnippets.push("uniform ivec2 outShape;");
            prefixSnippets.push("uniform int outShapeStrides;");
            break;
          case 3:
            prefixSnippets.push("uniform ivec3 outShape;");
            prefixSnippets.push("uniform ivec2 outShapeStrides;");
            break;
          case 4:
            prefixSnippets.push("uniform ivec4 outShape;");
            prefixSnippets.push("uniform ivec3 outShapeStrides;");
            break;
        }
        prefixSnippets.push("uniform ivec2 outTexShape;");
      }
      if (program.customUniforms) {
        program.customUniforms.forEach(function(d) {
          prefixSnippets.push("uniform ".concat(d.type, " ").concat(d.name).concat(d.arrayIndex ? "[".concat(d.arrayIndex, "]") : "", ";"));
        });
      }
      var inputPrefixSnippet = prefixSnippets.join("\n");
      var inputSamplingSnippet = inputsInfo.map(function(x) {
        return getInputSamplingSnippet(x, outputShape, program.packedInputs, program.enableShapeUniforms);
      }).join("\n");
      var outTexShape = outputShape.texShape;
      var glsl = getGlslDifferences();
      var floatTextureSampleSnippet = getFloatTextureSampleSnippet(glsl);
      var outputSamplingSnippet;
      var floatTextureSetOutputSnippet;
      var shaderPrefix = getShaderPrefix(glsl);
      if (outputShape.isPacked) {
        outputSamplingSnippet = getPackedOutputSamplingSnippet(outputShape.logicalShape, outTexShape, program.enableShapeUniforms);
        floatTextureSetOutputSnippet = getFloatTextureSetRGBASnippet(glsl);
      } else {
        outputSamplingSnippet = getOutputSamplingSnippet(outputShape.logicalShape, outTexShape, program.enableShapeUniforms);
        floatTextureSetOutputSnippet = getFloatTextureSetRSnippet(glsl);
      }
      if (program.packedInputs) {
        shaderPrefix += SHADER_PACKED_PREFIX;
      }
      var source = [
        shaderPrefix,
        floatTextureSampleSnippet,
        floatTextureSetOutputSnippet,
        inputPrefixSnippet,
        outputSamplingSnippet,
        inputSamplingSnippet,
        program.userCode
      ].join("\n");
      return source;
    }
    function getSamplerFromInInfo(inInfo, enableShapeUniforms) {
      if (enableShapeUniforms === void 0) {
        enableShapeUniforms = false;
      }
      var shape = inInfo.shapeInfo.logicalShape;
      switch (shape.length) {
        case 0:
          return getSamplerScalar(inInfo, enableShapeUniforms);
        case 1:
          return getSampler1D(inInfo, enableShapeUniforms);
        case 2:
          return getSampler2D(inInfo, enableShapeUniforms);
        case 3:
          return getSampler3D(inInfo, enableShapeUniforms);
        case 4:
          return getSampler4D(inInfo, enableShapeUniforms);
        case 5:
          return getSampler5D(inInfo);
        case 6:
          return getSampler6D(inInfo);
        default:
          throw new Error("".concat(shape.length, "-D input sampling") + " is not yet supported");
      }
    }
    function getPackedSamplerFromInInfo(inInfo, enableShapeUniforms) {
      var shape = inInfo.shapeInfo.logicalShape;
      switch (shape.length) {
        case 0:
          return getPackedSamplerScalar(inInfo);
        case 1:
          return getPackedSampler1D(inInfo, enableShapeUniforms);
        case 2:
          return getPackedSampler2D(inInfo, enableShapeUniforms);
        case 3:
          return getPackedSampler3D(inInfo, enableShapeUniforms);
        default:
          return getPackedSamplerND(inInfo, enableShapeUniforms);
      }
    }
    function getInputSamplingSnippet(inInfo, outShapeInfo, usesPackedTextures, enableShapeUniforms) {
      if (usesPackedTextures === void 0) {
        usesPackedTextures = false;
      }
      var res = "";
      if (usesPackedTextures) {
        res += getPackedSamplerFromInInfo(inInfo, enableShapeUniforms);
      } else {
        res += getSamplerFromInInfo(inInfo, enableShapeUniforms);
      }
      var inShape = inInfo.shapeInfo.logicalShape;
      var outShape = outShapeInfo.logicalShape;
      if (inShape.length <= outShape.length) {
        if (usesPackedTextures) {
          res += getPackedSamplerAtOutputCoords(inInfo, outShapeInfo);
        } else {
          res += getSamplerAtOutputCoords(inInfo, outShapeInfo);
        }
      }
      return res;
    }
    function getPackedOutputSamplingSnippet(outShape, outTexShape, enableShapeUniforms) {
      switch (outShape.length) {
        case 0:
          return getOutputScalarCoords();
        case 1:
          return getOutputPacked1DCoords(outShape, outTexShape, enableShapeUniforms);
        case 2:
          return getOutputPacked2DCoords(outShape, outTexShape, enableShapeUniforms);
        case 3:
          return getOutputPacked3DCoords(outShape, outTexShape, enableShapeUniforms);
        default:
          return getOutputPackedNDCoords(outShape, outTexShape, enableShapeUniforms);
      }
    }
    function getOutputSamplingSnippet(outShape, outTexShape, enableShapeUniforms) {
      switch (outShape.length) {
        case 0:
          return getOutputScalarCoords();
        case 1:
          return getOutput1DCoords(outShape, outTexShape, enableShapeUniforms);
        case 2:
          return getOutput2DCoords(outShape, outTexShape, enableShapeUniforms);
        case 3:
          return getOutput3DCoords(outShape, outTexShape, enableShapeUniforms);
        case 4:
          return getOutput4DCoords(outShape, outTexShape, enableShapeUniforms);
        case 5:
          return getOutput5DCoords(outShape, outTexShape);
        case 6:
          return getOutput6DCoords(outShape, outTexShape);
        default:
          throw new Error("".concat(outShape.length, "-D output sampling is not yet supported"));
      }
    }
    function getFloatTextureSampleSnippet(glsl) {
      return "\n    float sampleTexture(sampler2D textureSampler, vec2 uv) {\n      return ".concat(glsl.texture2D, "(textureSampler, uv).r;\n    }\n  ");
    }
    function getFloatTextureSetRSnippet(glsl) {
      return "\n    void setOutput(float val) {\n      ".concat(glsl.output, " = vec4(val, 0, 0, 0);\n    }\n  ");
    }
    function getFloatTextureSetRGBASnippet(glsl) {
      return "\n    void setOutput(vec4 val) {\n      ".concat(glsl.output, " = val;\n    }\n  ");
    }
    function getShaderPrefix(glsl) {
      var SHADER_PREFIX = "".concat(glsl.version, "\n    precision highp float;\n    precision highp int;\n    precision highp sampler2D;\n    ").concat(glsl.varyingFs, " vec2 resultUV;\n    ").concat(glsl.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    ").concat(glsl.defineSpecialNaN, "\n    ").concat(glsl.defineSpecialInf, "\n    ").concat(glsl.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    ").concat(SAMPLE_1D_SNIPPET, "\n    ").concat(SAMPLE_2D_SNIPPET, "\n    ").concat(SAMPLE_3D_SNIPPET, "\n  ");
      return SHADER_PREFIX;
    }
    var SAMPLE_1D_SNIPPET = "\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";
    var SAMPLE_2D_SNIPPET = "\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";
    var SAMPLE_3D_SNIPPET = "\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";
    var SHADER_PACKED_PREFIX = "\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 getOutputScalarCoords() {
      return "\n    int getOutputCoords() {\n      return 0;\n    }\n  ";
    }
    function getOutputPacked1DCoords(shape, texShape, enableShapeUniforms) {
      var packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
      if (packedTexShape[0] === 1) {
        if (enableShapeUniforms) {
          return "\n      int getOutputCoords() {\n        return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));\n      }\n    ";
        }
        return "\n      int getOutputCoords() {\n        return 2 * int(resultUV.x * ".concat(packedTexShape[1], ".0);\n      }\n    ");
      }
      if (packedTexShape[1] === 1) {
        if (enableShapeUniforms) {
          return "\n      int getOutputCoords() {\n        return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));\n      }\n    ";
        }
        return "\n      int getOutputCoords() {\n        return 2 * int(resultUV.y * ".concat(packedTexShape[0], ".0);\n      }\n    ");
      }
      if (enableShapeUniforms) {
        return "\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  ";
      }
      return "\n    int getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(".concat(packedTexShape[0], ", ").concat(packedTexShape[1], "));\n      return 2 * (resTexRC.x * ").concat(packedTexShape[1], " + resTexRC.y);\n    }\n  ");
    }
    function getOutput1DCoords(shape, texShape, enableShapeUniforms) {
      if (texShape[0] === 1) {
        if (enableShapeUniforms) {
          return "\n      int getOutputCoords() {\n        return int(resultUV.x * float(outTexShape[1]));\n      }\n    ";
        }
        return "\n      int getOutputCoords() {\n        return int(resultUV.x * ".concat(texShape[1], ".0);\n      }\n    ");
      }
      if (texShape[1] === 1) {
        if (enableShapeUniforms) {
          return "\n      int getOutputCoords() {\n        return int(resultUV.y * float(outTexShape[0]));\n      }\n    ";
        }
        return "\n      int getOutputCoords() {\n        return int(resultUV.y * ".concat(texShape[0], ".0);\n      }\n    ");
      }
      if (enableShapeUniforms) {
        return "\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  ";
      }
      return "\n    int getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(".concat(texShape[0], ", ").concat(texShape[1], "));\n      return resTexRC.x * ").concat(texShape[1], " + resTexRC.y;\n    }\n  ");
    }
    function getOutputPacked3DCoords(shape, texShape, enableShapeUniforms) {
      if (enableShapeUniforms) {
        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  ";
      }
      var packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
      var texelsInLogicalRow = Math.ceil(shape[2] / 2);
      var texelsInBatch = texelsInLogicalRow * Math.ceil(shape[1] / 2);
      return "\n    ivec3 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(".concat(packedTexShape[0], ", ").concat(packedTexShape[1], "));\n      int index = resTexRC.x * ").concat(packedTexShape[1], " + resTexRC.y;\n\n      int b = index / ").concat(texelsInBatch, ";\n      index -= b * ").concat(texelsInBatch, ";\n\n      int r = 2 * (index / ").concat(texelsInLogicalRow, ");\n      int c = imod(index, ").concat(texelsInLogicalRow, ") * 2;\n\n      return ivec3(b, r, c);\n    }\n  ");
    }
    function getOutput3DCoords(shape, texShape, enableShapeUniforms) {
      if (enableShapeUniforms) {
        var coordsFromIndexSnippet_1 = getOutputLogicalCoordinatesFromFlatIndexByUniform(["r", "c", "d"], shape);
        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    ".concat(coordsFromIndexSnippet_1, "\n    return ivec3(r, c, d);\n  }\n");
      }
      var coordsFromIndexSnippet = getLogicalCoordinatesFromFlatIndex(["r", "c", "d"], shape);
      return "\n    ivec3 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(".concat(texShape[0], ", ").concat(texShape[1], "));\n      int index = resTexRC.x * ").concat(texShape[1], " + resTexRC.y;\n      ").concat(coordsFromIndexSnippet, "\n      return ivec3(r, c, d);\n    }\n  ");
    }
    function getOutputPackedNDCoords(shape, texShape, enableShapeUniforms) {
      if (enableShapeUniforms) {
        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  ";
      }
      var packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
      var texelsInLogicalRow = Math.ceil(shape[shape.length - 1] / 2);
      var texelsInBatch = texelsInLogicalRow * Math.ceil(shape[shape.length - 2] / 2);
      var texelsInBatchN = texelsInBatch;
      var batches = "";
      var coords2 = "b, r, c";
      for (var b = 2; b < shape.length - 1; b++) {
        texelsInBatchN *= shape[shape.length - b - 1];
        batches = "\n      int b".concat(b, " = index / ").concat(texelsInBatchN, ";\n      index -= b").concat(b, " * ").concat(texelsInBatchN, ";\n    ") + batches;
        coords2 = "b".concat(b, ", ") + coords2;
      }
      return "\n    ivec".concat(shape.length, " getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(").concat(packedTexShape[0], ", ").concat(packedTexShape[1], "));\n      int index = resTexRC.x * ").concat(packedTexShape[1], " + resTexRC.y;\n\n      ").concat(batches, "\n\n      int b = index / ").concat(texelsInBatch, ";\n      index -= b * ").concat(texelsInBatch, ";\n\n      int r = 2 * (index / ").concat(texelsInLogicalRow, ");\n      int c = imod(index, ").concat(texelsInLogicalRow, ") * 2;\n\n      return ivec").concat(shape.length, "(").concat(coords2, ");\n    }\n  ");
    }
    function getOutput4DCoords(shape, texShape, enableShapeUniforms) {
      if (enableShapeUniforms) {
        var coordsFromIndexSnippet_2 = getOutputLogicalCoordinatesFromFlatIndexByUniform(["r", "c", "d", "d2"], shape);
        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      ".concat(coordsFromIndexSnippet_2, "\n      return ivec4(r, c, d, d2);\n    }\n  ");
      }
      var coordsFromIndexSnippet = getLogicalCoordinatesFromFlatIndex(["r", "c", "d", "d2"], shape);
      return "\n    ivec4 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n        vec2(".concat(texShape[0], ", ").concat(texShape[1], "));\n      int index = resTexRC.x * ").concat(texShape[1], " + resTexRC.y;\n      ").concat(coordsFromIndexSnippet, "\n      return ivec4(r, c, d, d2);\n    }\n  ");
    }
    function getOutput5DCoords(shape, texShape) {
      var coordsFromIndexSnippet = getLogicalCoordinatesFromFlatIndex(["r", "c", "d", "d2", "d3"], shape);
      return "\n    ivec5 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx * vec2(".concat(texShape[0], ",\n                             ").concat(texShape[1], "));\n\n      int index = resTexRC.x * ").concat(texShape[1], " + resTexRC.y;\n\n      ").concat(coordsFromIndexSnippet, "\n\n      ivec5 outShape = ivec5(r, c, d, d2, d3);\n      return outShape;\n    }\n  ");
    }
    function getOutput6DCoords(shape, texShape) {
      var coordsFromIndexSnippet = getLogicalCoordinatesFromFlatIndex(["r", "c", "d", "d2", "d3", "d4"], shape);
      return "\n    ivec6 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n        vec2(".concat(texShape[0], ", ").concat(texShape[1], "));\n      int index = resTexRC.x * ").concat(texShape[1], " + resTexRC.y;\n\n      ").concat(coordsFromIndexSnippet, "\n\n      ivec6 result = ivec6(r, c, d, d2, d3, d4);\n      return result;\n    }\n  ");
    }
    function getOutputPacked2DCoords(shape, texShape, enableShapeUniforms) {
      var packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
      if (tf.util.arraysEqual(shape, texShape)) {
        if (enableShapeUniforms) {
          return "\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    ";
        }
        return "\n      ivec2 getOutputCoords() {\n        return 2 * ivec2(resultUV.yx * vec2(".concat(packedTexShape[0], ", ").concat(packedTexShape[1], "));\n      }\n    ");
      }
      var texelsInLogicalRow = Math.ceil(shape[1] / 2);
      if (enableShapeUniforms) {
        return "\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  ";
      }
      return "\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(".concat(packedTexShape[0], ", ").concat(packedTexShape[1], "));\n\n      int index = resTexRC.x * ").concat(packedTexShape[1], " + resTexRC.y;\n      int r = 2 * (index / ").concat(texelsInLogicalRow, ");\n      int c = imod(index, ").concat(texelsInLogicalRow, ") * 2;\n\n      return ivec2(r, c);\n    }\n  ");
    }
    function getOutput2DCoords(shape, texShape, enableShapeUniforms) {
      if (tf.util.arraysEqual(shape, texShape)) {
        if (enableShapeUniforms) {
          return "\n      ivec2 getOutputCoords() {\n        return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));\n      }\n    ";
        }
        return "\n      ivec2 getOutputCoords() {\n        return ivec2(resultUV.yx * vec2(".concat(texShape[0], ", ").concat(texShape[1], "));\n      }\n    ");
      }
      if (shape[1] === 1) {
        if (enableShapeUniforms) {
          return "\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    ";
        }
        return "\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2(".concat(texShape[0], ", ").concat(texShape[1], "));\n        int index = resTexRC.x * ").concat(texShape[1], " + resTexRC.y;\n        return ivec2(index, 0);\n      }\n    ");
      }
      if (shape[0] === 1) {
        if (enableShapeUniforms) {
          return "\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    ";
        }
        return "\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2(".concat(texShape[0], ", ").concat(texShape[1], "));\n        int index = resTexRC.x * ").concat(texShape[1], " + resTexRC.y;\n        return ivec2(0, index);\n      }\n    ");
      }
      if (enableShapeUniforms) {
        return "\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  ";
      }
      return "\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(".concat(texShape[0], ", ").concat(texShape[1], "));\n      int index = resTexRC.x * ").concat(texShape[1], " + resTexRC.y;\n      int r = index / ").concat(shape[1], ";\n      int c = index - r * ").concat(shape[1], ";\n      return ivec2(r, c);\n    }\n  ");
    }
    function getFlatOffsetUniformName(texName) {
      return "offset".concat(texName);
    }
    function getPackedSamplerScalar(inputInfo) {
      var texName = inputInfo.name;
      var funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
      var glsl = getGlslDifferences();
      return "\n    vec4 ".concat(funcName, "() {\n      return ").concat(glsl.texture2D, "(").concat(texName, ", halfCR);\n    }\n  ");
    }
    function getSamplerScalar(inputInfo, enableShapeUniforms) {
      var texName = inputInfo.name;
      var funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
      if (inputInfo.shapeInfo.isUniform) {
        return "float ".concat(funcName, "() {return ").concat(texName, ";}");
      }
      var _a2 = __read(inputInfo.shapeInfo.texShape, 2), texNumR = _a2[0], texNumC = _a2[1];
      if (texNumR === 1 && texNumC === 1) {
        return "\n      float ".concat(funcName, "() {\n        return sampleTexture(").concat(texName, ", halfCR);\n      }\n    ");
      }
      var offset = getFlatOffsetUniformName(texName);
      if (enableShapeUniforms) {
        return "\n    float ".concat(funcName, "() {\n      vec2 uv = uvFromFlat(").concat(texName, "TexShape[0], ").concat(texName, "TexShape[1], ").concat(offset, ");\n      return sampleTexture(").concat(texName, ", uv);\n    }\n  ");
      }
      var _b = __read(inputInfo.shapeInfo.texShape, 2), tNumR = _b[0], tNumC = _b[1];
      return "\n    float ".concat(funcName, "() {\n      vec2 uv = uvFromFlat(").concat(tNumR, ", ").concat(tNumC, ", ").concat(offset, ");\n      return sampleTexture(").concat(texName, ", uv);\n    }\n  ");
    }
    function getPackedSampler1D(inputInfo, enableShapeUniforms) {
      var texName = inputInfo.name;
      var funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
      var texShape = inputInfo.shapeInfo.texShape;
      var glsl = getGlslDifferences();
      if (enableShapeUniforms) {
        return "\n    vec4 ".concat(funcName, "(int index) {\n      ivec2 packedTexShape = ivec2(ceil(float(").concat(texName, "TexShape[0]) / 2.0), ceil(float(").concat(texName, "TexShape[1]) / 2.0));\n      vec2 uv = packedUVfrom1D(\n        packedTexShape[0], packedTexShape[1], index);\n      return ").concat(glsl.texture2D, "(").concat(texName, ", uv);\n    }\n  ");
      }
      var packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
      return "\n    vec4 ".concat(funcName, "(int index) {\n      vec2 uv = packedUVfrom1D(\n        ").concat(packedTexShape[0], ", ").concat(packedTexShape[1], ", index);\n      return ").concat(glsl.texture2D, "(").concat(texName, ", uv);\n    }\n  ");
    }
    function getSampler1D(inputInfo, enableShapeUniforms) {
      var texName = inputInfo.name;
      var funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
      if (inputInfo.shapeInfo.isUniform) {
        return "\n      float ".concat(funcName, "(int index) {\n        ").concat(getUniformSampler(inputInfo), "\n      }\n    ");
      }
      var texShape = inputInfo.shapeInfo.texShape;
      var tNumR = texShape[0];
      var tNumC = texShape[1];
      if (tNumC === 1 && tNumR === 1) {
        return "\n      float ".concat(funcName, "(int index) {\n        return sampleTexture(").concat(texName, ", halfCR);\n      }\n    ");
      }
      var offset = getFlatOffsetUniformName(texName);
      if (tNumC === 1) {
        if (enableShapeUniforms) {
          return "\n      float ".concat(funcName, "(int index) {\n        vec2 uv = vec2(0.5, (float(index + ").concat(offset, ") + 0.5) / float(").concat(texName, "TexShape[0]));\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
        }
        return "\n      float ".concat(funcName, "(int index) {\n        vec2 uv = vec2(0.5, (float(index + ").concat(offset, ") + 0.5) / ").concat(tNumR, ".0);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
      }
      if (tNumR === 1) {
        if (enableShapeUniforms) {
          return "\n      float ".concat(funcName, "(int index) {\n        vec2 uv = vec2((float(index + ").concat(offset, ") + 0.5) / float(").concat(texName, "TexShape[1]), 0.5);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
        }
        return "\n      float ".concat(funcName, "(int index) {\n        vec2 uv = vec2((float(index + ").concat(offset, ") + 0.5) / ").concat(tNumC, ".0, 0.5);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
      }
      if (enableShapeUniforms) {
        return "\n    float ".concat(funcName, "(int index) {\n      vec2 uv = uvFromFlat(").concat(texName, "TexShape[0], ").concat(texName, "TexShape[1], index + ").concat(offset, ");\n      return sampleTexture(").concat(texName, ", uv);\n    }\n  ");
      }
      return "\n    float ".concat(funcName, "(int index) {\n      vec2 uv = uvFromFlat(").concat(tNumR, ", ").concat(tNumC, ", index + ").concat(offset, ");\n      return sampleTexture(").concat(texName, ", uv);\n    }\n  ");
    }
    function getPackedSampler2D(inputInfo, enableShapeUniforms) {
      var shape = inputInfo.shapeInfo.logicalShape;
      var texName = inputInfo.name;
      var funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
      var texShape = inputInfo.shapeInfo.texShape;
      var texNumR = texShape[0];
      var texNumC = texShape[1];
      var glsl = getGlslDifferences();
      if (texShape != null && tf.util.arraysEqual(shape, texShape)) {
        if (enableShapeUniforms) {
          return "\n      vec4 ".concat(funcName, "(int row, int col) {\n        vec2 uv = (vec2(col, row) + halfCR) / vec2(").concat(texName, "TexShape[1], ").concat(texName, "TexShape[0]);\n\n        return ").concat(glsl.texture2D, "(").concat(texName, ", uv);\n      }\n    ");
        }
        return "\n      vec4 ".concat(funcName, "(int row, int col) {\n        vec2 uv = (vec2(col, row) + halfCR) / vec2(").concat(texNumC, ".0, ").concat(texNumR, ".0);\n\n        return ").concat(glsl.texture2D, "(").concat(texName, ", uv);\n      }\n    ");
      }
      if (enableShapeUniforms) {
        return "\n    vec4 ".concat(funcName, "(int row, int col) {\n      ivec2 packedTexShape = ivec2(ceil(float(").concat(texName, "TexShape[0]) / 2.0), ceil(float(").concat(texName, "TexShape[1]) / 2.0));\n      int valuesPerRow = int(ceil(float(").concat(texName, "Shape[1]) / 2.0));\n      vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);\n      return ").concat(glsl.texture2D, "(").concat(texName, ", uv);\n    }\n  ");
      }
      var packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
      var valuesPerRow = Math.ceil(shape[1] / 2);
      return "\n    vec4 ".concat(funcName, "(int row, int col) {\n      vec2 uv = packedUVfrom2D(").concat(valuesPerRow, ", ").concat(packedTexShape[0], ", ").concat(packedTexShape[1], ", row, col);\n      return ").concat(glsl.texture2D, "(").concat(texName, ", uv);\n    }\n  ");
    }
    function getSampler2D(inputInfo, enableShapeUniforms) {
      var shape = inputInfo.shapeInfo.logicalShape;
      var texName = inputInfo.name;
      var funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
      var texShape = inputInfo.shapeInfo.texShape;
      if (texShape != null && tf.util.arraysEqual(shape, texShape)) {
        if (enableShapeUniforms) {
          return "\n      float ".concat(funcName, "(int row, int col) {\n        vec2 uv = (vec2(col, row) + halfCR) / vec2(").concat(texName, "TexShape[1], ").concat(texName, "TexShape[0]);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
        }
        var texNumR_1 = texShape[0];
        var texNumC_1 = texShape[1];
        return "\n    float ".concat(funcName, "(int row, int col) {\n      vec2 uv = (vec2(col, row) + halfCR) / vec2(").concat(texNumC_1, ".0, ").concat(texNumR_1, ".0);\n      return sampleTexture(").concat(texName, ", uv);\n    }\n  ");
      }
      var _a2 = tf.util.squeezeShape(shape), newShape = _a2.newShape, keptDims = _a2.keptDims;
      var squeezedShape = newShape;
      if (squeezedShape.length < shape.length) {
        var newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);
        var params = ["row", "col"];
        return "\n      ".concat(getSamplerFromInInfo(newInputInfo, enableShapeUniforms), "\n      float ").concat(funcName, "(int row, int col) {\n        return ").concat(funcName, "(").concat(getSqueezedParams(params, keptDims), ");\n      }\n    ");
      }
      if (inputInfo.shapeInfo.isUniform) {
        return "\n      float ".concat(funcName, "(int row, int col) {\n        int index = round(dot(vec2(row, col), vec2(").concat(shape[1], ", 1)));\n        ").concat(getUniformSampler(inputInfo), "\n      }\n    ");
      }
      var texNumR = texShape[0];
      var texNumC = texShape[1];
      var offset = getFlatOffsetUniformName(texName);
      if (texNumC === 1) {
        if (enableShapeUniforms) {
          return "\n      float ".concat(funcName, "(int row, int col) {\n        float index = dot(vec3(row, col, ").concat(offset, "), vec3(").concat(texName, "Shape[1], 1, 1));\n        vec2 uv = vec2(0.5, (index + 0.5) / float(").concat(texName, "TexShape[0]));\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
        }
        return "\n    float ".concat(funcName, "(int row, int col) {\n      float index = dot(vec3(row, col, ").concat(offset, "), vec3(").concat(shape[1], ", 1, 1));\n      vec2 uv = vec2(0.5, (index + 0.5) / ").concat(texNumR, ".0);\n      return sampleTexture(").concat(texName, ", uv);\n    }\n  ");
      }
      if (texNumR === 1) {
        if (enableShapeUniforms) {
          return "\n      float ".concat(funcName, "(int row, int col) {\n        float index = dot(vec3(row, col, ").concat(offset, "), vec3(").concat(texName, "Shape[1], 1, 1));\n        vec2 uv = vec2((index + 0.5) / float(").concat(texName, "TexShape[1]), 0.5);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
        }
        return "\n    float ".concat(funcName, "(int row, int col) {\n      float index = dot(vec3(row, col, ").concat(offset, "), vec3(").concat(shape[1], ", 1, 1));\n      vec2 uv = vec2((index + 0.5) / ").concat(texNumC, ".0, 0.5);\n      return sampleTexture(").concat(texName, ", uv);\n    }\n  ");
      }
      if (enableShapeUniforms) {
        return "\n      float ".concat(funcName, "(int row, int col) {\n        // Explicitly use integer operations as dot() only works on floats.\n        int index = row * ").concat(texName, "Shape[1] + col + ").concat(offset, ";\n        vec2 uv = uvFromFlat(").concat(texName, "TexShape[0], ").concat(texName, "TexShape[1], index);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
      }
      return "\n  float ".concat(funcName, "(int row, int col) {\n    // Explicitly use integer operations as dot() only works on floats.\n    int index = row * ").concat(shape[1], " + col + ").concat(offset, ";\n    vec2 uv = uvFromFlat(").concat(texNumR, ", ").concat(texNumC, ", index);\n    return sampleTexture(").concat(texName, ", uv);\n  }\n");
    }
    function getPackedSampler3D(inputInfo, enableShapeUniforms) {
      var shape = inputInfo.shapeInfo.logicalShape;
      var texName = inputInfo.name;
      var funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
      var texShape = inputInfo.shapeInfo.texShape;
      var packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
      if (shape[0] === 1) {
        var squeezedShape = shape.slice(1);
        var keptDims = [1, 2];
        var newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);
        var params = ["b", "row", "col"];
        return "\n        ".concat(getPackedSamplerFromInInfo(newInputInfo, enableShapeUniforms), "\n        vec4 ").concat(funcName, "(int b, int row, int col) {\n          return ").concat(funcName, "(").concat(getSqueezedParams(params, keptDims), ");\n        }\n      ");
      }
      var glsl = getGlslDifferences();
      if (enableShapeUniforms) {
        return "\n    vec4 ".concat(funcName, "(int b, int row, int col) {\n      ivec2 packedTexShape = ivec2(ceil(float(").concat(texName, "TexShape[0]) / 2.0), ceil(float(").concat(texName, "TexShape[1]) / 2.0));\n      int valuesPerRow = int(ceil(float(").concat(texName, "Shape[2]) / 2.0));\n      int texelsInBatch = valuesPerRow * int(ceil(float(").concat(texName, "Shape[1]) / 2.0));\n      vec2 uv = packedUVfrom3D(\n        packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);\n      return ").concat(glsl.texture2D, "(").concat(texName, ", uv);\n    }\n  ");
      }
      var texNumR = packedTexShape[0];
      var texNumC = packedTexShape[1];
      var valuesPerRow = Math.ceil(shape[2] / 2);
      var texelsInBatch = valuesPerRow * Math.ceil(shape[1] / 2);
      return "\n    vec4 ".concat(funcName, "(int b, int row, int col) {\n      vec2 uv = packedUVfrom3D(\n        ").concat(texNumR, ", ").concat(texNumC, ", ").concat(texelsInBatch, ", ").concat(valuesPerRow, ", b, row, col);\n      return ").concat(glsl.texture2D, "(").concat(texName, ", uv);\n    }\n  ");
    }
    function getSampler3D(inputInfo, enableShapeUniforms) {
      var shape = inputInfo.shapeInfo.logicalShape;
      var texName = inputInfo.name;
      var funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
      var stride0 = shape[1] * shape[2];
      var stride1 = shape[2];
      var _a2 = tf.util.squeezeShape(shape), newShape = _a2.newShape, keptDims = _a2.keptDims;
      var squeezedShape = newShape;
      if (squeezedShape.length < shape.length) {
        var newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);
        var params = ["row", "col", "depth"];
        return "\n        ".concat(getSamplerFromInInfo(newInputInfo, enableShapeUniforms), "\n        float ").concat(funcName, "(int row, int col, int depth) {\n          return ").concat(funcName, "(").concat(getSqueezedParams(params, keptDims), ");\n        }\n      ");
      }
      if (inputInfo.shapeInfo.isUniform) {
        return "\n      float ".concat(funcName, "(int row, int col, int depth) {\n        int index = round(dot(vec3(row, col, depth),\n                          vec3(").concat(stride0, ", ").concat(stride1, ", 1)));\n        ").concat(getUniformSampler(inputInfo), "\n      }\n    ");
      }
      var texShape = inputInfo.shapeInfo.texShape;
      var texNumR = texShape[0];
      var texNumC = texShape[1];
      var flatOffset = inputInfo.shapeInfo.flatOffset;
      if (texNumC === stride0 && flatOffset == null) {
        if (enableShapeUniforms) {
          return "\n      float ".concat(funcName, "(int row, int col, int depth) {\n        int stride1 = ").concat(texName, "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(").concat(texName, "TexShape[1], ").concat(texName, "TexShape[0]);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
        }
        return "\n        float ".concat(funcName, "(int row, int col, int depth) {\n          float texR = float(row);\n          float texC = dot(vec2(col, depth), vec2(").concat(stride1, ", 1));\n          vec2 uv = (vec2(texC, texR) + halfCR) /\n                     vec2(").concat(texNumC, ".0, ").concat(texNumR, ".0);\n          return sampleTexture(").concat(texName, ", uv);\n        }\n      ");
      }
      if (texNumC === stride1 && flatOffset == null) {
        if (enableShapeUniforms) {
          return "\n      float ".concat(funcName, "(int row, int col, int depth) {\n        float texR = dot(vec2(row, col), vec2(").concat(texName, "Shape[1], 1));\n        float texC = float(depth);\n        vec2 uv = (vec2(texC, texR) + halfCR) / vec2(").concat(texName, "TexShape[1], ").concat(texName, "TexShape[0]);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
        }
        return "\n    float ".concat(funcName, "(int row, int col, int depth) {\n      float texR = dot(vec2(row, col), vec2(").concat(shape[1], ", 1));\n      float texC = float(depth);\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(").concat(texNumC, ".0, ").concat(texNumR, ".0);\n      return sampleTexture(").concat(texName, ", uv);\n    }\n  ");
      }
      var offset = getFlatOffsetUniformName(texName);
      if (enableShapeUniforms) {
        return "\n    float ".concat(funcName, "(int row, int col, int depth) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int stride0 = ").concat(texName, "Shape[1] * ").concat(texName, "Shape[2];\n      int stride1 = ").concat(texName, "Shape[2];\n      int index = row * stride0 + col * stride1 + depth + ").concat(offset, ";\n      vec2 uv = uvFromFlat(").concat(texName, "TexShape[0], ").concat(texName, "TexShape[1], index);\n      return sampleTexture(").concat(texName, ", uv);\n    }\n    ");
      }
      return "\n      float ".concat(funcName, "(int row, int col, int depth) {\n        // Explicitly use integer operations as dot() only works on floats.\n        int index = row * ").concat(stride0, " + col * ").concat(stride1, " + depth + ").concat(offset, ";\n        vec2 uv = uvFromFlat(").concat(texNumR, ", ").concat(texNumC, ", index);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n  ");
    }
    function getPackedSamplerND(inputInfo, enableShapeUniforms) {
      var texName = inputInfo.name;
      var funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
      var glsl = getGlslDifferences();
      if (enableShapeUniforms) {
        return "\n    vec4 ".concat(funcName, "(int b2, int b, int row, int col) {\n      int valuesPerRow = int(ceil(float(").concat(texName, "Shape[3]) / 2.0));\n      int texelsInBatch = valuesPerRow * int(ceil(float(").concat(texName, "Shape[2]) / 2.0));\n      int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);\n      texelsInBatch *= ").concat(texName, "Shape[1];\n      index = b2 * texelsInBatch + index;\n      ivec2 packedTexShape = ivec2(ceil(float(").concat(texName, "TexShape[0]) / 2.0), ceil(float(").concat(texName, "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 ").concat(glsl.texture2D, "(").concat(texName, ", uv);\n    }\n  ");
      }
      var shape = inputInfo.shapeInfo.logicalShape;
      var rank = shape.length;
      var texShape = inputInfo.shapeInfo.texShape;
      var packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
      var texNumR = packedTexShape[0];
      var texNumC = packedTexShape[1];
      var valuesPerRow = Math.ceil(shape[rank - 1] / 2);
      var texelsInBatch = valuesPerRow * Math.ceil(shape[rank - 2] / 2);
      var params = "int b, int row, int col";
      var index = "b * ".concat(texelsInBatch, " + (row / 2) * ").concat(valuesPerRow, " + (col / 2)");
      for (var b = 2; b < rank - 1; b++) {
        params = "int b".concat(b, ", ") + params;
        texelsInBatch *= shape[rank - b - 1];
        index = "b".concat(b, " * ").concat(texelsInBatch, " + ") + index;
      }
      return "\n    vec4 ".concat(funcName, "(").concat(params, ") {\n      int index = ").concat(index, ";\n      int texR = index / ").concat(texNumC, ";\n      int texC = index - texR * ").concat(texNumC, ";\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(").concat(texNumC, ", ").concat(texNumR, ");\n      return ").concat(glsl.texture2D, "(").concat(texName, ", uv);\n    }\n  ");
    }
    function getSampler4D(inputInfo, enableShapeUniforms) {
      var shape = inputInfo.shapeInfo.logicalShape;
      var texName = inputInfo.name;
      var funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
      var stride2 = shape[3];
      var stride1 = shape[2] * stride2;
      var stride0 = shape[1] * stride1;
      var _a2 = tf.util.squeezeShape(shape), newShape = _a2.newShape, keptDims = _a2.keptDims;
      if (newShape.length < shape.length) {
        var newInputInfo = squeezeInputInfo(inputInfo, newShape);
        var params = ["row", "col", "depth", "depth2"];
        return "\n      ".concat(getSamplerFromInInfo(newInputInfo, enableShapeUniforms), "\n      float ").concat(funcName, "(int row, int col, int depth, int depth2) {\n        return ").concat(funcName, "(").concat(getSqueezedParams(params, keptDims), ");\n      }\n    ");
      }
      if (inputInfo.shapeInfo.isUniform) {
        return "\n      float ".concat(funcName, "(int row, int col, int depth, int depth2) {\n        int index = round(dot(vec4(row, col, depth, depth2),\n                          vec4(").concat(stride0, ", ").concat(stride1, ", ").concat(stride2, ", 1)));\n        ").concat(getUniformSampler(inputInfo), "\n      }\n    ");
      }
      var flatOffset = inputInfo.shapeInfo.flatOffset;
      var texShape = inputInfo.shapeInfo.texShape;
      var texNumR = texShape[0];
      var texNumC = texShape[1];
      var stride2Str = "int stride2 = ".concat(texName, "Shape[3];");
      var stride1Str = "int stride1 = ".concat(texName, "Shape[2] * stride2;");
      var stride0Str = "int stride0 = ".concat(texName, "Shape[1] * stride1;");
      if (texNumC === stride0 && flatOffset == null) {
        if (enableShapeUniforms) {
          return "\n      float ".concat(funcName, "(int row, int col, int depth, int depth2) {\n        ").concat(stride2Str, "\n        ").concat(stride1Str, "\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(").concat(texName, "TexShape[1], ").concat(texName, "TexShape[0]);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
        }
        return "\n      float ".concat(funcName, "(int row, int col, int depth, int depth2) {\n        float texR = float(row);\n        float texC =\n            dot(vec3(col, depth, depth2),\n                vec3(").concat(stride1, ", ").concat(stride2, ", 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2(").concat(texNumC, ".0, ").concat(texNumR, ".0);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
      }
      if (texNumC === stride2 && flatOffset == null) {
        if (enableShapeUniforms) {
          return "\n      float ".concat(funcName, "(int row, int col, int depth, int depth2) {\n        float texR = dot(vec3(row, col, depth),\n                         vec3(").concat(texName, "Shape[1] * ").concat(texName, "Shape[2], ").concat(texName, "Shape[2], 1));\n        float texC = float(depth2);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2(").concat(texName, "TexShape[1], ").concat(texName, "TexShape[0]);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
        }
        return "\n      float ".concat(funcName, "(int row, int col, int depth, int depth2) {\n        float texR = dot(vec3(row, col, depth),\n                         vec3(").concat(shape[1] * shape[2], ", ").concat(shape[2], ", 1));\n        float texC = float(depth2);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2(").concat(texNumC, ".0, ").concat(texNumR, ".0);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
      }
      var offset = getFlatOffsetUniformName(texName);
      if (enableShapeUniforms) {
        return "\n    float ".concat(funcName, "(int row, int col, int depth, int depth2) {\n      // Explicitly use integer operations as dot() only works on floats.\n      ").concat(stride2Str, "\n      ").concat(stride1Str, "\n      ").concat(stride0Str, "\n      int index = row * stride0 + col * stride1 +\n          depth * stride2 + depth2;\n      vec2 uv = uvFromFlat(").concat(texName, "TexShape[0], ").concat(texName, "TexShape[1], index + ").concat(offset, ");\n      return sampleTexture(").concat(texName, ", uv);\n    }\n  ");
      }
      return "\n    float ".concat(funcName, "(int row, int col, int depth, int depth2) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * ").concat(stride0, " + col * ").concat(stride1, " +\n          depth * ").concat(stride2, " + depth2;\n      vec2 uv = uvFromFlat(").concat(texNumR, ", ").concat(texNumC, ", index + ").concat(offset, ");\n      return sampleTexture(").concat(texName, ", uv);\n    }\n  ");
    }
    function getSampler5D(inputInfo) {
      var shape = inputInfo.shapeInfo.logicalShape;
      var texName = inputInfo.name;
      var funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
      var stride3 = shape[4];
      var stride2 = shape[3] * stride3;
      var stride1 = shape[2] * stride2;
      var stride0 = shape[1] * stride1;
      var _a2 = tf.util.squeezeShape(shape), newShape = _a2.newShape, keptDims = _a2.keptDims;
      if (newShape.length < shape.length) {
        var newInputInfo = squeezeInputInfo(inputInfo, newShape);
        var params = ["row", "col", "depth", "depth2", "depth3"];
        return "\n      ".concat(getSamplerFromInInfo(newInputInfo), "\n      float ").concat(funcName, "(int row, int col, int depth, int depth2, int depth3) {\n        return ").concat(funcName, "(").concat(getSqueezedParams(params, keptDims), ");\n      }\n    ");
      }
      if (inputInfo.shapeInfo.isUniform) {
        return "\n      float ".concat(funcName, "(int row, int col, int depth, int depth2, int depth3) {\n        float index = dot(\n          vec4(row, col, depth, depth2),\n          vec4(").concat(stride0, ", ").concat(stride1, ", ").concat(stride2, ", ").concat(stride3, ")) +\n          depth3;\n        ").concat(getUniformSampler(inputInfo), "\n      }\n    ");
      }
      var flatOffset = inputInfo.shapeInfo.flatOffset;
      var texShape = inputInfo.shapeInfo.texShape;
      var texNumR = texShape[0];
      var texNumC = texShape[1];
      if (texNumC === stride0 && flatOffset == null) {
        return "\n      float ".concat(funcName, "(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(").concat(stride1, ", ").concat(stride2, ", ").concat(stride3, ", 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2(").concat(texNumC, ".0, ").concat(texNumR, ".0);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
      }
      if (texNumC === stride3 && flatOffset == null) {
        return "\n      float ".concat(funcName, "(int row, int col, int depth, int depth2, int depth3) {\n        float texR = dot(\n          vec4(row, col, depth, depth2),\n          vec4(").concat(shape[1] * shape[2] * shape[3], ",\n               ").concat(shape[2] * shape[3], ", ").concat(shape[3], ", 1));\n        int texC = depth3;\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2(").concat(texNumC, ".0, ").concat(texNumR, ".0);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
      }
      var offset = getFlatOffsetUniformName(texName);
      return "\n    float ".concat(funcName, "(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 * ").concat(stride0, " + col * ").concat(stride1, " + depth * ").concat(stride2, " +\n          depth2 * ").concat(stride3, " + depth3 + ").concat(offset, ";\n      vec2 uv = uvFromFlat(").concat(texNumR, ", ").concat(texNumC, ", index);\n      return sampleTexture(").concat(texName, ", uv);\n    }\n  ");
    }
    function getSampler6D(inputInfo) {
      var shape = inputInfo.shapeInfo.logicalShape;
      var texName = inputInfo.name;
      var funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
      var _a2 = tf.util.squeezeShape(shape), newShape = _a2.newShape, keptDims = _a2.keptDims;
      if (newShape.length < shape.length) {
        var newInputInfo = squeezeInputInfo(inputInfo, newShape);
        var params = ["row", "col", "depth", "depth2", "depth3", "depth4"];
        return "\n      ".concat(getSamplerFromInInfo(newInputInfo), "\n      float ").concat(funcName, "(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        return ").concat(funcName, "(").concat(getSqueezedParams(params, keptDims), ");\n      }\n    ");
      }
      var stride4 = shape[5];
      var stride3 = shape[4] * stride4;
      var stride2 = shape[3] * stride3;
      var stride1 = shape[2] * stride2;
      var stride0 = shape[1] * stride1;
      if (inputInfo.shapeInfo.isUniform) {
        return "\n      float ".concat(funcName, "(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(").concat(stride0, ", ").concat(stride1, ", ").concat(stride2, ", ").concat(stride3, ")) +\n          dot(\n            vec2(depth3, depth4),\n            vec2(").concat(stride4, ", 1)));\n        ").concat(getUniformSampler(inputInfo), "\n      }\n    ");
      }
      var flatOffset = inputInfo.shapeInfo.flatOffset;
      var texShape = inputInfo.shapeInfo.texShape;
      var texNumR = texShape[0];
      var texNumC = texShape[1];
      if (texNumC === stride0 && flatOffset == null) {
        return "\n      float ".concat(funcName, "(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(").concat(stride1, ", ").concat(stride2, ", ").concat(stride3, ", ").concat(stride4, ")) +\n               float(depth4);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2(").concat(texNumC, ".0, ").concat(texNumR, ".0);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
      }
      if (texNumC === stride4 && flatOffset == null) {
        return "\n      float ".concat(funcName, "(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        float texR = dot(vec4(row, col, depth, depth2),\n          vec4(").concat(shape[1] * shape[2] * shape[3] * shape[4], ",\n               ").concat(shape[2] * shape[3] * shape[4], ",\n               ").concat(shape[3] * shape[4], ",\n               ").concat(shape[4], ")) + float(depth3);\n        int texC = depth4;\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2(").concat(texNumC, ".0, ").concat(texNumR, ".0);\n        return sampleTexture(").concat(texName, ", uv);\n      }\n    ");
      }
      var offset = getFlatOffsetUniformName(texName);
      return "\n    float ".concat(funcName, "(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 * ").concat(stride0, " + col * ").concat(stride1, " + depth * ").concat(stride2, " +\n          depth2 * ").concat(stride3, " + depth3 * ").concat(stride4, " + depth4 + ").concat(offset, ";\n      vec2 uv = uvFromFlat(").concat(texNumR, ", ").concat(texNumC, ", index);\n      return sampleTexture(").concat(texName, ", uv);\n    }\n  ");
    }
    function getUniformSampler(inputInfo) {
      var texName = inputInfo.name;
      var inSize = tf.util.sizeFromShape(inputInfo.shapeInfo.logicalShape);
      if (inSize < 2) {
        return "return ".concat(texName, ";");
      }
      return "\n    for (int i = 0; i < ".concat(inSize, "; i++) {\n      if (i == index) {\n        return ").concat(texName, "[i];\n      }\n    }\n  ");
    }
    function getPackedSamplerAtOutputCoords(inputInfo, outShapeInfo) {
      var texName = inputInfo.name;
      var texFuncSnippet = texName.charAt(0).toUpperCase() + texName.slice(1);
      var funcName = "get" + texFuncSnippet + "AtOutCoords";
      var inRank = inputInfo.shapeInfo.logicalShape.length;
      var outRank = outShapeInfo.logicalShape.length;
      var broadcastDims = getBroadcastDims(inputInfo.shapeInfo.logicalShape, outShapeInfo.logicalShape);
      var type = getCoordsDataType(outRank);
      var rankDiff = outRank - inRank;
      var coordsSnippet;
      var fields = ["x", "y", "z", "w", "u", "v"];
      if (inRank === 0) {
        coordsSnippet = "";
      } else if (outRank < 2 && broadcastDims.length >= 1) {
        coordsSnippet = "coords = 0;";
      } else {
        coordsSnippet = broadcastDims.map(function(d) {
          return "coords.".concat(fields[d + rankDiff], " = 0;");
        }).join("\n");
      }
      var unpackedCoordsSnippet = "";
      if (outRank < 2 && inRank > 0) {
        unpackedCoordsSnippet = "coords";
      } else {
        unpackedCoordsSnippet = inputInfo.shapeInfo.logicalShape.map(function(s, i) {
          return "coords.".concat(fields[i + rankDiff]);
        }).join(", ");
      }
      var output = "return outputValue;";
      var inSize = tf.util.sizeFromShape(inputInfo.shapeInfo.logicalShape);
      var isInputScalar = inSize === 1;
      var outSize = tf.util.sizeFromShape(outShapeInfo.logicalShape);
      var isOutputScalar = outSize === 1;
      if (inRank === 1 && !isInputScalar && !isOutputScalar) {
        output = "\n      return vec4(outputValue.xy, outputValue.xy);\n    ";
      } else if (isInputScalar && !isOutputScalar) {
        if (outRank === 1) {
          output = "\n        return vec4(outputValue.x, outputValue.x, 0., 0.);\n      ";
        } else {
          output = "\n        return vec4(outputValue.x);\n      ";
        }
      } else if (broadcastDims.length) {
        var rows = inRank - 2;
        var cols = inRank - 1;
        if (broadcastDims.indexOf(rows) > -1 && broadcastDims.indexOf(cols) > -1) {
          output = "return vec4(outputValue.x);";
        } else if (broadcastDims.indexOf(rows) > -1) {
          output = "return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);";
        } else if (broadcastDims.indexOf(cols) > -1) {
          output = "return vec4(outputValue.xx, outputValue.zz);";
        }
      }
      return "\n    vec4 ".concat(funcName, "() {\n      ").concat(type, " coords = getOutputCoords();\n      ").concat(coordsSnippet, "\n      vec4 outputValue = get").concat(texFuncSnippet, "(").concat(unpackedCoordsSnippet, ");\n      ").concat(output, "\n    }\n  ");
    }
    function getSamplerAtOutputCoords(inputInfo, outShapeInfo) {
      var texName = inputInfo.name;
      var texFuncSnippet = texName.charAt(0).toUpperCase() + texName.slice(1);
      var funcName = "get" + texFuncSnippet + "AtOutCoords";
      var outTexShape = outShapeInfo.texShape;
      var inTexShape = inputInfo.shapeInfo.texShape;
      var inRank = inputInfo.shapeInfo.logicalShape.length;
      var outRank = outShapeInfo.logicalShape.length;
      if (!inputInfo.shapeInfo.isUniform && inRank === outRank && inputInfo.shapeInfo.flatOffset == null && tf.util.arraysEqual(inTexShape, outTexShape)) {
        return "\n      float ".concat(funcName, "() {\n        return sampleTexture(").concat(texName, ", resultUV);\n      }\n    ");
      }
      var type = getCoordsDataType(outRank);
      var broadcastDims = getBroadcastDims(inputInfo.shapeInfo.logicalShape, outShapeInfo.logicalShape);
      var rankDiff = outRank - inRank;
      var coordsSnippet;
      var fields = ["x", "y", "z", "w", "u", "v"];
      if (inRank === 0) {
        coordsSnippet = "";
      } else if (outRank < 2 && broadcastDims.length >= 1) {
        coordsSnippet = "coords = 0;";
      } else {
        coordsSnippet = broadcastDims.map(function(d) {
          return "coords.".concat(fields[d + rankDiff], " = 0;");
        }).join("\n");
      }
      var unpackedCoordsSnippet = "";
      if (outRank < 2 && inRank > 0) {
        unpackedCoordsSnippet = "coords";
      } else {
        unpackedCoordsSnippet = inputInfo.shapeInfo.logicalShape.map(function(s, i) {
          return "coords.".concat(fields[i + rankDiff]);
        }).join(", ");
      }
      return "\n    float ".concat(funcName, "() {\n      ").concat(type, " coords = getOutputCoords();\n      ").concat(coordsSnippet, "\n      return get").concat(texFuncSnippet, "(").concat(unpackedCoordsSnippet, ");\n    }\n  ");
    }
    function getCoordsDataType(rank) {
      if (rank <= 1) {
        return "int";
      } else if (rank === 2) {
        return "ivec2";
      } else if (rank === 3) {
        return "ivec3";
      } else if (rank === 4) {
        return "ivec4";
      } else if (rank === 5) {
        return "ivec5";
      } else if (rank === 6) {
        return "ivec6";
      } else {
        throw Error("GPU for rank ".concat(rank, " is not yet supported"));
      }
    }
    function getUniformInfoFromShape(isPacked, shape, texShape) {
      var _a2 = tf.util.squeezeShape(shape), newShape = _a2.newShape, keptDims = _a2.keptDims;
      var rank = shape.length;
      var useSqueezePackedShape = isPacked && rank === 3 && shape[0] === 1;
      var squeezeShape = useSqueezePackedShape ? shape.slice(1) : newShape;
      var useSqueezeShape = !isPacked && rank > 1 && !tf.util.arraysEqual(shape, texShape) && newShape.length < rank || useSqueezePackedShape;
      var uniformShape = useSqueezeShape ? squeezeShape : shape;
      return { useSqueezeShape, uniformShape, keptDims };
    }
    function squeezeInputInfo(inInfo, squeezedShape) {
      var newInputInfo = JSON.parse(JSON.stringify(inInfo));
      newInputInfo.shapeInfo.logicalShape = squeezedShape;
      return newInputInfo;
    }
    function getSqueezedParams(params, keptDims) {
      return keptDims.map(function(d) {
        return params[d];
      }).join(", ");
    }
    function compileProgram(gpgpu, program, inputs, output) {
      var inputInfos = inputs.map(function(input, i) {
        var shapeInfo = {
          logicalShape: input.shape,
          texShape: input.isUniform ? null : input.texData.texShape,
          isUniform: input.isUniform,
          isPacked: input.isUniform ? false : input.texData.isPacked,
          flatOffset: null
        };
        if (input.texData != null && input.texData.slice != null && input.texData.slice.flatOffset > 0) {
          shapeInfo.flatOffset = input.texData.slice.flatOffset;
        }
        return { name: program.variableNames[i], shapeInfo };
      });
      var inShapeInfos = inputInfos.map(function(x) {
        return x.shapeInfo;
      });
      var outShapeInfo = {
        logicalShape: output.shape,
        texShape: output.texData.texShape,
        isUniform: false,
        isPacked: output.texData.isPacked,
        flatOffset: null
      };
      var source = makeShader(inputInfos, outShapeInfo, program);
      var fragmentShader = createFragmentShader(gpgpu.gl, source);
      var webGLProgram = gpgpu.createProgram(fragmentShader);
      if (!tf.env().get("ENGINE_COMPILE_ONLY")) {
        gpgpu.buildVao(webGLProgram);
        return Object.assign({ program, fragmentShader, source, webGLProgram, inShapeInfos, outShapeInfo }, getUniformLocations(gpgpu, program, webGLProgram));
      } else {
        return {
          program,
          fragmentShader,
          source,
          webGLProgram,
          inShapeInfos,
          outShapeInfo,
          variablesLocations: null,
          customUniformLocations: null,
          infLoc: null,
          nanLoc: null,
          outShapeLocation: null,
          outShapeStridesLocation: null,
          outTexShapeLocation: null
        };
      }
    }
    function getUniformLocations(gpgpu, program, webGLProgram) {
      var e_12, _a2, e_2, _b;
      var variablesLocations = [];
      var customUniformLocations = [];
      var outShapeLocation;
      var outTexShapeLocation;
      var outShapeStridesLocation;
      var infLoc = null;
      var nanLoc = null;
      nanLoc = gpgpu.getUniformLocation(webGLProgram, "NAN", false);
      if (tf.env().getNumber("WEBGL_VERSION") === 1) {
        infLoc = gpgpu.getUniformLocation(webGLProgram, "INFINITY", false);
      }
      var shouldThrow = false;
      try {
        for (var _c = __values(program.variableNames), _d = _c.next(); !_d.done; _d = _c.next()) {
          var varName = _d.value;
          var varLocs = {
            name: varName,
            uniform: gpgpu.getUniformLocation(webGLProgram, varName, shouldThrow),
            offset: gpgpu.getUniformLocation(webGLProgram, "offset".concat(varName), shouldThrow)
          };
          if (program.enableShapeUniforms) {
            varLocs.shape = gpgpu.getUniformLocation(webGLProgram, "".concat(varName, "Shape"), shouldThrow);
            varLocs.texShape = gpgpu.getUniformLocation(webGLProgram, "".concat(varName, "TexShape"), shouldThrow);
          }
          variablesLocations.push(varLocs);
        }
      } catch (e_1_1) {
        e_12 = { error: e_1_1 };
      } finally {
        try {
          if (_d && !_d.done && (_a2 = _c.return)) _a2.call(_c);
        } finally {
          if (e_12) throw e_12.error;
        }
      }
      if (program.enableShapeUniforms) {
        outShapeLocation = gpgpu.getUniformLocation(webGLProgram, "outShape", shouldThrow);
        outShapeStridesLocation = gpgpu.getUniformLocation(webGLProgram, "outShapeStrides", shouldThrow);
        outTexShapeLocation = gpgpu.getUniformLocation(webGLProgram, "outTexShape", shouldThrow);
      }
      if (program.customUniforms) {
        try {
          for (var _e = __values(program.customUniforms), _f = _e.next(); !_f.done; _f = _e.next()) {
            var d = _f.value;
            customUniformLocations.push(gpgpu.getUniformLocation(webGLProgram, d.name, shouldThrow));
          }
        } catch (e_2_1) {
          e_2 = { error: e_2_1 };
        } finally {
          try {
            if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
          } finally {
            if (e_2) throw e_2.error;
          }
        }
      }
      return {
        variablesLocations,
        customUniformLocations,
        infLoc,
        nanLoc,
        outShapeLocation,
        outShapeStridesLocation,
        outTexShapeLocation
      };
    }
    function validateBinaryAndProgram(shapeInfos, inputs) {
      if (shapeInfos.length !== inputs.length) {
        throw Error("Binary was compiled with ".concat(shapeInfos.length, " inputs, but ") + "was executed with ".concat(inputs.length, " inputs"));
      }
      shapeInfos.forEach(function(s, i) {
        var shapeA = s.logicalShape;
        var input = inputs[i];
        var shapeB = input.shape;
        if (!tf.util.arraysEqual(shapeA, shapeB)) {
          throw Error("Binary was compiled with different shapes than " + "the current args. Shapes ".concat(shapeA, " and ").concat(shapeB, " must match"));
        }
        if (s.isUniform && input.isUniform) {
          return;
        }
        var texShapeA = s.texShape;
        var texShapeB = input.isUniform ? null : input.texData.texShape;
        if (!tf.util.arraysEqual(texShapeA, texShapeB)) {
          throw Error("Binary was compiled with different texture shapes than the" + " current args. Shape ".concat(texShapeA, " and ").concat(texShapeB, " must match"));
        }
      });
    }
    function runProgram(gpgpu, binary, inputs, output, customUniformValues) {
      if (!binary.program.enableShapeUniforms) {
        validateBinaryAndProgram(binary.inShapeInfos, inputs);
        validateBinaryAndProgram([binary.outShapeInfo], [output]);
      }
      var outTex = output.texData.texture;
      var outTexShape = output.texData.texShape;
      if (output.texData.isPacked) {
        gpgpu.setOutputPackedMatrixTexture(outTex.texture, outTexShape[0], outTexShape[1]);
      } else {
        gpgpu.setOutputMatrixTexture(outTex.texture, outTexShape[0], outTexShape[1]);
      }
      gpgpu.setProgram(binary.webGLProgram);
      gpgpu.bindVertexArray(binary.webGLProgram.vao);
      if (tf.env().getNumber("WEBGL_VERSION") === 1) {
        if (binary.infLoc !== null) {
          gpgpu.gl.uniform1f(binary.infLoc, Infinity);
        }
      }
      if (binary.nanLoc !== null) {
        gpgpu.gl.uniform1f(binary.nanLoc, NaN);
      }
      for (var i = 0; i < inputs.length; ++i) {
        var input = inputs[i];
        var _a2 = binary.variablesLocations[i], varLoc = _a2.uniform, varOffsetLoc = _a2.offset, varShapeLoc = _a2.shape, varTexShapeLoc = _a2.texShape;
        if (varShapeLoc) {
          var uniformShape = getUniformInfoFromShape(binary.program.packedInputs, input.shape, input.texData.texShape).uniformShape;
          switch (uniformShape.length) {
            case 1:
              gpgpu.gl.uniform1iv(varShapeLoc, new Int32Array(uniformShape));
              break;
            case 2:
              gpgpu.gl.uniform2iv(varShapeLoc, new Int32Array(uniformShape));
              break;
            case 3:
              gpgpu.gl.uniform3iv(varShapeLoc, new Int32Array(uniformShape));
              break;
            case 4:
              gpgpu.gl.uniform4iv(varShapeLoc, new Int32Array(uniformShape));
              break;
          }
        }
        if (varTexShapeLoc) {
          gpgpu.gl.uniform2i(varTexShapeLoc, input.texData.texShape[0], input.texData.texShape[1]);
        }
        if (varLoc == null) {
          continue;
        }
        if (input.isUniform) {
          if (tf.util.sizeFromShape(input.shape) < 2) {
            gpgpu.gl.uniform1f(varLoc, input.uniformValues[0]);
          } else {
            var vals = input.uniformValues;
            if (!(vals instanceof Float32Array)) {
              vals = new Float32Array(vals);
            }
            gpgpu.gl.uniform1fv(varLoc, vals);
          }
          continue;
        }
        if (input.texData.slice != null && varOffsetLoc != null) {
          gpgpu.gl.uniform1i(varOffsetLoc, input.texData.slice.flatOffset);
        }
        gpgpu.setInputMatrixTexture(input.texData.texture.texture, varLoc, i);
      }
      var outShapeLoc = binary.outShapeLocation;
      if (outShapeLoc) {
        switch (output.shape.length) {
          case 1:
            gpgpu.gl.uniform1iv(outShapeLoc, new Int32Array(output.shape));
            break;
          case 2:
            gpgpu.gl.uniform2iv(outShapeLoc, new Int32Array(output.shape));
            break;
          case 3:
            gpgpu.gl.uniform3iv(outShapeLoc, new Int32Array(output.shape));
            break;
          case 4:
            gpgpu.gl.uniform4iv(outShapeLoc, new Int32Array(output.shape));
            break;
        }
      }
      if (binary.outShapeStridesLocation) {
        var strides = tf.util.computeStrides(output.shape);
        switch (output.shape.length) {
          case 2:
            gpgpu.gl.uniform1iv(binary.outShapeStridesLocation, new Int32Array(strides));
            break;
          case 3:
            gpgpu.gl.uniform2iv(binary.outShapeStridesLocation, new Int32Array(strides));
            break;
          case 4:
            gpgpu.gl.uniform3iv(binary.outShapeStridesLocation, new Int32Array(strides));
            break;
        }
      }
      if (binary.outTexShapeLocation) {
        gpgpu.gl.uniform2i(binary.outTexShapeLocation, output.texData.texShape[0], output.texData.texShape[1]);
      }
      if (binary.program.customUniforms && customUniformValues) {
        for (var i = 0; i < binary.program.customUniforms.length; ++i) {
          var d = binary.program.customUniforms[i];
          var customLoc = binary.customUniformLocations[i];
          var customValue = customUniformValues[i];
          if (d.type === "float") {
            gpgpu.gl.uniform1fv(customLoc, customValue);
          } else if (d.type === "vec2") {
            gpgpu.gl.uniform2fv(customLoc, customValue);
          } else if (d.type === "vec3") {
            gpgpu.gl.uniform3fv(customLoc, customValue);
          } else if (d.type === "vec4") {
            gpgpu.gl.uniform4fv(customLoc, customValue);
          } else if (d.type === "int") {
            gpgpu.gl.uniform1iv(customLoc, customValue);
          } else if (d.type === "ivec2") {
            gpgpu.gl.uniform2iv(customLoc, customValue);
          } else if (d.type === "ivec3") {
            gpgpu.gl.uniform3iv(customLoc, customValue);
          } else if (d.type === "ivec4") {
            gpgpu.gl.uniform4iv(customLoc, customValue);
          } else {
            throw Error("uniform type ".concat(d.type, " is not supported yet."));
          }
        }
      }
      gpgpu.executeProgram();
    }
    function makeShaderKey(program, inputs, output) {
      var keyInputs = "";
      inputs.concat(output).forEach(function(x) {
        var hasOffset = x.texData != null && x.texData.slice != null && x.texData.slice.flatOffset > 0;
        if (program.enableShapeUniforms && !x.isUniform) {
          var xTexShape = x.texData.texShape;
          var _a2 = getUniformInfoFromShape(program.packedInputs, x.shape, xTexShape), useSqueezeShape = _a2.useSqueezeShape, uniformShape = _a2.uniformShape, keptDims = _a2.keptDims;
          var rank1 = "", rank2 = "", rank34 = "";
          if (uniformShape.length === 1 && program.packedInputs) {
            var packedTexShape = [Math.ceil(xTexShape[0] / 2), Math.ceil(xTexShape[1] / 2)];
            rank1 = "".concat(packedTexShape[0] > 1, "_").concat(packedTexShape[1] > 1);
          } else if (uniformShape.length === 2 && !program.packedInputs) {
            rank2 = "".concat(uniformShape[0] > 1, "_").concat(uniformShape[1] > 1);
          } else if (uniformShape.length > 2 && !program.packedInputs) {
            var strides = tf.util.computeStrides(uniformShape);
            rank34 = "".concat(strides[0] === xTexShape[1], "_").concat(strides[strides.length - 1] === xTexShape[1]);
          }
          var xRank = x.shape.length;
          var isLogicalShapTexShapeEqual = uniformShape.length === 2 && tf.util.arraysEqual(x.shape, xTexShape);
          var isScalar = tf.util.sizeFromShape(x.shape) === 1;
          var broadcastDims = tf.backend_util.getBroadcastDims(x.shape, output.shape);
          var isInOutTexShapeEqual = !program.packedInputs && xRank === output.shape.length && tf.util.arraysEqual(xTexShape, output.texData.texShape);
          var isTexShapeGreaterThanOne = program.packedInputs || uniformShape.length > 2 ? "" : "".concat(xTexShape[0] > 1, "_").concat(xTexShape[1] > 1);
          keyInputs += "".concat(xRank, "_").concat(isInOutTexShapeEqual, "_").concat(useSqueezeShape ? keptDims : "", "_").concat(uniformShape.length, "_").concat(isScalar, "_").concat(broadcastDims, "_").concat(isLogicalShapTexShapeEqual, "_").concat(rank1, "_").concat(rank2, "_").concat(rank34, "_").concat(isTexShapeGreaterThanOne, "_").concat(hasOffset);
        } else {
          var texShape = x.isUniform ? "uniform" : x.texData.texShape;
          keyInputs += "".concat(x.shape, "_").concat(texShape, "_").concat(hasOffset);
        }
      });
      var keyUserCode = program.userCode;
      var key = program.constructor.name;
      key += "_" + keyInputs + "_" + keyUserCode + "".concat(tf.env().getNumber("WEBGL_VERSION"));
      return key;
    }
    function useShapeUniforms(rank) {
      return tf.env().getBool("WEBGL_USE_SHAPES_UNIFORMS") && rank <= 4;
    }
    var DecodeMatrixProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function DecodeMatrixProgram2(outputShape) {
          this.variableNames = ["A"];
          this.packedInputs = false;
          this.packedOutput = true;
          this.outPackingScheme = PackingScheme.DENSE;
          this.customUniforms = [{ name: "texShape", type: "ivec2" }];
          var glsl = getGlslDifferences();
          this.outputShape = outputShape;
          this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);
          this.userCode = "\n      ivec3 outCoordsFromFlatIndex(int index) {\n        ".concat(this.enableShapeUniforms ? getOutputLogicalCoordinatesFromFlatIndexByUniform(["r", "c", "d"], outputShape) : getLogicalCoordinatesFromFlatIndex(["r", "c", "d"], outputShape), "\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        ").concat(glsl.output, " = result;\n      }\n    ");
        }
        return DecodeMatrixProgram2;
      }()
    );
    var DecodeMatrixPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function DecodeMatrixPackedProgram2(outputShape) {
          this.variableNames = ["A"];
          this.packedInputs = true;
          this.packedOutput = true;
          this.outPackingScheme = PackingScheme.DENSE;
          this.customUniforms = [{ name: "texShape", type: "ivec2" }];
          var glsl = getGlslDifferences();
          this.outputShape = outputShape;
          this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);
          this.userCode = "\n      ivec3 outCoordsFromFlatIndex(int index) {\n        ".concat(this.enableShapeUniforms ? getOutputLogicalCoordinatesFromFlatIndexByUniform(["r", "c", "d"], outputShape) : getLogicalCoordinatesFromFlatIndex(["r", "c", "d"], outputShape), "\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        ").concat(glsl.output, " = result;\n      }\n    ");
        }
        return DecodeMatrixPackedProgram2;
      }()
    );
    var EncodeFloatProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function EncodeFloatProgram2(outputShape) {
          this.variableNames = ["A"];
          this.outTexUsage = TextureUsage.DOWNLOAD;
          var glsl = getGlslDifferences();
          this.outputShape = outputShape;
          this.userCode = "\n      ".concat(ENCODE_FLOAT_SNIPPET, "\n\n      void main() {\n        float x = getAAtOutCoords();\n        ").concat(glsl.output, " = encode_float(x);\n      }\n    ");
        }
        return EncodeFloatProgram2;
      }()
    );
    var EncodeFloatPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function EncodeFloatPackedProgram2(outputShape) {
          this.variableNames = ["A"];
          this.packedInputs = true;
          this.packedOutput = false;
          this.outTexUsage = TextureUsage.DOWNLOAD;
          var glsl = getGlslDifferences();
          this.outputShape = outputShape;
          this.userCode = "\n      ".concat(ENCODE_FLOAT_SNIPPET, "\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n        float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n        ").concat(glsl.output, " = encode_float(x);\n      }\n    ");
        }
        return EncodeFloatPackedProgram2;
      }()
    );
    var CHANNEL_CHAR_TO_INDEX_MAP = {
      "R": 0,
      "G": 1,
      "B": 2,
      "A": 3
    };
    var EncodeMatrixProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function EncodeMatrixProgram2(outputShape, inputIsUnsignedByte, usedChannels) {
          if (inputIsUnsignedByte === void 0) {
            inputIsUnsignedByte = false;
          }
          if (usedChannels === void 0) {
            usedChannels = "RGBA";
          }
          this.variableNames = ["A"];
          this.customUniforms = [{ name: "texShape", type: "ivec2" }];
          var glsl = getGlslDifferences();
          this.outputShape = outputShape;
          this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);
          var output = "result";
          if (inputIsUnsignedByte) {
            output = "floor(result * 255. + 0.5)";
          }
          var mainLoop = "";
          for (var usedChannelIndex = 0; usedChannelIndex < usedChannels.length; usedChannelIndex++) {
            var curChannel = usedChannels[usedChannelIndex];
            mainLoop += "\n          if(offset == ".concat(usedChannelIndex, ") {\n            result = values[").concat(CHANNEL_CHAR_TO_INDEX_MAP[curChannel], "];\n          }");
          }
          this.userCode = "\n      ".concat(this.enableShapeUniforms ? getFlatIndexFrom3DOutput() : getFlatIndexFrom3D(outputShape), "\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n        int flatIndex = getFlatIndex(coords);\n        float result = 0.;\n        int offset = imod(flatIndex, ").concat(usedChannels.length, ");\n\n        flatIndex = idiv(flatIndex, ").concat(usedChannels.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 = ").concat(glsl.texture2D, "(A, uv);\n          ").concat(mainLoop, "\n        }\n        ").concat(glsl.output, " = vec4(").concat(output, ", 0., 0., 0.);\n      }\n    ");
        }
        return EncodeMatrixProgram2;
      }()
    );
    var EncodeMatrixPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function EncodeMatrixPackedProgram2(outputShape, inputIsUnsignedByte) {
          if (inputIsUnsignedByte === void 0) {
            inputIsUnsignedByte = false;
          }
          this.variableNames = ["A"];
          this.packedInputs = false;
          this.packedOutput = true;
          this.customUniforms = [{ name: "texShape", type: "ivec2" }];
          var glsl = getGlslDifferences();
          this.outputShape = outputShape;
          this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);
          var mainLoop = "";
          var output = "result";
          if (inputIsUnsignedByte) {
            output = "floor(result * 255. + 0.5)";
          }
          for (var row = 0; row <= 1; row++) {
            for (var col = 0; col <= 1; col++) {
              var channel = row * 2 + col;
              mainLoop += "\n          localCoords = coords;\n          if(localCoords[2] + ".concat(col, " < ").concat(this.enableShapeUniforms ? "outShape[2]" : "".concat(outputShape[2]), ") {\n          localCoords[2] += ").concat(col, ";\n          if (localCoords[1] + ").concat(row, " < ").concat(this.enableShapeUniforms ? "outShape[1]" : "".concat(outputShape[1]), ") {\n            localCoords[1] += ").concat(row, ";\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 = ").concat(glsl.texture2D, "(A, uv);\n\n            if (offset == 0) {\n              result[").concat(channel, "] = values[0];\n            } else if (offset == 1) {\n              result[").concat(channel, "] = values[1];\n            } else if (offset == 2) {\n              result[").concat(channel, "] = values[2];\n            } else {\n              result[").concat(channel, "] = values[3];\n            }\n          }\n        }\n        ");
            }
          }
          this.userCode = "\n        ".concat(this.enableShapeUniforms ? getFlatIndexFrom3DOutput() : getFlatIndexFrom3D(outputShape), "\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          ").concat(mainLoop, "\n\n          ").concat(glsl.output, " = ").concat(output, ";\n        }\n    ");
        }
        return EncodeMatrixPackedProgram2;
      }()
    );
    function createVertexShader(gl) {
      var glsl = getGlslDifferences();
      var vertexShaderSource = "".concat(glsl.version, "\n    precision highp float;\n    ").concat(glsl.attribute, " vec3 clipSpacePos;\n    ").concat(glsl.attribute, " vec2 uv;\n    ").concat(glsl.varyingVs, " vec2 resultUV;\n\n    void main() {\n      gl_Position = vec4(clipSpacePos, 1);\n      resultUV = uv;\n    }");
      return createVertexShader$1(gl, vertexShaderSource);
    }
    function createVertexBuffer(gl) {
      var vertexArray = new Float32Array([-1, 1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0]);
      return createStaticVertexBuffer(gl, vertexArray);
    }
    function createIndexBuffer(gl) {
      var triangleVertexIndices = new Uint16Array([0, 1, 2, 2, 1, 3]);
      return createStaticIndexBuffer(gl, triangleVertexIndices);
    }
    function createAndConfigureTexture(gl, width, height, internalFormat, textureFormat, textureType) {
      validateTextureSize(width, height);
      var texture = createTexture(gl);
      var tex2d = gl.TEXTURE_2D;
      callAndCheck(gl, function() {
        return gl.bindTexture(tex2d, texture);
      });
      callAndCheck(gl, function() {
        return gl.texParameteri(tex2d, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      });
      callAndCheck(gl, function() {
        return gl.texParameteri(tex2d, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      });
      callAndCheck(gl, function() {
        return gl.texParameteri(tex2d, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      });
      callAndCheck(gl, function() {
        return gl.texParameteri(tex2d, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
      });
      if (tf.env().getNumber("WEBGL_VERSION") === 1) {
        callAndCheck(gl, function() {
          return gl.texImage2D(tex2d, 0, internalFormat, width, height, 0, textureFormat, textureType, null);
        });
      } else {
        callAndCheck(gl, function() {
          return gl.texStorage2D(tex2d, 1, internalFormat, width, height);
        });
      }
      callAndCheck(gl, function() {
        return gl.bindTexture(gl.TEXTURE_2D, null);
      });
      return { texture, texShape: [height, width] };
    }
    function getInternalFormatForFloat32MatrixTexture(textureConfig) {
      return textureConfig.internalFormatFloat;
    }
    function createFloat32MatrixTexture(gl, rows, columns, textureConfig) {
      var _a2 = __read(getUnpackedMatrixTextureShapeWidthHeight(rows, columns), 2), width = _a2[0], height = _a2[1];
      return createAndConfigureTexture(gl, width, height, getInternalFormatForFloat32MatrixTexture(textureConfig), textureConfig.textureFormatFloat, gl.FLOAT);
    }
    function getInternalFormatForFloat16MatrixTexture(textureConfig) {
      return textureConfig.internalFormatHalfFloat;
    }
    function createFloat16MatrixTexture(gl, rows, columns, textureConfig) {
      var _a2 = __read(getUnpackedMatrixTextureShapeWidthHeight(rows, columns), 2), width = _a2[0], height = _a2[1];
      return createAndConfigureTexture(gl, width, height, getInternalFormatForFloat16MatrixTexture(textureConfig), textureConfig.textureFormatFloat, textureConfig.textureTypeHalfFloat);
    }
    function getInternalFormatForUnsignedBytesMatrixTexture(textureConfig) {
      return textureConfig.downloadTextureFormat;
    }
    function createUnsignedBytesMatrixTexture(gl, rows, columns, textureConfig) {
      var _a2 = __read(getUnpackedMatrixTextureShapeWidthHeight(rows, columns), 2), width = _a2[0], height = _a2[1];
      return createAndConfigureTexture(gl, width, height, getInternalFormatForUnsignedBytesMatrixTexture(textureConfig), gl.RGBA, gl.UNSIGNED_BYTE);
    }
    function getInternalFormatForPackedMatrixTexture(textureConfig) {
      return textureConfig.internalFormatPackedFloat;
    }
    function createPackedMatrixTexture(gl, rows, columns, textureConfig) {
      var _a2 = __read(getPackedMatrixTextureShapeWidthHeight(rows, columns), 2), width = _a2[0], height = _a2[1];
      return createAndConfigureTexture(gl, width, height, getInternalFormatForPackedMatrixTexture(textureConfig), gl.RGBA, gl.FLOAT);
    }
    function getInternalFormatForFloat16PackedMatrixTexture(textureConfig) {
      return textureConfig.internalFormatPackedHalfFloat;
    }
    function createFloat16PackedMatrixTexture(gl, rows, columns, textureConfig) {
      var _a2 = __read(getPackedMatrixTextureShapeWidthHeight(rows, columns), 2), width = _a2[0], height = _a2[1];
      return createAndConfigureTexture(gl, width, height, getInternalFormatForFloat16PackedMatrixTexture(textureConfig), gl.RGBA, textureConfig.textureTypeHalfFloat);
    }
    function bindVertexProgramAttributeStreams(gl, program, vertexBuffer) {
      var posOffset = 0;
      var uvOffset = 3 * 4;
      var stride = 3 * 4 + 2 * 4;
      callAndCheck(gl, function() {
        return gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
      });
      var success = bindVertexBufferToProgramAttribute(gl, program, "clipSpacePos", vertexBuffer, 3, stride, posOffset);
      return success && bindVertexBufferToProgramAttribute(gl, program, "uv", vertexBuffer, 2, stride, uvOffset);
    }
    function uploadDenseMatrixToTexture(gl, texture, width, height, data, textureConfig) {
      callAndCheck(gl, function() {
        return gl.bindTexture(gl.TEXTURE_2D, texture);
      });
      var dataForUpload, texelDataType, internalFormat;
      if (data instanceof Uint8Array) {
        dataForUpload = new Uint8Array(width * height * 4);
        texelDataType = gl.UNSIGNED_BYTE;
        internalFormat = gl.RGBA;
      } else {
        dataForUpload = new Float32Array(width * height * 4);
        texelDataType = gl.FLOAT;
        internalFormat = textureConfig.internalFormatPackedFloat;
      }
      dataForUpload.set(data);
      if (tf.env().getNumber("WEBGL_VERSION") === 2) {
        callAndCheck(gl, function() {
          return gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, gl.RGBA, texelDataType, dataForUpload);
        });
      } else {
        callAndCheck(gl, function() {
          return gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, width, height, 0, gl.RGBA, texelDataType, dataForUpload);
        });
      }
      callAndCheck(gl, function() {
        return gl.bindTexture(gl.TEXTURE_2D, null);
      });
    }
    function uploadPixelDataToTexture(gl, texture, pixels) {
      callAndCheck(gl, function() {
        return gl.bindTexture(gl.TEXTURE_2D, texture);
      });
      if (pixels.data instanceof Uint8Array) {
        if (tf.env().getNumber("WEBGL_VERSION") === 2) {
          callAndCheck(gl, function() {
            return gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, pixels.width, pixels.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels.data);
          });
        } else {
          callAndCheck(gl, function() {
            return gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pixels.width, pixels.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, pixels.data);
          });
        }
      } else {
        if (tf.env().getNumber("WEBGL_VERSION") === 2) {
          callAndCheck(gl, function() {
            return gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
          });
        } else {
          callAndCheck(gl, function() {
            return gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
          });
        }
      }
      callAndCheck(gl, function() {
        return gl.bindTexture(gl.TEXTURE_2D, null);
      });
    }
    function createBufferFromOutputTexture(gl2, rows, columns, textureConfig) {
      var buffer = gl2.createBuffer();
      callAndCheck(gl2, function() {
        return gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, buffer);
      });
      var bytesPerFloat = 4;
      var valuesPerTexel = 4;
      var bufferSizeBytes = bytesPerFloat * valuesPerTexel * rows * columns;
      callAndCheck(gl2, function() {
        return gl2.bufferData(gl2.PIXEL_PACK_BUFFER, bufferSizeBytes, gl2.STREAM_READ);
      });
      callAndCheck(gl2, function() {
        return gl2.readPixels(0, 0, columns, rows, gl2.RGBA, gl2.FLOAT, 0);
      });
      callAndCheck(gl2, function() {
        return gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, null);
      });
      return buffer;
    }
    function downloadFloat32MatrixFromBuffer(gl, buffer, size) {
      var gl2 = gl;
      var downloadTarget = new Float32Array(size);
      gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, buffer);
      gl2.getBufferSubData(gl2.PIXEL_PACK_BUFFER, 0, downloadTarget);
      gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, null);
      return downloadTarget;
    }
    function downloadByteEncodedFloatMatrixFromOutputTexture(gl, rows, columns, textureConfig) {
      var _a2 = __read(getUnpackedMatrixTextureShapeWidthHeight(rows, columns), 2), w = _a2[0], h = _a2[1];
      var numChannels = 4;
      var downloadTarget = new Uint8Array(getUnpackedArraySizeFromMatrixSize(rows * columns, numChannels));
      callAndCheck(gl, function() {
        return gl.readPixels(0, 0, w, h, textureConfig.downloadTextureFormat, gl.UNSIGNED_BYTE, downloadTarget);
      });
      return new Float32Array(downloadTarget.buffer);
    }
    function downloadPackedMatrixFromBuffer(gl, buffer, batch, rows, cols, physicalRows, physicalCols, textureConfig) {
      var gl2 = gl;
      var downloadTarget = new Float32Array(getPackedRGBAArraySizeFromMatrixShape(physicalRows, physicalCols));
      gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, buffer);
      gl2.getBufferSubData(gl2.PIXEL_PACK_BUFFER, 0, downloadTarget);
      gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, null);
      return downloadTarget;
    }
    function downloadMatrixFromPackedOutputTexture(gl, physicalRows, physicalCols) {
      var packedRGBA = new Float32Array(physicalRows * physicalCols * 4);
      callAndCheck(gl, function() {
        return gl.readPixels(0, 0, physicalCols, physicalRows, gl.RGBA, gl.FLOAT, packedRGBA);
      });
      return packedRGBA;
    }
    var gpgpu_util = {
      __proto__: null,
      bindVertexProgramAttributeStreams,
      createBufferFromOutputTexture,
      createFloat16MatrixTexture,
      createFloat16PackedMatrixTexture,
      createFloat32MatrixTexture,
      createIndexBuffer,
      createPackedMatrixTexture,
      createUnsignedBytesMatrixTexture,
      createVertexBuffer,
      createVertexShader,
      downloadByteEncodedFloatMatrixFromOutputTexture,
      downloadFloat32MatrixFromBuffer,
      downloadMatrixFromPackedOutputTexture,
      downloadPackedMatrixFromBuffer,
      getInternalFormatForFloat16MatrixTexture,
      getInternalFormatForFloat16PackedMatrixTexture,
      getInternalFormatForFloat32MatrixTexture,
      getInternalFormatForPackedMatrixTexture,
      getInternalFormatForUnsignedBytesMatrixTexture,
      uploadDenseMatrixToTexture,
      uploadPixelDataToTexture
    };
    var GPGPUContext = (
      /** @class */
      function() {
        function GPGPUContext2(gl) {
          this.outputTexture = null;
          this.program = null;
          this.disposed = false;
          this.itemsToPoll = [];
          var glVersion = tf.env().getNumber("WEBGL_VERSION");
          if (gl != null) {
            this.gl = gl;
            setWebGLContext(glVersion, gl);
          } else {
            this.gl = getWebGLContext(glVersion);
          }
          gl = this.gl;
          if (tf.env().getNumber("WEBGL_VERSION") === 2) {
            var gl2_1 = gl;
            this.createVertexArray = function() {
              return callAndCheck(gl2_1, function() {
                return gl2_1.createVertexArray();
              });
            };
            this.bindVertexArray = function(vao) {
              return callAndCheck(gl2_1, function() {
                return gl2_1.bindVertexArray(vao);
              });
            };
            this.deleteVertexArray = function(vao) {
              return callAndCheck(gl2_1, function() {
                return gl2_1.deleteVertexArray(vao);
              });
            };
            this.getVertexArray = function() {
              return callAndCheck(gl2_1, function() {
                return gl2_1.getParameter(gl2_1.VERTEX_ARRAY_BINDING);
              });
            };
          } else if (gl != null) {
            var ext_1 = gl.getExtension("OES_vertex_array_object");
            if (ext_1 == null) {
              throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");
            }
            this.createVertexArray = function() {
              return callAndCheck(gl, function() {
                return ext_1.createVertexArrayOES();
              });
            };
            this.bindVertexArray = function(vao) {
              return callAndCheck(gl, function() {
                return ext_1.bindVertexArrayOES(vao);
              });
            };
            this.deleteVertexArray = function(vao) {
              return callAndCheck(gl, function() {
                return ext_1.deleteVertexArrayOES(vao);
              });
            };
            this.getVertexArray = function() {
              return callAndCheck(gl, function() {
                return gl.getParameter(ext_1.VERTEX_ARRAY_BINDING_OES);
              });
            };
          }
          var COLOR_BUFFER_FLOAT = "WEBGL_color_buffer_float";
          var COLOR_BUFFER_HALF_FLOAT = "EXT_color_buffer_half_float";
          this.parallelCompilationExtension = this.gl.getExtension("KHR_parallel_shader_compile");
          if (tf.env().getNumber("WEBGL_VERSION") === 1) {
            var TEXTURE_FLOAT = "OES_texture_float";
            var TEXTURE_HALF_FLOAT = "OES_texture_half_float";
            this.textureFloatExtension = getExtensionOrThrow(this.gl, TEXTURE_FLOAT);
            if (hasExtension(this.gl, TEXTURE_HALF_FLOAT)) {
              this.textureHalfFloatExtension = getExtensionOrThrow(this.gl, TEXTURE_HALF_FLOAT);
            } else if (tf.env().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.");
            }
            this.colorBufferFloatExtension = this.gl.getExtension(COLOR_BUFFER_FLOAT);
            if (hasExtension(this.gl, COLOR_BUFFER_HALF_FLOAT)) {
              this.colorBufferHalfFloatExtension = getExtensionOrThrow(this.gl, COLOR_BUFFER_HALF_FLOAT);
            } else if (tf.env().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 {
            COLOR_BUFFER_FLOAT = "EXT_color_buffer_float";
            if (hasExtension(this.gl, COLOR_BUFFER_FLOAT)) {
              this.colorBufferFloatExtension = this.gl.getExtension(COLOR_BUFFER_FLOAT);
            } else if (hasExtension(this.gl, COLOR_BUFFER_HALF_FLOAT)) {
              this.colorBufferHalfFloatExtension = this.gl.getExtension(COLOR_BUFFER_HALF_FLOAT);
            } else {
              throw new Error("GL context does not support color renderable floats");
            }
          }
          this.vertexBuffer = createVertexBuffer(this.gl);
          this.indexBuffer = createIndexBuffer(this.gl);
          this.framebuffer = createFramebuffer(this.gl);
          this.textureConfig = getTextureConfig(this.gl, this.textureHalfFloatExtension);
        }
        Object.defineProperty(GPGPUContext2.prototype, "debug", {
          get: function() {
            return tf.env().getBool("DEBUG");
          },
          enumerable: false,
          configurable: true
        });
        GPGPUContext2.prototype.dispose = function() {
          var _this = this;
          if (this.disposed) {
            return;
          }
          if (this.program != null) {
            console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing.");
          }
          if (this.outputTexture != null) {
            console.warn("Disposing a GPGPUContext that still has a bound output matrix texture.  This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");
          }
          var gl = this.gl;
          callAndCheck(gl, function() {
            return gl.finish();
          });
          callAndCheck(gl, function() {
            return gl.bindFramebuffer(gl.FRAMEBUFFER, null);
          });
          callAndCheck(gl, function() {
            return gl.deleteFramebuffer(_this.framebuffer);
          });
          callAndCheck(gl, function() {
            return gl.bindBuffer(gl.ARRAY_BUFFER, null);
          });
          callAndCheck(gl, function() {
            return gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
          });
          callAndCheck(gl, function() {
            return gl.deleteBuffer(_this.indexBuffer);
          });
          this.disposed = true;
        };
        GPGPUContext2.prototype.createFloat32MatrixTexture = function(rows, columns) {
          this.throwIfDisposed();
          return createFloat32MatrixTexture(this.gl, rows, columns, this.textureConfig);
        };
        GPGPUContext2.prototype.createFloat16MatrixTexture = function(rows, columns) {
          this.throwIfDisposed();
          return createFloat16MatrixTexture(this.gl, rows, columns, this.textureConfig);
        };
        GPGPUContext2.prototype.createUnsignedBytesMatrixTexture = function(rows, columns) {
          this.throwIfDisposed();
          return createUnsignedBytesMatrixTexture(this.gl, rows, columns, this.textureConfig);
        };
        GPGPUContext2.prototype.uploadPixelDataToTexture = function(texture, pixels) {
          this.throwIfDisposed();
          uploadPixelDataToTexture(this.gl, texture, pixels);
        };
        GPGPUContext2.prototype.uploadDenseMatrixToTexture = function(texture, width, height, data) {
          this.throwIfDisposed();
          uploadDenseMatrixToTexture(this.gl, texture, width, height, data, this.textureConfig);
        };
        GPGPUContext2.prototype.createFloat16PackedMatrixTexture = function(rows, columns) {
          this.throwIfDisposed();
          return createFloat16PackedMatrixTexture(this.gl, rows, columns, this.textureConfig);
        };
        GPGPUContext2.prototype.createPackedMatrixTexture = function(rows, columns) {
          this.throwIfDisposed();
          return createPackedMatrixTexture(this.gl, rows, columns, this.textureConfig);
        };
        GPGPUContext2.prototype.deleteMatrixTexture = function(texture) {
          var _this = this;
          this.throwIfDisposed();
          if (this.outputTexture === texture) {
            unbindColorTextureFromFramebuffer(this.gl, this.framebuffer);
            this.outputTexture = null;
          }
          callAndCheck(this.gl, function() {
            return _this.gl.deleteTexture(texture);
          });
        };
        GPGPUContext2.prototype.downloadByteEncodedFloatMatrixFromOutputTexture = function(texture, rows, columns) {
          var _this = this;
          return this.downloadMatrixDriver(texture, function() {
            return downloadByteEncodedFloatMatrixFromOutputTexture(_this.gl, rows, columns, _this.textureConfig);
          });
        };
        GPGPUContext2.prototype.downloadPackedMatrixFromBuffer = function(buffer, batch, rows, columns, physicalRows, physicalCols) {
          return downloadPackedMatrixFromBuffer(this.gl, buffer, batch, rows, columns, physicalRows, physicalCols, this.textureConfig);
        };
        GPGPUContext2.prototype.downloadFloat32MatrixFromBuffer = function(buffer, size) {
          return downloadFloat32MatrixFromBuffer(this.gl, buffer, size);
        };
        GPGPUContext2.prototype.createBufferFromTexture = function(texture, rows, columns) {
          this.bindTextureToFrameBuffer(texture);
          var result = createBufferFromOutputTexture(this.gl, rows, columns, this.textureConfig);
          this.unbindTextureToFrameBuffer();
          return result;
        };
        GPGPUContext2.prototype.createAndWaitForFence = function() {
          var fenceContext = this.createFence(this.gl);
          return this.pollFence(fenceContext);
        };
        GPGPUContext2.prototype.createFence = function(gl) {
          var _this = this;
          var query;
          var isFencePassed;
          if (tf.env().getBool("WEBGL_FENCE_API_ENABLED")) {
            var gl2_2 = gl;
            var sync_1 = gl2_2.fenceSync(gl2_2.SYNC_GPU_COMMANDS_COMPLETE, 0);
            gl.flush();
            isFencePassed = function() {
              var status = gl2_2.clientWaitSync(sync_1, 0, 0);
              return status === gl2_2.ALREADY_SIGNALED || status === gl2_2.CONDITION_SATISFIED;
            };
            query = sync_1;
          } else if (tf.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") > 0) {
            query = this.beginQuery();
            this.endQuery();
            isFencePassed = function() {
              return _this.isQueryAvailable(query, tf.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"));
            };
          } else {
            isFencePassed = function() {
              return true;
            };
          }
          return { query, isFencePassed };
        };
        GPGPUContext2.prototype.downloadMatrixFromPackedTexture = function(texture, physicalRows, physicalCols) {
          var _this = this;
          return this.downloadMatrixDriver(texture, function() {
            return downloadMatrixFromPackedOutputTexture(_this.gl, physicalRows, physicalCols);
          });
        };
        GPGPUContext2.prototype.createProgram = function(fragmentShader) {
          var _this = this;
          this.throwIfDisposed();
          var gl = this.gl;
          if (this.vertexShader == null) {
            this.vertexShader = createVertexShader(gl);
          }
          var program = createProgram(gl);
          callAndCheck(gl, function() {
            return gl.attachShader(program, _this.vertexShader);
          });
          callAndCheck(gl, function() {
            return gl.attachShader(program, fragmentShader);
          });
          linkProgram(gl, program);
          var program2 = Object.assign(program, { vao: this.createVertexArray() });
          if (this.debug) {
            validateProgram(gl, program2);
          }
          return program2;
        };
        GPGPUContext2.prototype.buildVao = function(program) {
          var _this = this;
          this.setProgram(program);
          this.bindVertexArray(program.vao);
          var gl = this.gl;
          callAndCheck(gl, function() {
            return gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _this.indexBuffer);
          });
          bindVertexProgramAttributeStreams(gl, program, this.vertexBuffer);
        };
        GPGPUContext2.prototype.deleteProgram = function(program) {
          var _this = this;
          this.throwIfDisposed();
          if (program === this.program) {
            this.program = null;
          }
          if (program != null) {
            callAndCheck(this.gl, function() {
              return _this.gl.deleteProgram(program);
            });
            this.deleteVertexArray(program.vao);
          }
        };
        GPGPUContext2.prototype.setProgram = function(program) {
          var _this = this;
          this.throwIfDisposed();
          this.program = program;
          if (this.program != null) {
            if (this.debug) {
              validateProgram(this.gl, this.program);
            }
          }
          callAndCheck(this.gl, function() {
            return _this.gl.useProgram(program);
          });
        };
        GPGPUContext2.prototype.getUniformLocation = function(program, uniformName, shouldThrow) {
          if (shouldThrow === void 0) {
            shouldThrow = true;
          }
          this.throwIfDisposed();
          if (shouldThrow) {
            return getProgramUniformLocationOrThrow(this.gl, program, uniformName);
          } else {
            return getProgramUniformLocation(this.gl, program, uniformName);
          }
        };
        GPGPUContext2.prototype.getAttributeLocation = function(program, attribute) {
          var _this = this;
          this.throwIfDisposed();
          return callAndCheck(this.gl, function() {
            return _this.gl.getAttribLocation(program, attribute);
          });
        };
        GPGPUContext2.prototype.getUniformLocationNoThrow = function(program, uniformName) {
          this.throwIfDisposed();
          return this.gl.getUniformLocation(program, uniformName);
        };
        GPGPUContext2.prototype.setInputMatrixTexture = function(inputMatrixTexture, uniformLocation, textureUnit) {
          this.throwIfDisposed();
          this.throwIfNoProgram();
          bindTextureToProgramUniformSampler(this.gl, inputMatrixTexture, uniformLocation, textureUnit);
        };
        GPGPUContext2.prototype.setOutputMatrixTexture = function(outputMatrixTexture, rows, columns) {
          this.setOutputMatrixTextureDriver(outputMatrixTexture, columns, rows);
        };
        GPGPUContext2.prototype.setOutputPackedMatrixTexture = function(outputPackedMatrixTexture, rows, columns) {
          this.throwIfDisposed();
          var _a2 = __read(getPackedMatrixTextureShapeWidthHeight(rows, columns), 2), width = _a2[0], height = _a2[1];
          this.setOutputMatrixTextureDriver(outputPackedMatrixTexture, width, height);
        };
        GPGPUContext2.prototype.setOutputMatrixWriteRegion = function(startRow, numRows, startColumn, numColumns) {
          this.setOutputMatrixWriteRegionDriver(startColumn, startRow, numColumns, numRows);
        };
        GPGPUContext2.prototype.setOutputPackedMatrixWriteRegion = function(startRow, numRows, startColumn, numColumns) {
          throw new Error("setOutputPackedMatrixWriteRegion not implemented.");
        };
        GPGPUContext2.prototype.debugValidate = function() {
          if (this.program != null) {
            validateProgram(this.gl, this.program);
          }
          validateFramebuffer(this.gl);
        };
        GPGPUContext2.prototype.executeProgram = function() {
          this.throwIfDisposed();
          this.throwIfNoProgram();
          var gl = this.gl;
          if (this.debug) {
            var boundVao = this.getVertexArray();
            console.assert(boundVao === this.program.vao, "VAO changed between setProgram and executeProgram!");
            this.debugValidate();
          }
          callAndCheck(gl, function() {
            return gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
          });
        };
        GPGPUContext2.prototype.blockUntilAllProgramsCompleted = function() {
          var _this = this;
          this.throwIfDisposed();
          callAndCheck(this.gl, function() {
            return _this.gl.finish();
          });
        };
        GPGPUContext2.prototype.getQueryTimerExtension = function() {
          if (this.disjointQueryTimerExtension == null) {
            this.disjointQueryTimerExtension = getExtensionOrThrow(this.gl, tf.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2 ? "EXT_disjoint_timer_query_webgl2" : "EXT_disjoint_timer_query");
          }
          return this.disjointQueryTimerExtension;
        };
        GPGPUContext2.prototype.getQueryTimerExtensionWebGL2 = function() {
          return this.getQueryTimerExtension();
        };
        GPGPUContext2.prototype.getQueryTimerExtensionWebGL1 = function() {
          return this.getQueryTimerExtension();
        };
        GPGPUContext2.prototype.beginQuery = function() {
          if (tf.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2) {
            var gl2 = this.gl;
            var ext_2 = this.getQueryTimerExtensionWebGL2();
            var query_1 = gl2.createQuery();
            gl2.beginQuery(ext_2.TIME_ELAPSED_EXT, query_1);
            return query_1;
          }
          var ext = this.getQueryTimerExtensionWebGL1();
          var query = ext.createQueryEXT();
          ext.beginQueryEXT(ext.TIME_ELAPSED_EXT, query);
          return query;
        };
        GPGPUContext2.prototype.endQuery = function() {
          if (tf.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2) {
            var gl2 = this.gl;
            var ext_3 = this.getQueryTimerExtensionWebGL2();
            gl2.endQuery(ext_3.TIME_ELAPSED_EXT);
            return;
          }
          var ext = this.getQueryTimerExtensionWebGL1();
          ext.endQueryEXT(ext.TIME_ELAPSED_EXT);
        };
        GPGPUContext2.prototype.waitForQueryAndGetTime = function(query) {
          return __awaiter(this, void 0, void 0, function() {
            var _this = this;
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  return [4, tf.util.repeatedTry(function() {
                    return _this.disposed || // while testing contexts are created / disposed
                    // in rapid succession, so without this check we
                    // may poll for the query timer indefinitely
                    _this.isQueryAvailable(query, tf.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"));
                  })];
                case 1:
                  _a2.sent();
                  return [2, this.getQueryTime(query, tf.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))];
              }
            });
          });
        };
        GPGPUContext2.prototype.getQueryTime = function(query, queryTimerVersion) {
          if (queryTimerVersion === 0) {
            return null;
          }
          if (queryTimerVersion === 2) {
            var gl2 = this.gl;
            var timeElapsedNanos = gl2.getQueryParameter(query, gl2.QUERY_RESULT);
            return timeElapsedNanos / 1e6;
          } else {
            var ext = this.getQueryTimerExtensionWebGL1();
            var timeElapsedNanos = ext.getQueryObjectEXT(query, ext.QUERY_RESULT_EXT);
            return timeElapsedNanos / 1e6;
          }
        };
        GPGPUContext2.prototype.isQueryAvailable = function(query, queryTimerVersion) {
          if (queryTimerVersion === 0) {
            return true;
          }
          if (queryTimerVersion === 2) {
            var gl2 = this.gl;
            var ext = this.getQueryTimerExtensionWebGL2();
            var available = gl2.getQueryParameter(query, gl2.QUERY_RESULT_AVAILABLE);
            if (this.disjoint == null) {
              this.disjoint = this.gl.getParameter(ext.GPU_DISJOINT_EXT);
            }
            return available && !this.disjoint;
          } else {
            var ext = this.getQueryTimerExtensionWebGL1();
            var available = ext.getQueryObjectEXT(query, ext.QUERY_RESULT_AVAILABLE_EXT);
            if (this.disjoint == null) {
              this.disjoint = this.gl.getParameter(ext.GPU_DISJOINT_EXT);
            }
            return available && !this.disjoint;
          }
        };
        GPGPUContext2.prototype.pollFence = function(fenceContext) {
          var _this = this;
          return new Promise(function(resolve) {
            _this.addItemToPoll(function() {
              return fenceContext.isFencePassed();
            }, function() {
              return resolve();
            });
          });
        };
        GPGPUContext2.prototype.pollItems = function() {
          var index = linearSearchLastTrue(this.itemsToPoll.map(function(x) {
            return x.isDoneFn;
          }));
          for (var i = 0; i <= index; ++i) {
            var resolveFn = this.itemsToPoll[i].resolveFn;
            resolveFn();
          }
          this.itemsToPoll = this.itemsToPoll.slice(index + 1);
        };
        GPGPUContext2.prototype.addItemToPoll = function(isDoneFn, resolveFn) {
          var _this = this;
          this.itemsToPoll.push({ isDoneFn, resolveFn });
          if (this.itemsToPoll.length > 1) {
            return;
          }
          var scheduleFn = void 0;
          if ("setTimeoutCustom" in tf.env().platform) {
            scheduleFn = tf.env().platform.setTimeoutCustom.bind(tf.env().platform);
          }
          tf.util.repeatedTry(function() {
            _this.pollItems();
            return _this.itemsToPoll.length === 0;
          }, function() {
            return 0;
          }, null, scheduleFn);
        };
        GPGPUContext2.prototype.bindTextureToFrameBuffer = function(texture) {
          this.throwIfDisposed();
          bindColorTextureToFramebuffer(this.gl, texture, this.framebuffer);
          if (this.debug) {
            validateFramebuffer(this.gl);
          }
        };
        GPGPUContext2.prototype.unbindTextureToFrameBuffer = function() {
          if (this.outputTexture != null) {
            bindColorTextureToFramebuffer(this.gl, this.outputTexture, this.framebuffer);
            if (this.debug) {
              validateFramebuffer(this.gl);
            }
          } else {
            unbindColorTextureFromFramebuffer(this.gl, this.framebuffer);
          }
        };
        GPGPUContext2.prototype.downloadMatrixDriver = function(texture, downloadAndDecode) {
          this.bindTextureToFrameBuffer(texture);
          var result = downloadAndDecode();
          this.unbindTextureToFrameBuffer();
          return result;
        };
        GPGPUContext2.prototype.setOutputMatrixTextureDriver = function(outputMatrixTextureMaybePacked, width, height) {
          this.throwIfDisposed();
          var gl = this.gl;
          bindColorTextureToFramebuffer(gl, outputMatrixTextureMaybePacked, this.framebuffer);
          if (this.debug) {
            validateFramebuffer(gl);
          }
          this.outputTexture = outputMatrixTextureMaybePacked;
          callAndCheck(gl, function() {
            return gl.viewport(0, 0, width, height);
          });
          callAndCheck(gl, function() {
            return gl.scissor(0, 0, width, height);
          });
        };
        GPGPUContext2.prototype.setOutputMatrixWriteRegionDriver = function(x, y, width, height) {
          var _this = this;
          this.throwIfDisposed();
          callAndCheck(this.gl, function() {
            return _this.gl.scissor(x, y, width, height);
          });
        };
        GPGPUContext2.prototype.throwIfDisposed = function() {
          if (this.disposed) {
            throw new Error("Attempted to use disposed GPGPUContext.");
          }
        };
        GPGPUContext2.prototype.throwIfNoProgram = function() {
          if (this.program == null) {
            throw new Error("No GPU program is currently set.");
          }
        };
        return GPGPUContext2;
      }()
    );
    function linearSearchLastTrue(arr) {
      var i = 0;
      for (; i < arr.length; ++i) {
        var isDone = arr[i]();
        if (!isDone) {
          break;
        }
      }
      return i - 1;
    }
    function simpleAbsImpl(vals) {
      var resultValues = new Float32Array(vals.length);
      for (var i = 0; i < vals.length; ++i) {
        resultValues[i] = Math.abs(vals[i]);
      }
      return resultValues;
    }
    function createSimpleBinaryKernelImpl(op) {
      return function(aShape, bShape, aVals, bVals, dtype) {
        var newShape = tf.backend_util.assertAndGetBroadcastShape(aShape, bShape);
        var resultRank = newShape.length;
        var resultStrides = tf.util.computeStrides(newShape);
        var resultSize = tf.util.sizeFromShape(newShape);
        var result = tf.util.getTypedArrayFromDType(dtype, resultSize);
        var aRank = aShape.length;
        var bRank = bShape.length;
        var aStrides = tf.util.computeStrides(aShape);
        var bStrides = tf.util.computeStrides(bShape);
        var aBroadcastDims = tf.backend_util.getBroadcastDims(aShape, newShape);
        var bBroadcastDims = tf.backend_util.getBroadcastDims(bShape, newShape);
        if (aBroadcastDims.length + bBroadcastDims.length === 0) {
          for (var i = 0; i < result.length; ++i) {
            result[i] = op(aVals[i % aVals.length], bVals[i % bVals.length]);
          }
        } else {
          var _loop_1 = function(i2) {
            var loc = tf.util.indexToLoc(i2, resultRank, resultStrides);
            var aLoc = loc.slice(-aRank);
            aBroadcastDims.forEach(function(d) {
              return aLoc[d] = 0;
            });
            var aIndex = tf.util.locToIndex(aLoc, aRank, aStrides);
            var bLoc = loc.slice(-bRank);
            bBroadcastDims.forEach(function(d) {
              return bLoc[d] = 0;
            });
            var bIndex = tf.util.locToIndex(bLoc, bRank, bStrides);
            result[i2] = op(aVals[aIndex], bVals[bIndex]);
          };
          for (var i = 0; i < result.length; ++i) {
            _loop_1(i);
          }
        }
        return [result, newShape];
      };
    }
    function castImpl(values, shape, inputType, dtype) {
      if (dtype === "int32") {
        var resultValues = Int32Array.from(values);
        return [shape, "int32", resultValues];
      }
      if (dtype === "bool") {
        var zero = tf.util.toTypedArray([0], inputType);
        var _a2 = __read(createSimpleBinaryKernelImpl(function(a, b) {
          return a !== b ? 1 : 0;
        })(shape, [], values, zero, "bool"), 2), resultData = _a2[0], resultShape = _a2[1];
        return [resultShape, "bool", resultData];
      }
      throw new Error("Error in Cast: failed to cast ".concat(inputType, " to ").concat(dtype));
    }
    var addImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a + b;
    });
    function bincountImpl(xVals, weightsVals, weightsDtype, weightsShape, size) {
      var weightsSize = tf.util.sizeFromShape(weightsShape);
      var outVals = tf.util.makeZerosTypedArray(size, weightsDtype);
      for (var i = 0; i < xVals.length; i++) {
        var value = xVals[i];
        if (value < 0) {
          throw new Error("Input x must be non-negative!");
        }
        if (value >= size) {
          continue;
        }
        if (weightsSize > 0) {
          outVals[value] += weightsVals[i];
        } else {
          outVals[value] += 1;
        }
      }
      return outVals;
    }
    function bincountReduceImpl(xBuf, weightsBuf, size, binaryOutput) {
      if (binaryOutput === void 0) {
        binaryOutput = false;
      }
      var numRows = xBuf.shape[0];
      var numCols = xBuf.shape[1];
      var outBuf = tf.buffer([numRows, size], weightsBuf.dtype);
      for (var i = 0; i < numRows; i++) {
        for (var j = 0; j < numCols; j++) {
          var value = xBuf.get(i, j);
          if (value < 0) {
            throw new Error("Input x must be non-negative!");
          }
          if (value >= size) {
            continue;
          }
          if (binaryOutput) {
            outBuf.set(1, i, value);
          } else {
            if (weightsBuf.size > 0) {
              outBuf.set(outBuf.get(i, value) + weightsBuf.get(i, j), i, value);
            } else {
              outBuf.set(outBuf.get(i, value) + 1, i, value);
            }
          }
        }
      }
      return outBuf;
    }
    var bitwiseAndImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a & b;
    });
    function createSimpleUnaryImpl(op) {
      return function(values, dtype, attrs) {
        var newValues = tf.util.getArrayFromDType(dtype, values.length);
        for (var i = 0; i < values.length; ++i) {
          newValues[i] = op(values[i], attrs);
        }
        return newValues;
      };
    }
    var ceilImpl = createSimpleUnaryImpl(function(xi) {
      return Math.ceil(xi);
    });
    function concatImpl$1(inputs, outShape, dtype, simplyConcat) {
      var outVals = tf.util.getArrayFromDType(dtype, tf.util.sizeFromShape(outShape));
      if (simplyConcat && dtype !== "string") {
        var offset_1 = 0;
        inputs.forEach(function(input) {
          var size = tf.util.sizeFromShape(input.shape);
          outVals.set(input.vals, offset_1);
          offset_1 += size;
        });
      } else {
        var colOffset_1 = 0;
        inputs.forEach(function(input) {
          var decodedData = dtype === "string" ? tf.backend_util.fromUint8ToStringArray(input.vals) : input.vals;
          var tIdx = 0;
          for (var row = 0; row < input.shape[0]; ++row) {
            var resIdx = row * outShape[1] + colOffset_1;
            for (var col = 0; col < input.shape[1]; ++col) {
              outVals[resIdx + col] = decodedData[tIdx++];
            }
          }
          colOffset_1 += input.shape[1];
        });
      }
      return outVals;
    }
    var equalImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a === b ? 1 : 0;
    });
    var expImpl = createSimpleUnaryImpl(function(xi) {
      return Math.exp(xi);
    });
    var expm1Impl = createSimpleUnaryImpl(function(xi) {
      return Math.expm1(xi);
    });
    var floorImpl = createSimpleUnaryImpl(function(xi) {
      return Math.floor(xi);
    });
    function gatherNdImpl(indicesData, paramsBuf, dtype, numSlices, sliceRank, sliceSize, strides, paramsShape, paramsSize) {
      var outBuf = tf.buffer([numSlices, sliceSize], dtype);
      for (var i = 0; i < numSlices; i++) {
        var index = [];
        var flattenIndex = 0;
        for (var j = 0; j < sliceRank; j++) {
          var dim = indicesData[i * sliceRank + j];
          flattenIndex += dim * strides[j];
          index.push(dim);
        }
        if (flattenIndex < 0 || flattenIndex >= paramsSize / sliceSize) {
          throw new Error("Invalid indices: ".concat(index, " does not index into ").concat(paramsShape));
        }
        for (var k = 0; k < sliceSize; k++) {
          outBuf.values[i * sliceSize + k] = paramsBuf.get.apply(paramsBuf, __spreadArray([], __read(paramsBuf.indexToLoc(flattenIndex * sliceSize + k)), false));
        }
      }
      return outBuf;
    }
    function gatherV2Impl(xBuf, indicesBuf, flattenOutputShape) {
      var outBuf = tf.buffer(flattenOutputShape, xBuf.dtype);
      for (var i = 0; i < outBuf.size; ++i) {
        var newLoc = outBuf.indexToLoc(i);
        var originalLoc = newLoc.slice();
        var batchIdx = originalLoc[0];
        var indicesIdx = originalLoc[2];
        var indicesIndex = indicesBuf.locToIndex([batchIdx, indicesIdx]);
        originalLoc[2] = indicesBuf.values[indicesIndex];
        var originalIndex = xBuf.locToIndex(originalLoc);
        if (0 <= originalIndex && originalIndex < xBuf.values.length) {
          outBuf.values[i] = xBuf.values[originalIndex];
        }
      }
      return outBuf;
    }
    var greaterImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a > b ? 1 : 0;
    });
    var greaterEqualImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a >= b ? 1 : 0;
    });
    var lessImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a < b ? 1 : 0;
    });
    var lessEqualImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a <= b ? 1 : 0;
    });
    function linSpaceImpl(start, stop, num) {
      var step2 = (stop - start) / (num - 1);
      var values = tf.util.makeZerosTypedArray(num, "float32");
      values[0] = start;
      for (var i = 1; i < values.length; i++) {
        values[i] = values[i - 1] + step2;
      }
      return values;
    }
    var logImpl = createSimpleUnaryImpl(function(xi) {
      return Math.log(xi);
    });
    function maxImpl$1(aVals, reduceSize, outShape, dtype) {
      var vals = tf.util.getTypedArrayFromDType(dtype, tf.util.sizeFromShape(outShape));
      for (var i = 0; i < vals.length; ++i) {
        var offset = i * reduceSize;
        var max2 = aVals[offset];
        for (var j = 0; j < reduceSize; ++j) {
          var value = aVals[offset + j];
          if (Number.isNaN(value) || value > max2) {
            max2 = value;
          }
        }
        vals[i] = max2;
      }
      return vals;
    }
    var maximumImpl = createSimpleBinaryKernelImpl(function(aValue, bValue) {
      return Math.max(aValue, bValue);
    });
    var minimumImpl = createSimpleBinaryKernelImpl(function(aValue, bValue) {
      return Math.min(aValue, bValue);
    });
    var multiplyImpl = createSimpleBinaryKernelImpl(function(aValue, bValue) {
      return aValue * bValue;
    });
    function negImpl(xVals, xShape, xDtype) {
      var minusOne = tf.util.createScalarValue(-1, xDtype);
      return multiplyImpl([], xShape, minusOne, xVals, xDtype);
    }
    var notEqualImpl = createSimpleBinaryKernelImpl(function(a, b) {
      return a !== b ? 1 : 0;
    });
    function transposeImpl$1(xVals, xShape, dtype, perm, newShape) {
      var xRank = xShape.length;
      var xSize = tf.util.sizeFromShape(xShape);
      var xStrides = tf.util.computeStrides(xShape);
      var newStrides = tf.util.computeStrides(newShape);
      var result = tf.util.getTypedArrayFromDType(dtype, tf.util.sizeFromShape(newShape));
      for (var i = 0; i < xSize; ++i) {
        var loc = tf.util.indexToLoc(i, xRank, xStrides);
        var newLoc = new Array(loc.length);
        for (var i_1 = 0; i_1 < newLoc.length; i_1++) {
          newLoc[i_1] = loc[perm[i_1]];
        }
        var newIndex = tf.util.locToIndex(newLoc, xRank, newStrides);
        result[newIndex] = xVals[i];
      }
      return result;
    }
    function prodImpl(xShape, xDtype, xVals, reductionAxes) {
      var _a2 = __read(tf.backend_util.computeOutAndReduceShapes(xShape, reductionAxes), 2), outShape = _a2[0], reduceShape = _a2[1];
      var outDtype = tf.upcastType(xDtype, "int32");
      var outVals = tf.util.makeZerosTypedArray(tf.util.sizeFromShape(outShape), outDtype);
      var reduceSize = tf.util.sizeFromShape(reduceShape);
      for (var i = 0; i < outVals.length; ++i) {
        var offset = i * reduceSize;
        var prod_1 = 1;
        for (var j = 0; j < reduceSize; ++j) {
          prod_1 *= xVals[offset + j];
        }
        outVals[i] = prod_1;
      }
      return { outVals, outShape, outDtype };
    }
    function validateIndices(indices, indicesShape, numParams) {
      indices.forEach(function(index, i) {
        if (index < 0 || index >= numParams) {
          var locString = tf.util.indexToLoc(i, indicesShape.length, tf.util.computeStrides(indicesShape)).join(",");
          throw new Error("indices[".concat(locString, "] = ").concat(index, " is not in [0, ").concat(numParams, ")"));
        }
      });
    }
    function validateSplits(paramsNestedSplits, numParamsDenseValues) {
      for (var dim = 0; dim < paramsNestedSplits.length; ++dim) {
        var splits = paramsNestedSplits[dim];
        var lastSplit = dim === paramsNestedSplits.length - 1 ? numParamsDenseValues : paramsNestedSplits[dim + 1].length;
        if (splits.length === 0) {
          throw new Error("Ragged splits may not be empty");
        }
        if (splits[0] < 0) {
          throw new Error("Ragged splits must be non-negative");
        }
        if (splits[splits.length - 1] > lastSplit) {
          throw new Error("Ragged splits must not point past values");
        }
        for (var i = 1; i < splits.length; ++i) {
          if (splits[i - 1] > splits[i]) {
            throw new Error("Ragged splits must be sorted in ascending order");
          }
        }
      }
    }
    function makeSplits(indices, indicesShape, paramsNestedSplits, numParamsDenseValues) {
      var valueSlices = [];
      var numValues = 0;
      var numSplits = indicesShape.length - 1 + paramsNestedSplits.length;
      var outSplits = new Array(numSplits).fill(null).map(function() {
        return [0];
      });
      validateSplits(paramsNestedSplits, numParamsDenseValues);
      var nrows = 1;
      for (var dim = 0; dim < indicesShape.length - 1; ++dim) {
        nrows *= indicesShape[dim];
        var rowLength = indicesShape[dim + 1];
        for (var i = 1; i < nrows + 1; ++i) {
          outSplits[dim].push(i * rowLength);
        }
      }
      for (var i = 0; i < indices.length; ++i) {
        var start = indices[i];
        var limit = indices[i] + 1;
        for (var dim = 0; dim < paramsNestedSplits.length; ++dim) {
          var splits = paramsNestedSplits[dim];
          var outDim = dim + indicesShape.length - 1;
          if (outDim >= 0) {
            var outSplitsOutDim = outSplits[outDim];
            var delta = outSplitsOutDim[outSplitsOutDim.length - 1] - splits[start];
            for (var j = start; j < limit; ++j) {
              outSplits[outDim].push(splits[j + 1] + delta);
            }
          }
          start = splits[start];
          limit = splits[limit];
        }
        if (limit !== start) {
          valueSlices.push([start, limit]);
          numValues += limit - start;
        }
      }
      return { outSplits, valueSlices, numValues };
    }
    function getSplits(outSplits) {
      var splitsOut = [];
      var _loop_1 = function(i2) {
        var numSplits = outSplits[i2].length;
        var splits = tf.util.getArrayFromDType("int32", numSplits);
        splitsOut.push(splits);
        outSplits[i2].forEach(function(value, j) {
          return splits[j] = value;
        });
      };
      for (var i = 0; i < outSplits.length; ++i) {
        _loop_1(i);
      }
      return splitsOut;
    }
    function computeFlatOuterDims(orig, numOutDims) {
      var outDims = orig.slice(0, numOutDims);
      while (outDims.length < numOutDims) {
        outDims.push(1);
      }
      for (var inDim = numOutDims; inDim < orig.length; inDim++) {
        outDims[numOutDims - 1] *= orig[inDim];
      }
      return outDims;
    }
    function writeValueSlices(paramsDenseValues, paramsDenseValuesShape, valueSlices, valueSize, values, valuesShape) {
      var e_12, _a2;
      var denseM = computeFlatOuterDims(paramsDenseValuesShape, 2)[1];
      var valuesM = computeFlatOuterDims(valuesShape, 2)[1];
      var outPos = 0;
      try {
        for (var valueSlices_1 = __values(valueSlices), valueSlices_1_1 = valueSlices_1.next(); !valueSlices_1_1.done; valueSlices_1_1 = valueSlices_1.next()) {
          var slice2 = valueSlices_1_1.value;
          for (var i = slice2[0]; i < slice2[1]; ++i) {
            for (var j = 0; j < valueSize; ++j) {
              values[outPos * valuesM + j] = paramsDenseValues[i * denseM + j];
            }
            ++outPos;
          }
        }
      } catch (e_1_1) {
        e_12 = { error: e_1_1 };
      } finally {
        try {
          if (valueSlices_1_1 && !valueSlices_1_1.done && (_a2 = valueSlices_1.return)) _a2.call(valueSlices_1);
        } finally {
          if (e_12) throw e_12.error;
        }
      }
    }
    function getValues(paramsDenseValues, paramsDenseValuesShape, paramsDenseValuesDType, valueSlices, numValues) {
      var valuesShape = paramsDenseValuesShape.slice();
      valuesShape[0] = numValues;
      var valuesOut = tf.util.getArrayFromDType(paramsDenseValuesDType, tf.util.sizeFromShape(valuesShape));
      var numElements = paramsDenseValues.length;
      var valueSize = numElements === 0 ? 0 : numElements / paramsDenseValuesShape[0];
      writeValueSlices(paramsDenseValues, paramsDenseValuesShape, valueSlices, valueSize, valuesOut, valuesShape);
      return [valuesOut, valuesShape];
    }
    function raggedGatherImpl(paramsNestedSplits, paramsNestedSplitsShapes, paramsDenseValues, paramsDenseValuesShape, paramsDenseValuesDType, indices, indicesShape, outputRaggedRank) {
      if (paramsNestedSplits.length === 0) {
        throw new Error("paramsNestedSplits must be non empty");
      }
      if (paramsNestedSplitsShapes[0].length === 0) {
        throw new Error("Split tensors must not be scalars");
      }
      var numParams = paramsNestedSplitsShapes[0][0] - 1;
      validateIndices(indices, indicesShape, numParams);
      if (paramsDenseValuesShape.length === 0) {
        throw new Error("params.rank must be nonzero");
      }
      var numParamsDenseValues = paramsDenseValuesShape[0];
      var _a2 = makeSplits(indices, indicesShape, paramsNestedSplits, numParamsDenseValues), outSplits = _a2.outSplits, valueSlices = _a2.valueSlices, numValues = _a2.numValues;
      var outputNestedSplits = getSplits(outSplits);
      var outputDenseValues = getValues(paramsDenseValues, paramsDenseValuesShape, paramsDenseValuesDType, valueSlices, numValues);
      return [outputNestedSplits, outputDenseValues[0], outputDenseValues[1]];
    }
    var INT32_MAX = 2147483647;
    function raggedRangeImpl(starts, startsShape, startsDType, limits, limitsShape, deltas, deltasShape) {
      if (startsShape.length > 1) {
        throw new Error("starts must be a scalar or vector");
      }
      if (limitsShape.length > 1) {
        throw new Error("limits must be a scalar or vector");
      }
      if (deltasShape.length > 1) {
        throw new Error("deltas must be a scalar or vector");
      }
      var broadcastStarts = startsShape.length === 0;
      var broadcastLimits = limitsShape.length === 0;
      var broadcastDeltas = deltasShape.length === 0;
      var inSizes = [];
      if (!broadcastStarts) {
        inSizes.push(startsShape[0]);
      }
      if (!broadcastLimits) {
        inSizes.push(limitsShape[0]);
      }
      if (!broadcastDeltas) {
        inSizes.push(deltasShape[0]);
      }
      for (var i = 1; i < inSizes.length; ++i) {
        if (inSizes[i] !== inSizes[i - 1]) {
          throw new Error("starts, limits, and deltas must have the same shape");
        }
      }
      var nRows = inSizes.length === 0 ? 1 : inSizes[0];
      var rtNestedSplits = tf.util.getArrayFromDType("int32", nRows + 1);
      rtNestedSplits[0] = 0;
      for (var row = 0; row < nRows; ++row) {
        var start = broadcastStarts ? starts[0] : starts[row];
        var limit = broadcastLimits ? limits[0] : limits[row];
        var delta = broadcastDeltas ? deltas[0] : deltas[row];
        if (delta === 0) {
          throw new Error("Requires delta != 0");
        }
        var size = (
          // The number of elements in the specified range.
          void 0
        );
        if (delta > 0 && limit < start || delta < 0 && limit > start) {
          size = 0;
        } else {
          size = Math.ceil(Math.abs((limit - start) / delta));
          if (size > INT32_MAX) {
            throw new Error("Requires ((limit - start) / delta) <= ".concat(INT32_MAX));
          }
        }
        rtNestedSplits[row + 1] = rtNestedSplits[row] + size;
      }
      var nVals = rtNestedSplits[nRows];
      var rtDenseValues = tf.util.getArrayFromDType(startsDType, nVals);
      var valueIndex = 0;
      for (var row = 0; row < nRows; ++row) {
        var rowSize = rtNestedSplits[row + 1] - rtNestedSplits[row];
        var value = broadcastStarts ? starts[0] : starts[row];
        var delta = broadcastDeltas ? deltas[0] : deltas[row];
        for (var i = 0; i < rowSize; ++i) {
          rtDenseValues[valueIndex++] = value;
          value += delta;
        }
      }
      return [rtNestedSplits, rtDenseValues];
    }
    var RowPartitionType = tf.backend_util.RowPartitionType;
    var RaggedTensorToTensorOp = (
      /** @class */
      function() {
        function RaggedTensorToTensorOp2(shape, shapeShape, values, valuesShape, valuesDType, defaultValue, defaultValueShape, rowPartitionValues, rowPartitionValuesShapes, rowPartitionTypeStrings) {
          this.shape = shape;
          this.shapeShape = shapeShape;
          this.values = values;
          this.valuesShape = valuesShape;
          this.valuesDType = valuesDType;
          this.defaultValue = defaultValue;
          this.defaultValueShape = defaultValueShape;
          this.rowPartitionValues = rowPartitionValues;
          this.rowPartitionValuesShapes = rowPartitionValuesShapes;
          this.rowPartitionTypes = tf.backend_util.getRowPartitionTypesHelper(rowPartitionTypeStrings);
          this.raggedRank = tf.backend_util.getRaggedRank(this.rowPartitionTypes);
        }
        RaggedTensorToTensorOp2.prototype.getRowPartitionTypeByDimension = function(dimension) {
          if (this.rowPartitionTypes[0] === RowPartitionType.FIRST_DIM_SIZE) {
            return this.rowPartitionTypes[dimension + 1];
          } else {
            return this.rowPartitionTypes[dimension];
          }
        };
        RaggedTensorToTensorOp2.prototype.getRowPartitionTensor = function(dimension) {
          if (this.rowPartitionTypes[0] === RowPartitionType.FIRST_DIM_SIZE) {
            return this.rowPartitionValues[dimension + 1];
          } else {
            return this.rowPartitionValues[dimension];
          }
        };
        RaggedTensorToTensorOp2.prototype.getMaxWidth = function(dimension) {
          var rowPartitionTensor = this.getRowPartitionTensor(dimension - 1);
          switch (this.getRowPartitionTypeByDimension(dimension - 1)) {
            case RowPartitionType.VALUE_ROWIDS:
              return RaggedTensorToTensorOp2.getMaxWidthValueRowID(rowPartitionTensor);
            case RowPartitionType.ROW_SPLITS:
              return RaggedTensorToTensorOp2.getMaxWidthRowSplit(rowPartitionTensor);
            default:
              throw new Error("Cannot handle partition type ".concat(RowPartitionType[this.getRowPartitionTypeByDimension(dimension - 1)]));
          }
        };
        RaggedTensorToTensorOp2.getMaxWidthRowSplit = function(rowSplit) {
          var tensorLength = rowSplit.length;
          if (tensorLength === 0 || tensorLength === 1) {
            return 0;
          }
          var maxWidth = 0;
          for (var i = 0; i < tensorLength - 1; ++i) {
            var currentWidth = rowSplit[i + 1] - rowSplit[i];
            if (currentWidth > maxWidth) {
              maxWidth = currentWidth;
            }
          }
          return maxWidth;
        };
        RaggedTensorToTensorOp2.getMaxWidthValueRowID = function(valueRowIds) {
          var indexLength = valueRowIds.length;
          if (indexLength === 0) {
            return 0;
          }
          var firstEqualIndex = 0;
          var firstEqualIndexValue = valueRowIds[0];
          var maxWidth = 0;
          for (var i = 1; i < indexLength; ++i) {
            var value = valueRowIds[i];
            if (value !== firstEqualIndexValue) {
              firstEqualIndexValue = value;
              maxWidth = Math.max(i - firstEqualIndex, maxWidth);
              firstEqualIndex = i;
            }
          }
          return Math.max(indexLength - firstEqualIndex, maxWidth);
        };
        RaggedTensorToTensorOp2.prototype.tensorShapeFromTensor = function(t, tShape, isPartial) {
          if (isPartial === void 0) {
            isPartial = true;
          }
          if (tShape.length === 0) {
            if (t[0] === -1) {
              return [];
            }
            throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.");
          }
          return makeShape(t, isPartial);
        };
        RaggedTensorToTensorOp2.prototype.calculateOutputSize = function(firstDim) {
          var valueShape = this.valuesShape;
          var defaultValueShape = this.defaultValueShape;
          tf.backend_util.validateDefaultValueShape(defaultValueShape, valueShape);
          var shape = this.tensorShapeFromTensor(this.shape, this.shapeShape);
          var outputShape = tf.backend_util.combineRaggedTensorToTensorShapes(this.raggedRank, shape, valueShape);
          var result = outputShape;
          if (result[0] < 0) {
            result[0] = firstDim;
          }
          for (var i = 1; i <= this.raggedRank; ++i) {
            if (result[i] < 0) {
              result[i] = this.getMaxWidth(i);
            }
          }
          return result;
        };
        RaggedTensorToTensorOp2.prototype.calculateFirstParentOutputIndex = function(firstDimension, outputIndexMultiplier, firstDimensionOutput) {
          var minDimension = Math.min(firstDimension, firstDimensionOutput);
          var result = [];
          var currentOutputIndex = 0;
          for (var i = 0; i < minDimension; ++i, currentOutputIndex += outputIndexMultiplier) {
            result.push(currentOutputIndex);
          }
          for (var i = minDimension; i < firstDimension; ++i) {
            result.push(-1);
          }
          tf.util.assert(result.length === firstDimension, function() {
            return "Final length of result must be equal to firstDimension.";
          });
          return result;
        };
        RaggedTensorToTensorOp2.prototype.calculateOutputIndexRowSplit = function(rowSplit, parentOutputIndex, outputIndexMultiplier, outputSize) {
          var rowSplitSize = rowSplit.length;
          var result = [];
          for (var i = 0; i < rowSplitSize - 1; ++i) {
            var rowLength = rowSplit[i + 1] - rowSplit[i];
            var realLength = Math.min(outputSize, rowLength);
            var parentOutputIndexCurrent = parentOutputIndex[i];
            if (parentOutputIndexCurrent === -1) {
              realLength = 0;
            }
            for (var j = 0; j < realLength; ++j) {
              result.push(parentOutputIndexCurrent);
              parentOutputIndexCurrent += outputIndexMultiplier;
            }
            for (var j = 0; j < rowLength - realLength; ++j) {
              result.push(-1);
            }
          }
          if (rowSplitSize > 0 && result.length !== rowSplit[rowSplitSize - 1]) {
            throw new Error("Invalid row split size.");
          }
          return result;
        };
        RaggedTensorToTensorOp2.prototype.calculateOutputIndexValueRowID = function(valueRowIds, parentOutputIndex, outputIndexMultiplier, outputSize) {
          var indexSize = valueRowIds.length;
          var result = [];
          if (indexSize === 0) {
            return [];
          }
          var currentOutputColumn = 0;
          var currentValueRowId = valueRowIds[0];
          if (currentValueRowId >= parentOutputIndex.length) {
            throw new Error("Got currentValueRowId=".concat(currentValueRowId, ", which is not less than ").concat(parentOutputIndex.length));
          }
          var currentOutputIndex = parentOutputIndex[currentValueRowId];
          result.push(currentOutputIndex);
          for (var i = 1; i < indexSize; ++i) {
            var nextValueRowId = valueRowIds[i];
            if (nextValueRowId === currentValueRowId) {
              if (currentOutputIndex >= 0) {
                ++currentOutputColumn;
                if (currentOutputColumn < outputSize) {
                  currentOutputIndex += outputIndexMultiplier;
                } else {
                  currentOutputIndex = -1;
                }
              }
            } else {
              currentOutputColumn = 0;
              currentValueRowId = nextValueRowId;
              if (nextValueRowId >= parentOutputIndex.length) {
                throw new Error("Got nextValueRowId=".concat(nextValueRowId, " which is not less than ").concat(parentOutputIndex.length));
              }
              currentOutputIndex = parentOutputIndex[nextValueRowId];
            }
            result.push(currentOutputIndex);
          }
          if (result.length !== valueRowIds.length) {
            throw new Error("Invalid row ids.");
          }
          return result;
        };
        RaggedTensorToTensorOp2.prototype.calculateOutputIndex = function(dimension, parentOutputIndex, outputIndexMultiplier, outputSize) {
          var rowPartitionTensor = this.getRowPartitionTensor(dimension);
          var partitionType = this.getRowPartitionTypeByDimension(dimension);
          switch (partitionType) {
            case RowPartitionType.VALUE_ROWIDS:
              return this.calculateOutputIndexValueRowID(rowPartitionTensor, parentOutputIndex, outputIndexMultiplier, outputSize);
            case RowPartitionType.ROW_SPLITS:
              if (rowPartitionTensor.length - 1 > parentOutputIndex.length) {
                throw new Error("Row partition size is greater than output size: ".concat(rowPartitionTensor.length - 1, " > ").concat(parentOutputIndex.length));
              }
              return this.calculateOutputIndexRowSplit(rowPartitionTensor, parentOutputIndex, outputIndexMultiplier, outputSize);
            default:
              throw new Error("Unsupported partition type: ".concat(RowPartitionType[partitionType]));
          }
        };
        RaggedTensorToTensorOp2.prototype.getFirstDimensionSize = function() {
          var firstPartitionTensor = this.rowPartitionValues[0];
          if (this.rowPartitionTypes.length === 0) {
            throw new Error("No row_partition_types given.");
          }
          var firstPartitionType = this.rowPartitionTypes[0];
          switch (firstPartitionType) {
            case RowPartitionType.FIRST_DIM_SIZE:
              return firstPartitionTensor[0];
            case RowPartitionType.VALUE_ROWIDS:
              throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");
            case RowPartitionType.ROW_SPLITS:
              return this.rowPartitionValuesShapes[0][0] - 1;
            default:
              throw new Error("Cannot handle type ".concat(RowPartitionType[firstPartitionType]));
          }
        };
        RaggedTensorToTensorOp2.prototype.compute = function() {
          var firstPartitionTensor = this.rowPartitionValues[0];
          if (firstPartitionTensor.length <= 0) {
            throw new Error("Invalid first partition input. Tensor requires at least one element.");
          }
          var firstDimension = this.getFirstDimensionSize();
          var outputSize = this.calculateOutputSize(firstDimension);
          var multiplier = new Array(this.raggedRank + 1);
          multiplier[multiplier.length - 1] = 1;
          for (var i = multiplier.length - 2; i >= 0; --i) {
            multiplier[i] = multiplier[i + 1] * outputSize[i + 1];
          }
          var outputShape = makeShape(outputSize, false);
          var outputTensor = tf.util.getArrayFromDType(this.valuesDType, tf.util.sizeFromShape(outputShape));
          var fullSize = multiplier[0] * outputSize[0];
          if (fullSize > 0) {
            var outputIndex = this.calculateFirstParentOutputIndex(firstDimension, multiplier[0], outputSize[0]);
            for (var i = 1; i <= this.raggedRank; ++i) {
              var newOutputIndex = this.calculateOutputIndex(i - 1, outputIndex, multiplier[i], outputSize[i]);
              outputIndex = newOutputIndex;
            }
            this.setOutput(this.raggedRank, outputIndex, outputTensor, outputShape);
          }
          return [outputShape, outputTensor];
        };
        RaggedTensorToTensorOp2.prototype.setOutput = function(raggedRank, outputIndex, outputTensor, outputShape) {
          if (outputTensor.length === 0) {
            return;
          }
          var valuesBase = this.values;
          var outputBase = outputTensor;
          var elementShape = outputShape.slice();
          elementShape = elementShape.slice(raggedRank + 1);
          var valueElementSize = tf.util.sizeFromShape(elementShape);
          var outputIndexSize = outputIndex.length;
          var defaultValue = this.defaultValue;
          if (defaultValue.length !== valueElementSize && defaultValue.length !== 1) {
            var srcShape_1 = this.defaultValueShape;
            tf.tidy(function() {
              var defaultValueTensor = tf.reshape(defaultValue, srcShape_1);
              var bCastDefault = tf.broadcastTo(defaultValueTensor, elementShape);
              defaultValue = bCastDefault.dataSync();
            });
          }
          var srcStart = 0;
          var dstStart = 0;
          var dstEnd = 0;
          for (var srcI = 0; srcI <= outputIndexSize; ++srcI) {
            var dstI = srcI < outputIndexSize ? outputIndex[srcI] : -1;
            if (dstI === dstEnd) {
              ++dstEnd;
              continue;
            }
            if (dstStart < dstEnd) {
              var src = valuesBase.subarray(srcStart * valueElementSize);
              var dst = outputBase.subarray(dstStart * valueElementSize);
              var nVals = (dstEnd - dstStart) * valueElementSize;
              copyArray(dst, src, nVals);
            }
            if (srcI >= outputIndexSize) {
              var outputSize = outputTensor.length;
              dstI = Math.floor(outputSize / valueElementSize);
            }
            if (dstI > dstEnd) {
              if (this.defaultValue.length === 1) {
                outputBase.subarray(dstEnd * valueElementSize, dstI * valueElementSize).fill(this.defaultValue[0]);
                dstEnd = dstI;
              } else {
                while (dstI > dstEnd) {
                  var dst = outputBase.slice(dstEnd * valueElementSize);
                  copyArray(dst, defaultValue, valueElementSize);
                  ++dstEnd;
                }
              }
            }
            if (dstI < 0) {
              srcStart = srcI + 1;
              dstStart = dstEnd;
            } else {
              srcStart = srcI;
              dstStart = dstEnd;
              dstEnd = dstStart + 1;
            }
          }
        };
        return RaggedTensorToTensorOp2;
      }()
    );
    function copyArray(dst, src, size) {
      for (var i = 0; i < size; i++) {
        dst[i] = src[i];
      }
    }
    function makeShape(shape, isPartial) {
      var e_12, _a2;
      var out = [];
      try {
        for (var shape_1 = __values(shape), shape_1_1 = shape_1.next(); !shape_1_1.done; shape_1_1 = shape_1.next()) {
          var dim = shape_1_1.value;
          if (dim < 0) {
            if (!isPartial) {
              throw new Error("Dimension ".concat(dim, " must be >= 0"));
            }
            if (dim < -1) {
              throw new Error("Dimension ".concat(dim, " must be >= -1"));
            }
            dim = -1;
          }
          out.push(dim);
        }
      } catch (e_1_1) {
        e_12 = { error: e_1_1 };
      } finally {
        try {
          if (shape_1_1 && !shape_1_1.done && (_a2 = shape_1.return)) _a2.call(shape_1);
        } finally {
          if (e_12) throw e_12.error;
        }
      }
      return out;
    }
    function raggedTensorToTensorImpl(shape, shapesShape, values, valuesShape, valuesDType, defaultValue, defaultValueShape, rowPartitionValues, rowPartitionValuesShapes, rowPartitionTypes) {
      return new RaggedTensorToTensorOp(shape, shapesShape, values, valuesShape, valuesDType, defaultValue, defaultValueShape, rowPartitionValues, rowPartitionValuesShapes, rowPartitionTypes).compute();
    }
    function rangeImpl(start, stop, step2, dtype) {
      var sameStartStop = start === stop;
      var increasingRangeNegativeStep = start < stop && step2 < 0;
      var decreasingRangePositiveStep = stop < start && step2 > 1;
      if (sameStartStop || increasingRangeNegativeStep || decreasingRangePositiveStep) {
        return tf.util.makeZerosTypedArray(0, dtype);
      }
      var numElements = Math.abs(Math.ceil((stop - start) / step2));
      var values = tf.util.makeZerosTypedArray(numElements, dtype);
      if (stop < start && step2 === 1) {
        step2 = -1;
      }
      values[0] = start;
      for (var i = 1; i < values.length; i++) {
        values[i] = values[i - 1] + step2;
      }
      return values;
    }
    var rsqrtImpl = createSimpleUnaryImpl(function(xi) {
      return 1 / Math.sqrt(xi);
    });
    function scatterImpl(indices, updates, shape, outputSize, sliceSize, numUpdates, sliceRank, strides, defaultValue, sumDupeIndices) {
      var flattenShape = [outputSize / sliceSize, sliceSize];
      var indicesData = indices.values;
      var updatesData = updates.values;
      if (outputSize === 0) {
        return tf.buffer(shape, updates.dtype);
      }
      var outBuf = defaultValue instanceof tf.TensorBuffer ? defaultValue : tf.buffer(flattenShape, updates.dtype);
      if (typeof defaultValue === "string") {
        outBuf.values.fill(defaultValue);
      } else if (typeof defaultValue === "number") {
        outBuf.values.fill(defaultValue);
      } else if (typeof defaultValue === "boolean") {
        outBuf.values.fill(+defaultValue);
      }
      for (var i = 0; i < numUpdates; i++) {
        var index = [];
        var flattenIndex = 0;
        for (var j = 0; j < sliceRank; j++) {
          var dim = indicesData[i * sliceRank + j];
          index.push(dim);
          flattenIndex += dim * strides[j];
        }
        if (flattenIndex < 0 || flattenIndex >= outputSize / sliceSize) {
          throw new Error("Invalid indices: ".concat(index, " does not index into ").concat(shape));
        }
        for (var k = 0; k < sliceSize; k++) {
          if (sumDupeIndices) {
            outBuf.values[flattenIndex * sliceSize + k] += updatesData[i * sliceSize + k];
          } else {
            outBuf.values[flattenIndex * sliceSize + k] = updates.rank === 0 ? updatesData[0] : updatesData[i * sliceSize + k];
          }
        }
      }
      return outBuf;
    }
    var sigmoidImpl = createSimpleUnaryImpl(function(xi) {
      return 1 / (1 + Math.exp(-xi));
    });
    function sliceImpl(vals, begin, size, shape, dtype) {
      var isContinous = tf.slice_util.isSliceContinous(shape, begin, size);
      var length = tf.util.sizeFromShape(size);
      var xStrides = tf.util.computeStrides(shape);
      if (isContinous) {
        var flatOffset = tf.slice_util.computeFlatOffset(begin, xStrides);
        if (dtype === "string") {
          return vals.slice(flatOffset, flatOffset + length);
        }
        return vals.subarray(flatOffset, flatOffset + length);
      }
      var decodedData = dtype === "string" ? tf.backend_util.fromUint8ToStringArray(vals) : vals;
      var inBuf = tf.buffer(shape, dtype, decodedData);
      var outBuf = tf.buffer(size, dtype);
      for (var i = 0; i < outBuf.size; ++i) {
        var outLoc = outBuf.indexToLoc(i);
        var inLoc = outLoc.map(function(idx, j) {
          return idx + begin[j];
        });
        outBuf.set.apply(outBuf, __spreadArray([inBuf.get.apply(inBuf, __spreadArray([], __read(inLoc), false))], __read(outLoc), false));
      }
      if (dtype === "string") {
        return tf.backend_util.fromStringArrayToUint8(outBuf.values);
      }
      return outBuf.values;
    }
    function sparseFillEmptyRowsImpl(indices, indicesShape, indicesDType, values, valuesDType, denseShape, defaultValue) {
      var indicesCount = indicesShape[0];
      var denseRows = denseShape[0];
      var emptyRowIndicator = new Array(denseRows);
      var reverseIndexMap = new Array(indicesCount);
      var rank = indicesShape[1];
      if (denseRows === 0) {
        if (indicesCount !== 0) {
          throw new Error(tf.backend_util.getSparseFillEmptyRowsIndicesDenseShapeMismatch(indicesCount));
        }
        var outputIndices = tf.util.getArrayFromDType(indicesDType, 0);
        var outputValues = tf.util.getArrayFromDType(valuesDType, 0);
        return [
          outputIndices,
          [0, rank],
          outputValues,
          emptyRowIndicator,
          reverseIndexMap
        ];
      }
      var rowsAreOrdered = true;
      var lastIndicesRow = 0;
      var csrOffset = new Array(denseRows).fill(0);
      for (var i = 0; i < indicesCount; ++i) {
        var row = indices[i * rank];
        if (row < 0) {
          throw new Error(tf.backend_util.getSparseFillEmptyRowsNegativeIndexErrorMessage(i, row));
        }
        if (row >= denseRows) {
          throw new Error(tf.backend_util.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(i, row, denseRows));
        }
        ++csrOffset[row];
        rowsAreOrdered = rowsAreOrdered && row >= lastIndicesRow;
        lastIndicesRow = row;
      }
      var allRowsFull = true;
      for (var row = 0; row < denseRows; ++row) {
        var rowEmpty = csrOffset[row] === 0;
        emptyRowIndicator[row] = rowEmpty;
        allRowsFull = allRowsFull && !rowEmpty;
        csrOffset[row] = Math.max(csrOffset[row], 1);
        if (row > 0) {
          csrOffset[row] += csrOffset[row - 1];
        }
      }
      if (allRowsFull && rowsAreOrdered) {
        var outputIndices = indices;
        var outputValues = values;
        for (var i = 0; i < indicesCount; ++i) {
          reverseIndexMap[i] = i;
        }
        return [
          outputIndices,
          [indicesCount, rank],
          outputValues,
          emptyRowIndicator,
          reverseIndexMap
        ];
      } else {
        var fullIndicesCount = csrOffset[denseRows - 1];
        var outputIndices = tf.util.getArrayFromDType(indicesDType, fullIndicesCount * rank);
        var outputValues = tf.util.getArrayFromDType(valuesDType, fullIndicesCount);
        var filledCount = new Array(denseRows).fill(0);
        for (var i = 0; i < indicesCount; ++i) {
          var row = indices[i * rank];
          var offset = filledCount[row];
          var outputI = (row === 0 ? 0 : csrOffset[row - 1]) + offset;
          filledCount[row]++;
          for (var j = 0; j < rank; ++j) {
            outputIndices[outputI * rank + j] = indices[i * rank + j];
          }
          outputValues[outputI] = values[i];
          reverseIndexMap[i] = outputI;
        }
        for (var row = 0; row < denseRows; ++row) {
          var rowCount = filledCount[row];
          if (rowCount === 0) {
            var startingIndex = row === 0 ? 0 : csrOffset[row - 1];
            outputIndices[startingIndex * rank + 0] = row;
            for (var col = 1; col < rank; ++col) {
              outputIndices[startingIndex * rank + col] = 0;
            }
            outputValues[startingIndex] = defaultValue;
          }
        }
        return [
          outputIndices,
          [fullIndicesCount, rank],
          outputValues,
          emptyRowIndicator,
          reverseIndexMap
        ];
      }
    }
    function sparseReshapeImpl(inputIndices, inputIndicesShape, inputDType, inputShape, targetShape) {
      var denseSize = tf.util.sizeFromShape(inputShape);
      var nnz = inputIndicesShape[0];
      var outputRank = targetShape.length;
      var outputShape = [];
      var product = 1;
      var unknownIndex = -1;
      for (var d = 0; d < outputRank; ++d) {
        var size = targetShape[d];
        if (size === -1) {
          if (unknownIndex !== -1) {
            throw new Error(tf.backend_util.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(unknownIndex, d));
          }
          unknownIndex = d;
          outputShape.push(1);
        } else {
          if (size < 0) {
            throw new Error(tf.backend_util.getSparseReshapeNegativeOutputDimErrorMessage(d, size));
          }
          product *= size;
          outputShape.push(size);
        }
      }
      if (unknownIndex !== -1) {
        if (product <= 0) {
          throw new Error(tf.backend_util.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());
        }
        var missing = Math.trunc(denseSize / product);
        if (product * missing !== denseSize) {
          throw new Error(tf.backend_util.getSparseReshapeInputOutputMultipleErrorMessage(inputShape, outputShape));
        }
        outputShape[unknownIndex] = missing;
      }
      var outputSize = tf.util.sizeFromShape(outputShape);
      if (outputSize !== denseSize) {
        throw new Error(tf.backend_util.getSparseReshapeInputOutputMismatchErrorMessage(inputShape, outputShape));
      }
      var inputRank = inputShape.length;
      var inputStrides = [];
      if (inputRank > 0) {
        inputStrides[inputRank - 1] = 1;
        for (var d = inputRank - 2; d >= 0; --d) {
          inputStrides[d] = inputStrides[d + 1] * inputShape[d + 1];
        }
      }
      var outputStrides = [];
      if (outputRank > 0) {
        outputStrides[outputRank - 1] = 1;
        for (var d = outputRank - 2; d >= 0; --d) {
          outputStrides[d] = outputStrides[d + 1] * outputShape[d + 1];
        }
      }
      var newIndices = tf.util.getArrayFromDType(inputDType, nnz * outputRank);
      for (var i = 0; i < nnz; ++i) {
        var id = 0;
        for (var j = 0; j < inputRank; ++j) {
          id += inputIndices[i * inputRank + j] * inputStrides[j];
        }
        for (var j = 0; j < outputRank; ++j) {
          newIndices[i * outputRank + j] = Math.trunc(id / outputStrides[j]);
          id %= outputStrides[j];
        }
      }
      return [newIndices, [nnz, outputRank], outputShape];
    }
    function sparseSegmentReductionImpl(input, inputShape, inputDType, indices, segmentIds, isMean, defaultValue) {
      if (isMean === void 0) {
        isMean = false;
      }
      if (defaultValue === void 0) {
        defaultValue = 0;
      }
      var numIndices = indices.length;
      var inputFlat = [inputShape[0], input.length / inputShape[0]];
      var numCol = inputFlat[1];
      var lastSegmentIdPlusOne = numIndices > 0 ? segmentIds[numIndices - 1] + 1 : 0;
      var outputRows = lastSegmentIdPlusOne;
      if (outputRows < 0) {
        throw new Error(tf.backend_util.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());
      }
      var outputShape = inputShape.slice();
      outputShape[0] = outputRows;
      var outputLength = outputShape.reduce(function(product, value) {
        return product * value;
      }, 1);
      var output = tf.util.getArrayFromDType(inputDType, outputLength);
      if (numIndices === 0) {
        if (outputRows > 0) {
          output.fill(defaultValue);
        }
        return [output, outputShape];
      }
      if (outputRows <= 0) {
        throw new Error(tf.backend_util.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());
      }
      var start = 0, end = 1;
      var uninitializedIndex = 0;
      var outIndex = segmentIds[start];
      while (true) {
        var nextIndex = 0;
        if (end < numIndices) {
          nextIndex = segmentIds[end];
          if (outIndex === nextIndex) {
            ++end;
            continue;
          }
          if (outIndex >= nextIndex) {
            throw new Error(tf.backend_util.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage());
          }
        }
        if (outIndex < 0 || outIndex >= outputRows) {
          throw new Error(tf.backend_util.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(outIndex, outputRows));
        }
        if (outIndex > uninitializedIndex) {
          output.fill(defaultValue, uninitializedIndex * numCol, outIndex * numCol);
        }
        for (var i = start; i < end; ++i) {
          var index = indices[i];
          if (index < 0 || index >= inputFlat[0]) {
            throw new Error(tf.backend_util.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(i, indices[i], inputFlat[0]));
          }
          for (var j = 0; j < numCol; j++) {
            output[outIndex * numCol + j] += input[index * numCol + j];
          }
        }
        if (isMean) {
          for (var j = 0; j < numCol; j++) {
            output[outIndex * numCol + j] /= end - start;
          }
        }
        start = end;
        ++end;
        uninitializedIndex = outIndex + 1;
        outIndex = nextIndex;
        if (end > numIndices) {
          break;
        }
      }
      if (uninitializedIndex < outputRows) {
        output.fill(defaultValue, uninitializedIndex * numCol, outputRows * numCol);
      }
      return [output, outputShape];
    }
    var sqrtImpl = createSimpleUnaryImpl(function(xi) {
      return Math.sqrt(xi);
    });
    var staticRegexReplaceImpl = createSimpleUnaryImpl(function(x, attrs) {
      var pattern = attrs.pattern, replaceGlobal = attrs.replaceGlobal, rewrite = attrs.rewrite;
      return x.replace(new RegExp(pattern, replaceGlobal ? "g" : ""), rewrite);
    });
    function stridedSliceImpl(outShape, xBuf, strides, begin) {
      var outBuf = tf.buffer(outShape, xBuf.dtype);
      for (var i = 0; i < outBuf.size; i++) {
        var loc = outBuf.indexToLoc(i);
        var newLoc = new Array(loc.length);
        for (var j = 0; j < newLoc.length; j++) {
          newLoc[j] = loc[j] * strides[j] + begin[j];
        }
        outBuf.set.apply(outBuf, __spreadArray([xBuf.get.apply(xBuf, __spreadArray([], __read(newLoc), false))], __read(loc), false));
      }
      return outBuf;
    }
    var StringNGramsOp = (
      /** @class */
      function() {
        function StringNGramsOp2(separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences) {
          this.separator = tf.util.encodeString(separator);
          this.nGramWidths = nGramWidths;
          this.leftPad = tf.util.encodeString(leftPad);
          this.rightPad = tf.util.encodeString(rightPad);
          this.padWidth = padWidth;
          this.preserveShort = preserveShortSequences;
        }
        StringNGramsOp2.prototype.getPadWidth = function(nGramWidth) {
          return Math.min(this.padWidth < 0 ? nGramWidth - 1 : this.padWidth, nGramWidth - 1);
        };
        StringNGramsOp2.prototype.getNumNGrams = function(length, nGramWidth) {
          var padWidth = this.getPadWidth(nGramWidth);
          return Math.max(0, length + 2 * padWidth - nGramWidth + 1);
        };
        StringNGramsOp2.prototype.createNGrams = function(data, splitIndex, output, outputStartIndex, numNGrams, nGramWidth) {
          var _loop_1 = function(nGramIndex2) {
            var padWidth = this_1.getPadWidth(nGramWidth);
            var leftPadding = Math.max(0, padWidth - nGramIndex2);
            var rightPadding = Math.max(0, padWidth - (numNGrams - (nGramIndex2 + 1)));
            var numTokens = nGramWidth - (leftPadding + rightPadding);
            var dataStartIndex = splitIndex + (leftPadding > 0 ? 0 : nGramIndex2 - padWidth);
            var nGramSize = 0;
            nGramSize += leftPadding * this_1.leftPad.length;
            for (var n = 0; n < numTokens; ++n) {
              nGramSize += data[dataStartIndex + n].length;
            }
            nGramSize += rightPadding * this_1.rightPad.length;
            var numSeparators = leftPadding + rightPadding + numTokens - 1;
            nGramSize += numSeparators * this_1.separator.length;
            output[outputStartIndex + nGramIndex2] = new Uint8Array(nGramSize);
            var nGram = output[outputStartIndex + nGramIndex2];
            var nextNGramIndex = 0;
            var appendToNGram = function(str) {
              return str.forEach(function(value) {
                return nGram[nextNGramIndex++] = value;
              });
            };
            for (var n = 0; n < leftPadding; ++n) {
              appendToNGram(this_1.leftPad);
              appendToNGram(this_1.separator);
            }
            for (var n = 0; n < numTokens - 1; ++n) {
              appendToNGram(data[dataStartIndex + n]);
              appendToNGram(this_1.separator);
            }
            if (numTokens > 0) {
              appendToNGram(data[dataStartIndex + numTokens - 1]);
              for (var n = 0; n < rightPadding; ++n) {
                appendToNGram(this_1.separator);
                appendToNGram(this_1.rightPad);
              }
            } else {
              for (var n = 0; n < rightPadding - 1; ++n) {
                appendToNGram(this_1.rightPad);
                appendToNGram(this_1.separator);
              }
              appendToNGram(this_1.rightPad);
            }
          };
          var this_1 = this;
          for (var nGramIndex = 0; nGramIndex < numNGrams; ++nGramIndex) {
            _loop_1(nGramIndex);
          }
        };
        StringNGramsOp2.prototype.compute = function(data, splits) {
          var _this = this;
          var inputDataSize = data.length;
          var splitsSize = splits.length;
          if (splitsSize > 0) {
            var prevSplit = splits[0];
            if (prevSplit !== 0) {
              throw new Error("First split value must be 0, got ".concat(prevSplit));
            }
            for (var i = 1; i < splitsSize; ++i) {
              var validSplits = splits[i] >= prevSplit;
              validSplits = validSplits && splits[i] <= inputDataSize;
              if (!validSplits) {
                throw new Error("Invalid split value ".concat(splits[i], ", must be in [").concat(prevSplit, ", ").concat(inputDataSize, "]"));
              }
              prevSplit = splits[i];
            }
            if (prevSplit !== inputDataSize) {
              throw new Error("Last split value must be data size. Expected ".concat(inputDataSize, ", got ").concat(prevSplit));
            }
          }
          var numBatchItems = splitsSize - 1;
          var nGramsSplits = tf.util.getArrayFromDType("int32", splitsSize);
          if (inputDataSize === 0 || splitsSize === 0) {
            var empty = new Array(inputDataSize);
            for (var i = 0; i <= numBatchItems; ++i) {
              nGramsSplits[i] = 0;
            }
            return [empty, nGramsSplits];
          }
          nGramsSplits[0] = 0;
          var _loop_2 = function(i2) {
            var length = splits[i2] - splits[i2 - 1];
            var numNGrams = 0;
            this_2.nGramWidths.forEach(function(nGramWidth) {
              numNGrams += _this.getNumNGrams(length, nGramWidth);
            });
            if (this_2.preserveShort && length > 0 && numNGrams === 0) {
              numNGrams = 1;
            }
            nGramsSplits[i2] = nGramsSplits[i2 - 1] + numNGrams;
          };
          var this_2 = this;
          for (var i = 1; i <= numBatchItems; ++i) {
            _loop_2(i);
          }
          var nGrams = new Array(nGramsSplits[numBatchItems]);
          var _loop_3 = function(i2) {
            var splitIndex = splits[i2];
            var outputStartIdx = nGramsSplits[i2];
            this_3.nGramWidths.forEach(function(nGramWidth2) {
              var length = splits[i2 + 1] - splits[i2];
              var numNGrams2 = _this.getNumNGrams(length, nGramWidth2);
              _this.createNGrams(data, splitIndex, nGrams, outputStartIdx, numNGrams2, nGramWidth2);
              outputStartIdx += numNGrams2;
            });
            if (this_3.preserveShort && outputStartIdx === nGramsSplits[i2]) {
              var dataLength = splits[i2 + 1] - splits[i2];
              if (dataLength === 0) {
                return "continue";
              }
              var nGramWidth = dataLength + 2 * this_3.padWidth;
              var numNGrams = 1;
              this_3.createNGrams(data, splitIndex, nGrams, outputStartIdx, numNGrams, nGramWidth);
            }
          };
          var this_3 = this;
          for (var i = 0; i < numBatchItems; ++i) {
            _loop_3(i);
          }
          return [nGrams, nGramsSplits];
        };
        return StringNGramsOp2;
      }()
    );
    function stringNGramsImpl(data, dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences) {
      return new StringNGramsOp(separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences).compute(data, dataSplits);
    }
    function split(str, delimiters, skipEmpty, result) {
      if (!str.length) {
        return;
      }
      if (delimiters.length === 0) {
        for (var i = 0; i < str.length; ++i) {
          result.push(str.subarray(i, i + 1));
        }
        return;
      }
      if (delimiters.length === 1) {
        var delimiter = delimiters[0];
        var f = str.indexOf(delimiter);
        while (f !== -1) {
          var token = str.subarray(0, f);
          if (!skipEmpty || token.length !== 0) {
            result.push(token);
          }
          str = str.subarray(f + 1);
          f = str.indexOf(delimiter);
        }
        if (!skipEmpty || str.length !== 0) {
          result.push(str);
        }
        return;
      }
      var tokenStart = 0;
      for (var i = 0; i < str.length + 1; i++) {
        if (i === str.length || delimiters.indexOf(str[i]) !== -1) {
          var token = str.subarray(tokenStart, i);
          if (!skipEmpty || token.length !== 0) {
            result.push(token);
          }
          tokenStart = i + 1;
        }
      }
    }
    function stringSplitImpl(input, delimiter, skipEmpty) {
      var batchSize = input.length;
      var tokens = [];
      var outputSize = 0;
      var maxNumEntries = 0;
      var numIndices = new Array(batchSize);
      for (var i = 0; i < batchSize; ++i) {
        var prevTokensLength = tokens.length;
        split(input[i], delimiter, skipEmpty, tokens);
        var nEntries = tokens.length - prevTokensLength;
        numIndices[i] = nEntries;
        outputSize += nEntries;
        maxNumEntries = Math.max(maxNumEntries, nEntries);
      }
      var indices = tf.util.getArrayFromDType("int32", outputSize * 2);
      var values = new Array(outputSize);
      var shape = [batchSize, maxNumEntries];
      var c = 0;
      for (var i = 0; i < batchSize; ++i) {
        for (var j = 0; j < numIndices[i]; ++j) {
          indices[c * 2] = i;
          indices[c * 2 + 1] = j;
          values[c] = tokens[c];
          ++c;
        }
      }
      return [indices, values, shape];
    }
    function stringToHashBucketFastImpl(input, numBuckets) {
      var output = tf.util.getArrayFromDType("int32", input.length);
      for (var i = 0; i < input.length; ++i) {
        output[i] = tf.util.fingerPrint64(input[i]).modulo(numBuckets).getLowBitsUnsigned();
      }
      return output;
    }
    var subImpl = createSimpleBinaryKernelImpl(function(aValue, bValue) {
      return aValue - bValue;
    });
    function tileImpl(xBuf, reps) {
      var newShape = new Array(xBuf.rank);
      for (var i = 0; i < newShape.length; i++) {
        newShape[i] = xBuf.shape[i] * reps[i];
      }
      var result = tf.buffer(newShape, xBuf.dtype);
      for (var i = 0; i < result.values.length; ++i) {
        var newLoc = result.indexToLoc(i);
        var originalLoc = new Array(xBuf.rank);
        for (var j = 0; j < originalLoc.length; j++) {
          originalLoc[j] = newLoc[j] % xBuf.shape[j];
        }
        var originalIndex = xBuf.locToIndex(originalLoc);
        result.values[i] = xBuf.values[originalIndex];
      }
      return result;
    }
    var comparePair = function(a, b) {
      var valueDiff = b.value - a.value;
      return valueDiff === 0 ? a.index - b.index : valueDiff;
    };
    function select$1(array, k, left, right) {
      if (left === void 0) {
        left = 0;
      }
      if (right === void 0) {
        right = array.length - 1;
      }
      while (right > left) {
        if (right - left > 600) {
          var n = right - left + 1;
          var i_1 = k - left + 1;
          var z = Math.log(n);
          var s = 0.5 * Math.exp(2 * z / 3);
          var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * Math.sign(i_1 - n / 2);
          var newLeft = Math.max(left, Math.floor(k - i_1 * s / n + sd));
          var newRight = Math.min(right, Math.floor(k + (n - i_1) * s / n + sd));
          select$1(array, k, newLeft, newRight);
        }
        var t = array[k];
        var i = left;
        var j = right;
        tf.util.swap(array, left, k);
        if (comparePair(array[right], t) > 0) {
          tf.util.swap(array, left, right);
        }
        while (i < j) {
          tf.util.swap(array, i, j);
          i++;
          j--;
          while (comparePair(array[i], t) < 0) {
            i = i + 1;
          }
          while (comparePair(array[j], t) > 0) {
            j = j - 1;
          }
        }
        if (comparePair(array[left], t) === 0) {
          tf.util.swap(array, left, j);
        } else {
          j = j + 1;
          tf.util.swap(array, j, right);
        }
        if (j <= k) {
          left = j + 1;
        }
        if (k <= j) {
          right = j - 1;
        }
      }
    }
    function topKImpl(x, xShape, xDtype, k, sorted) {
      var lastDim = xShape[xShape.length - 1];
      var _a2 = __read([x.length / lastDim, lastDim], 2), batch = _a2[0], size = _a2[1];
      var allTopKVals = tf.util.getTypedArrayFromDType(xDtype, batch * k);
      var allTopKIndices = tf.util.getTypedArrayFromDType("int32", batch * k);
      var _loop_1 = function(b2) {
        var offset = b2 * size;
        var vals = x.subarray(offset, offset + size);
        var valAndInd = new Array(vals.length);
        vals.forEach(function(value, index) {
          return valAndInd[index] = { value, index };
        });
        if (k < valAndInd.length) {
          select$1(valAndInd, k);
          valAndInd = valAndInd.slice(0, k);
        }
        if (sorted) {
          valAndInd.sort(comparePair);
        }
        var outOffset = b2 * k;
        var topKVals = allTopKVals.subarray(outOffset, outOffset + k);
        var topKIndices = allTopKIndices.subarray(outOffset, outOffset + k);
        for (var i = 0; i < k; i++) {
          topKVals[i] = valAndInd[i].value;
          topKIndices[i] = valAndInd[i].index;
        }
      };
      for (var b = 0; b < batch; b++) {
        _loop_1(b);
      }
      var outputShape = xShape.slice();
      outputShape[outputShape.length - 1] = k;
      return [
        tf.buffer(outputShape, xDtype, allTopKVals),
        tf.buffer(outputShape, "int32", allTopKIndices)
      ];
    }
    function uniqueImpl(values, axis, shape, dtype) {
      var $axis = tf.util.parseAxisParam(axis, shape)[0];
      var newShape = [1, shape[0], 1];
      for (var i = 0; i < $axis; i++) {
        newShape[0] *= shape[i];
      }
      newShape[1] = shape[$axis];
      for (var i = $axis + 1; i < shape.length; i++) {
        newShape[2] *= shape[i];
      }
      var uniqueElements = /* @__PURE__ */ new Map();
      var indices = new Int32Array(shape[$axis]);
      var inputBuffer = new tf.TensorBuffer(newShape, dtype, values);
      var uniqueIndices = [];
      var is1DTensor = newShape[0] === 1 && newShape[2] === 1;
      for (var i = 0; i < shape[$axis]; i++) {
        var element = void 0;
        if (is1DTensor) {
          element = values[i].toString();
        } else {
          var axisValues = [];
          for (var m = 0; m < newShape[0]; m++) {
            for (var n = 0; n < newShape[2]; n++) {
              axisValues.push(inputBuffer.get(m, i, n));
            }
          }
          element = axisValues.join(",");
        }
        var existingIndex = uniqueElements.get(element);
        if (existingIndex != null) {
          indices[i] = existingIndex;
        } else {
          var uniqueIndex = uniqueElements.size;
          uniqueElements.set(element, uniqueIndex);
          indices[i] = uniqueIndex;
          uniqueIndices.push(i);
        }
      }
      var outputTmpShape = newShape.slice();
      outputTmpShape[1] = uniqueElements.size;
      var outputBuffer = new tf.TensorBuffer(outputTmpShape, dtype);
      uniqueIndices.forEach(function(uniqueElementIndex, i2) {
        for (var m2 = 0; m2 < newShape[0]; m2++) {
          for (var n2 = 0; n2 < newShape[2]; n2++) {
            outputBuffer.set(inputBuffer.get(m2, uniqueElementIndex, n2), m2, i2, n2);
          }
        }
      });
      var outputShape = shape.slice();
      outputShape[$axis] = outputTmpShape[1];
      return {
        outputValues: outputBuffer.values,
        outputShape,
        indices
      };
    }
    var addImplCPU = addImpl;
    var bincountImplCPU = bincountImpl;
    var bincountReduceImplCPU = bincountReduceImpl;
    var bitwiseAndImplCPU = bitwiseAndImpl;
    var castImplCPU = castImpl;
    var ceilImplCPU = ceilImpl;
    var concatImplCPU = concatImpl$1;
    var equalImplCPU = equalImpl;
    var expImplCPU = expImpl;
    var expm1ImplCPU = expm1Impl;
    var floorImplCPU = floorImpl;
    var gatherNdImplCPU = gatherNdImpl;
    var gatherV2ImplCPU = gatherV2Impl;
    var greaterImplCPU = greaterImpl;
    var greaterEqualImplCPU = greaterEqualImpl;
    var lessImplCPU = lessImpl;
    var lessEqualImplCPU = lessEqualImpl;
    var linSpaceImplCPU = linSpaceImpl;
    var logImplCPU = logImpl;
    var maxImplCPU = maxImpl$1;
    var maximumImplCPU = maximumImpl;
    var minimumImplCPU = minimumImpl;
    var multiplyImplCPU = multiplyImpl;
    var negImplCPU = negImpl;
    var notEqualImplCPU = notEqualImpl;
    var prodImplCPU = prodImpl;
    var raggedGatherImplCPU = raggedGatherImpl;
    var raggedRangeImplCPU = raggedRangeImpl;
    var raggedTensorToTensorImplCPU = raggedTensorToTensorImpl;
    var rangeImplCPU = rangeImpl;
    var rsqrtImplCPU = rsqrtImpl;
    var scatterImplCPU = scatterImpl;
    var sigmoidImplCPU = sigmoidImpl;
    var simpleAbsImplCPU = simpleAbsImpl;
    var sliceImplCPU = sliceImpl;
    var sparseFillEmptyRowsImplCPU = sparseFillEmptyRowsImpl;
    var sparseReshapeImplCPU = sparseReshapeImpl;
    var sparseSegmentReductionImplCPU = sparseSegmentReductionImpl;
    var sqrtImplCPU = sqrtImpl;
    var staticRegexReplaceImplCPU = staticRegexReplaceImpl;
    var stridedSliceImplCPU = stridedSliceImpl;
    var stringNGramsImplCPU = stringNGramsImpl;
    var stringSplitImplCPU = stringSplitImpl;
    var stringToHashBucketFastImplCPU = stringToHashBucketFastImpl;
    var subImplCPU = subImpl;
    var tileImplCPU = tileImpl;
    var topKImplCPU = topKImpl;
    var transposeImplCPU = transposeImpl$1;
    var uniqueImplCPU = uniqueImpl;
    function getVecChannels(name, rank) {
      return ["x", "y", "z", "w", "u", "v"].slice(0, rank).map(function(d) {
        return "".concat(name, ".").concat(d);
      });
    }
    function getChannels(name, rank) {
      if (rank === 1) {
        return [name];
      }
      return getVecChannels(name, rank);
    }
    function getSourceCoords$2(rank, dims) {
      if (rank === 1) {
        return "rc";
      }
      var coords2 = "";
      for (var i = 0; i < rank; i++) {
        coords2 += dims[i];
        if (i < rank - 1) {
          coords2 += ",";
        }
      }
      return coords2;
    }
    var PackProgram = (
      /** @class */
      function() {
        function PackProgram2(outputShape) {
          this.variableNames = ["A"];
          this.packedInputs = false;
          this.packedOutput = true;
          this.outputShape = outputShape;
          this.rank = outputShape.length;
          this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);
          if (this.rank === 0) {
            this.userCode = "\n        void main() {\n          setOutput(vec4(getA(), 0., 0., 0.));\n        }\n      ";
          } else {
            var channels = getChannels("rc", this.rank);
            var dtype = getCoordsDataType(this.rank);
            var outOfBoundsCondition = this.getOutOfBoundsCondition(channels);
            var setup = this.getSetup(channels);
            var output = this.getOutput(channels);
            this.userCode = "\n        void main() {\n          ".concat(dtype, " rc = getOutputCoords();\n\n          if(").concat(outOfBoundsCondition, ") {\n            setOutput(vec4(0));\n          } else {\n            ").concat(setup, "\n\n            setOutput(vec4(").concat(output, "));\n          }\n        }\n      ");
          }
        }
        PackProgram2.prototype.getSourceCoordsArr = function(dims) {
          var coords2 = [];
          for (var row = 0; row <= 1; row++) {
            for (var col = 0; col <= 1; col++) {
              var coord = "".concat(row === 0 ? "r" : "rp1", ", ").concat(col === 0 ? "c" : "cp1");
              for (var d = 2; d < this.rank; d++) {
                coord = "".concat(dims[dims.length - 1 - d], ",") + coord;
              }
              coords2.push(coord);
            }
          }
          return coords2;
        };
        PackProgram2.prototype.getOutOfBoundsCondition = function(dims) {
          if (this.rank === 1) {
            return "rc > ".concat(this.enableShapeUniforms ? "outShape" : this.outputShape[0]);
          }
          var cond = "";
          for (var i = this.rank - 2; i < this.rank; i++) {
            cond += "".concat(dims[i], " >= ").concat(this.enableShapeUniforms ? "outShape[".concat(i, "]") : this.outputShape[i]);
            if (i < this.rank - 1) {
              cond += "||";
            }
          }
          return cond;
        };
        PackProgram2.prototype.getSetup = function(dims) {
          if (this.rank === 1) {
            return "";
          }
          var innerDims = dims.slice(-2);
          var col = this.enableShapeUniforms ? "outShape[".concat(this.rank, " - 1]") : this.outputShape[this.rank - 1];
          var row = this.enableShapeUniforms ? "outShape[".concat(this.rank, " - 2]") : this.outputShape[this.rank - 2];
          return "\n      int r = ".concat(innerDims[0], ";\n      int c = ").concat(innerDims[1], ";\n      int rp1 = r + 1;\n      int cp1 = c + 1;\n\n      bool cEdge = cp1 >= ").concat(col, ";\n      bool rEdge = rp1 >= ").concat(row, ";\n    ");
        };
        PackProgram2.prototype.getOutput = function(dims) {
          var sourceCoords = this.getSourceCoordsArr(dims);
          if (this.rank === 1) {
            var outShape = this.enableShapeUniforms ? "outShape" : this.outputShape[0];
            return "getA(rc), (rc + 1 >= ".concat(outShape, " ? 0. : getA(rc + 1)), 0, 0");
          }
          return "getA(".concat(sourceCoords[0], "),\n            cEdge ? 0. : getA(").concat(sourceCoords[1], "),\n            rEdge ? 0. : getA(").concat(sourceCoords[2], "),\n            rEdge || cEdge ? 0. : getA(").concat(sourceCoords[3], ")");
        };
        return PackProgram2;
      }()
    );
    var ReshapePackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ReshapePackedProgram2(outputShape, inputShape) {
          this.variableNames = ["A"];
          this.packedInputs = true;
          this.packedOutput = true;
          this.customUniforms = [{ name: "inputShape", type: "ivec3" }];
          this.outputShape = outputShape;
          this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);
          var mainLoop = "";
          for (var i = 0; i < 4; i++) {
            var thisRC = "thisRC = rc;";
            if (i % 2 === 1) {
              thisRC += "thisRC.z += 1;";
            }
            if (i > 1) {
              thisRC += "thisRC.y += 1;";
            }
            mainLoop += "\n        ".concat(thisRC, "\n        ").concat(i > 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[").concat(i, "] =\n            getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n        ").concat(i > 0 ? "}" : "", "\n      ");
          }
          this.userCode = "\n      ".concat(getReshapedInputCoords(inputShape, this.enableShapeUniforms), "\n      ").concat(this.enableShapeUniforms ? getFlatIndexFrom3DOutput() : getFlatIndexFrom3D(outputShape), "\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n\n        vec4 result = vec4(0.);\n\n        ivec3 thisRC;\n        int rows = ").concat(this.enableShapeUniforms ? "outShape[1]" : outputShape[1], ";\n        int cols = ").concat(this.enableShapeUniforms ? "outShape[2]" : outputShape[2], ";\n\n        ").concat(mainLoop, "\n\n        setOutput(result);\n      }\n    ");
        }
        return ReshapePackedProgram2;
      }()
    );
    function getReshapedInputCoords(shape, enableShapeUniforms) {
      var coordsFromIndexSnippet = enableShapeUniforms ? getLogicalCoordinatesFromFlatIndexByUniform(["r", "c", "d"], "inputShape") : getLogicalCoordinatesFromFlatIndex(["r", "c", "d"], shape);
      return "\n    ivec3 inputCoordsFromReshapedOutCoords(int index) {\n      ".concat(coordsFromIndexSnippet, "\n      return ivec3(r, c, d);\n    }\n  ");
    }
    var TextureManager = (
      /** @class */
      function() {
        function TextureManager2(gpgpu) {
          this.gpgpu = gpgpu;
          this.numUsedTextures = 0;
          this.numFreeTextures = 0;
          this._numBytesAllocated = 0;
          this._numBytesFree = 0;
          this.freeTextures = {};
          this.usedTextures = {};
          this.logEnabled = false;
        }
        TextureManager2.prototype.acquireTexture = function(shapeRC, usage, isPacked) {
          var physicalTexType = getPhysicalFromLogicalTextureType(usage, isPacked);
          var shapeKey = getKeyFromTextureShape(shapeRC, physicalTexType, isPacked);
          if (!(shapeKey in this.freeTextures)) {
            this.freeTextures[shapeKey] = [];
          }
          if (!(shapeKey in this.usedTextures)) {
            this.usedTextures[shapeKey] = [];
          }
          var texBytes = computeBytes(shapeRC, physicalTexType, this.gpgpu.gl, this.gpgpu.textureConfig, isPacked);
          if (this.freeTextures[shapeKey].length > 0) {
            this.numFreeTextures--;
            this.numUsedTextures++;
            this._numBytesFree -= texBytes;
            this.log();
            var newTexture_1 = this.freeTextures[shapeKey].pop();
            this.usedTextures[shapeKey].push(newTexture_1);
            return newTexture_1;
          }
          var newTexture;
          if (physicalTexType === PhysicalTextureType.PACKED_2X2_FLOAT32) {
            newTexture = this.gpgpu.createPackedMatrixTexture(shapeRC[0], shapeRC[1]);
          } else if (physicalTexType === PhysicalTextureType.PACKED_2X2_FLOAT16) {
            newTexture = this.gpgpu.createFloat16PackedMatrixTexture(shapeRC[0], shapeRC[1]);
          } else if (physicalTexType === PhysicalTextureType.UNPACKED_FLOAT32) {
            newTexture = this.gpgpu.createFloat32MatrixTexture(shapeRC[0], shapeRC[1]);
          } else if (physicalTexType === PhysicalTextureType.UNPACKED_FLOAT16) {
            newTexture = this.gpgpu.createFloat16MatrixTexture(shapeRC[0], shapeRC[1]);
          } else if (physicalTexType === PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE) {
            newTexture = this.gpgpu.createUnsignedBytesMatrixTexture(shapeRC[0], shapeRC[1]);
          }
          this.usedTextures[shapeKey].push(newTexture);
          this.numUsedTextures++;
          this._numBytesAllocated += texBytes;
          this.log();
          return newTexture;
        };
        TextureManager2.prototype.releaseTexture = function(texture, shape, logicalTexType, isPacked) {
          if (this.freeTextures == null) {
            return;
          }
          var physicalTexType = getPhysicalFromLogicalTextureType(logicalTexType, isPacked);
          var shapeKey = getKeyFromTextureShape(shape, physicalTexType, isPacked);
          if (!(shapeKey in this.freeTextures)) {
            this.freeTextures[shapeKey] = [];
          }
          var texBytes = computeBytes(shape, physicalTexType, this.gpgpu.gl, this.gpgpu.textureConfig, isPacked);
          var deleteTexThreshold = tf.env().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");
          if (deleteTexThreshold !== -1 && this._numBytesAllocated > deleteTexThreshold) {
            this.gpgpu.deleteMatrixTexture(texture.texture);
            this._numBytesAllocated -= texBytes;
          } else {
            this.freeTextures[shapeKey].push(texture);
            this.numFreeTextures++;
            this._numBytesFree += texBytes;
          }
          this.numUsedTextures--;
          var texList = this.usedTextures[shapeKey];
          var texIndex = texList && texList.indexOf(texture);
          if (texIndex == null || texIndex < 0) {
            throw new Error("Cannot release a texture that was never provided by this texture manager");
          }
          texList[texIndex] = texList[texList.length - 1];
          texList.pop();
          this.log();
        };
        TextureManager2.prototype.log = function() {
          if (!this.logEnabled) {
            return;
          }
          var total = this.numFreeTextures + this.numUsedTextures;
          console.log("Free/Used", "".concat(this.numFreeTextures, " / ").concat(this.numUsedTextures), "(".concat(total, ")"));
          var freeRatio = this._numBytesFree / this._numBytesAllocated;
          console.log("Bytes allocated: ".concat(this._numBytesAllocated));
          console.log("Bytes unused: ".concat(this._numBytesFree, " (").concat(Math.round(100 * freeRatio), "%)"));
        };
        Object.defineProperty(TextureManager2.prototype, "numBytesAllocated", {
          get: function() {
            return this._numBytesAllocated;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(TextureManager2.prototype, "numBytesFree", {
          get: function() {
            return this._numBytesFree;
          },
          enumerable: false,
          configurable: true
        });
        TextureManager2.prototype.getNumUsedTextures = function() {
          return this.numUsedTextures;
        };
        TextureManager2.prototype.getNumFreeTextures = function() {
          return this.numFreeTextures;
        };
        TextureManager2.prototype.dispose = function() {
          var _this = this;
          if (this.freeTextures == null) {
            return;
          }
          for (var texShape in this.freeTextures) {
            this.freeTextures[texShape].forEach(function(tex) {
              _this.gpgpu.deleteMatrixTexture(tex.texture);
            });
          }
          for (var texShape in this.usedTextures) {
            this.usedTextures[texShape].forEach(function(tex) {
              _this.gpgpu.deleteMatrixTexture(tex.texture);
            });
          }
          this.freeTextures = null;
          this.usedTextures = null;
          this.numUsedTextures = 0;
          this.numFreeTextures = 0;
          this._numBytesAllocated = 0;
          this._numBytesFree = 0;
        };
        return TextureManager2;
      }()
    );
    function numBytesForInternalFormat(gl, internalFormat) {
      var glany = gl;
      if (internalFormat === glany.R32F) {
        return 4;
      } else if (internalFormat === glany.R16F) {
        return 2;
      } else if (internalFormat === glany.RGBA32F) {
        return 16;
      } else if (internalFormat === gl.RGBA) {
        return 16;
      } else if (internalFormat === glany.RGBA16F) {
        return 8;
      } else if (internalFormat === glany.RGBA8) {
        return 4;
      }
      throw new Error("Unknown internal format ".concat(internalFormat));
    }
    function computeBytes(shape, physicalTexType, gl, textureConfig, isPacked) {
      var internalFormat = internalFormatForPhysicalTexType(physicalTexType, textureConfig);
      var numElements;
      if (isPacked) {
        var _a2 = __read(getPackedMatrixTextureShapeWidthHeight(shape[0], shape[1]), 2), packedWidth = _a2[0], packedHeight = _a2[1];
        numElements = packedWidth * packedHeight;
      } else {
        var _b = __read(getUnpackedMatrixTextureShapeWidthHeight(shape[0], shape[1]), 2), width = _b[0], height = _b[1];
        numElements = width * height;
      }
      var bytesPerElement = numBytesForInternalFormat(gl, internalFormat);
      return numElements * bytesPerElement;
    }
    function internalFormatForPhysicalTexType(physicalTexType, textureConfig) {
      switch (physicalTexType) {
        case PhysicalTextureType.PACKED_2X2_FLOAT32:
          return getInternalFormatForPackedMatrixTexture(textureConfig);
        case PhysicalTextureType.PACKED_2X2_FLOAT16:
          return getInternalFormatForFloat16PackedMatrixTexture(textureConfig);
        case PhysicalTextureType.UNPACKED_FLOAT32:
          return getInternalFormatForFloat32MatrixTexture(textureConfig);
        case PhysicalTextureType.UNPACKED_FLOAT16:
          return getInternalFormatForFloat16MatrixTexture(textureConfig);
        case PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE:
          return getInternalFormatForUnsignedBytesMatrixTexture(textureConfig);
        default:
          throw new Error("Unknown physical texture type ".concat(physicalTexType));
      }
    }
    function getPhysicalTextureForRendering(isPacked) {
      if (tf.env().getBool("WEBGL_RENDER_FLOAT32_ENABLED")) {
        if (isPacked) {
          return PhysicalTextureType.PACKED_2X2_FLOAT32;
        }
        return PhysicalTextureType.UNPACKED_FLOAT32;
      }
      if (isPacked) {
        return PhysicalTextureType.PACKED_2X2_FLOAT16;
      }
      return PhysicalTextureType.UNPACKED_FLOAT16;
    }
    function getPhysicalFromLogicalTextureType(logicalTexType, isPacked) {
      if (logicalTexType === TextureUsage.UPLOAD) {
        return PhysicalTextureType.PACKED_2X2_FLOAT32;
      } else if (logicalTexType === TextureUsage.RENDER || logicalTexType == null) {
        return getPhysicalTextureForRendering(isPacked);
      } else if (logicalTexType === TextureUsage.DOWNLOAD || logicalTexType === TextureUsage.PIXELS) {
        return PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE;
      }
      throw new Error("Unknown logical texture type ".concat(logicalTexType));
    }
    function getKeyFromTextureShape(shapeRowsCol, physicalTexType, isPacked) {
      return "".concat(shapeRowsCol[0], "_").concat(shapeRowsCol[1], "_").concat(physicalTexType, "_").concat(isPacked);
    }
    var UnaryOpProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function UnaryOpProgram2(aShape, opSnippet) {
          this.variableNames = ["A"];
          this.outputShape = aShape;
          this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);
          this.userCode = "\n      float unaryOperation(float x) {\n        ".concat(opSnippet, "\n      }\n\n      void main() {\n        float x = getAAtOutCoords();\n        float y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    ");
        }
        return UnaryOpProgram2;
      }()
    );
    var CHECK_NAN_SNIPPET$1 = "if (isnan(x)) return x;";
    var LINEAR$1 = "return x;";
    var ABS$1 = "return abs(x);";
    var ELU$2 = "return (x >= 0.0) ? x : (exp(x) - 1.0);";
    var RELU$2 = CHECK_NAN_SNIPPET$1 + "\n  return (x < 0.0) ? 0.0 : x;\n";
    var RELU6$2 = CHECK_NAN_SNIPPET$1 + "\n  return (x < 0.0) ? 0.0 : min(6.0, x);\n";
    var CLONE = "return x;";
    var SIGMOID$2 = "return 1.0 / (1.0 + exp(-1.0 * x));";
    var LINEAR = "return x;";
    var ELU$1 = "\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";
    var RELU$1 = "\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";
    var RELU6$1 = "\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";
    var SIGMOID$1 = "return 1.0 / (1.0 + exp(-1.0 * x));";
    var UnaryOpPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function UnaryOpPackedProgram2(aShape, opSnippet) {
          this.variableNames = ["A"];
          this.packedInputs = true;
          this.packedOutput = true;
          this.outputShape = aShape;
          this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);
          this.userCode = "\n      vec4 unaryOperation(vec4 x) {\n        ".concat(opSnippet, "\n      }\n\n      void main() {\n        vec4 x = getAAtOutCoords();\n        vec4 y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    ");
        }
        return UnaryOpPackedProgram2;
      }()
    );
    var UnpackProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function UnpackProgram2(outputShape) {
          this.variableNames = ["A"];
          this.packedInputs = true;
          this.packedOutput = false;
          this.outputShape = outputShape;
          this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);
          var rank = outputShape.length;
          var channels = getChannels("rc", rank);
          var dtype = getCoordsDataType(rank);
          var sourceCoords = getSourceCoords$2(rank, channels);
          var innerDims = channels.slice(-2);
          var coords2 = rank <= 1 ? "rc" : "vec2(".concat(innerDims.join(","), ")");
          this.userCode = "\n      void main() {\n        ".concat(dtype, " rc = getOutputCoords();\n        vec4 packedInput = getA(").concat(sourceCoords, ");\n\n        setOutput(getChannel(packedInput, ").concat(coords2, "));\n      }\n    ");
        }
        return UnpackProgram2;
      }()
    );
    var whereImpl = tf.kernel_impls.whereImpl;
    var EPSILON_FLOAT32 = 1e-7;
    var EPSILON_FLOAT16 = 1e-4;
    var binaryCaches = {};
    function getBinaryCache(webGLVersion) {
      if (webGLVersion in binaryCaches) {
        return binaryCaches[webGLVersion];
      }
      binaryCaches[webGLVersion] = {};
      return binaryCaches[webGLVersion];
    }
    var CPU_HANDOFF_SIZE_THRESHOLD = tf.env().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");
    var BEFORE_PAGING_CONSTANT = 600;
    function numMBBeforeWarning() {
      if (tf.env().global.screen == null) {
        return 1024;
      }
      return tf.env().global.screen.height * tf.env().global.screen.width * window.devicePixelRatio * BEFORE_PAGING_CONSTANT / 1024 / 1024;
    }
    var MathBackendWebGL = (
      /** @class */
      function(_super) {
        __extends(MathBackendWebGL2, _super);
        function MathBackendWebGL2(gpuResource) {
          var _this = _super.call(this) || this;
          _this.pendingRead = /* @__PURE__ */ new WeakMap();
          _this.pendingDisposal = /* @__PURE__ */ new WeakSet();
          _this.dataRefCount = /* @__PURE__ */ new WeakMap();
          _this.numBytesInGPU = 0;
          _this.uploadWaitMs = 0;
          _this.downloadWaitMs = 0;
          _this.lastGlFlushTime = 0;
          _this.warnedAboutMemory = false;
          _this.pendingDeletes = 0;
          _this.disposed = false;
          if (!tf.env().getBool("HAS_WEBGL")) {
            throw new Error("WebGL is not supported on this device");
          }
          var newGPGPU;
          if (gpuResource != null) {
            if (gpuResource instanceof GPGPUContext) {
              newGPGPU = gpuResource;
            } else {
              var gl = getWebGLContext(tf.env().getNumber("WEBGL_VERSION"), gpuResource);
              newGPGPU = new GPGPUContext(gl);
            }
            _this.binaryCache = {};
            _this.gpgpuCreatedLocally = false;
          } else {
            var gl = getWebGLContext(tf.env().getNumber("WEBGL_VERSION"));
            newGPGPU = new GPGPUContext(gl);
            _this.binaryCache = getBinaryCache(tf.env().getNumber("WEBGL_VERSION"));
            _this.gpgpuCreatedLocally = true;
          }
          _this.gpgpu = newGPGPU;
          _this.canvas = _this.gpgpu.gl.canvas;
          _this.textureManager = new TextureManager(_this.gpgpu);
          _this.numMBBeforeWarning = numMBBeforeWarning();
          _this.texData = new tf.DataStorage(_this, tf.engine());
          return _this;
        }
        MathBackendWebGL2.prototype.nextDataId = function() {
          return MathBackendWebGL2.nextDataId++;
        };
        MathBackendWebGL2.prototype.numDataIds = function() {
          return this.texData.numDataIds() - this.pendingDeletes;
        };
        MathBackendWebGL2.prototype.writeTexture = function(texture, shape, dtype, texHeight, texWidth, channels) {
          var input = this.makeTensorInfo(shape, dtype);
          var inData = this.texData.get(input.dataId);
          inData.isPacked = false;
          inData.texture = { texture, texShape: [texHeight, texWidth] };
          inData.texShape = [texHeight, texWidth];
          var shapeAs3D = getShapeAs3D(shape);
          var program = new EncodeMatrixProgram(shapeAs3D, false, channels);
          var output = this.runWebGLProgram(program, [input], dtype, [[texHeight, texWidth]]);
          output.shape = shape;
          inData.texture = null;
          this.disposeIntermediateTensorInfo(input);
          return output.dataId;
        };
        MathBackendWebGL2.prototype.write = function(values, shape, dtype) {
          if (tf.env().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS") || tf.env().getBool("DEBUG")) {
            this.checkNumericalProblems(values);
          }
          if (dtype === "complex64" && values != null) {
            throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");
          }
          var dataId = { id: this.nextDataId() };
          this.texData.set(dataId, { shape, dtype, values, usage: TextureUsage.UPLOAD, refCount: 1 });
          return dataId;
        };
        MathBackendWebGL2.prototype.refCount = function(dataId) {
          if (this.texData.has(dataId)) {
            var tensorData = this.texData.get(dataId);
            return tensorData.refCount;
          }
          return 0;
        };
        MathBackendWebGL2.prototype.incRef = function(dataId) {
          var texData = this.texData.get(dataId);
          texData.refCount++;
        };
        MathBackendWebGL2.prototype.decRef = function(dataId) {
          if (this.texData.has(dataId)) {
            var texData = this.texData.get(dataId);
            texData.refCount--;
          }
        };
        MathBackendWebGL2.prototype.move = function(dataId, values, shape, dtype, refCount) {
          if (tf.env().getBool("DEBUG")) {
            this.checkNumericalProblems(values);
          }
          if (dtype === "complex64") {
            throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");
          }
          this.texData.set(dataId, { shape, dtype, values, usage: TextureUsage.UPLOAD, refCount });
        };
        MathBackendWebGL2.prototype.disposeIntermediateTensorInfo = function(tensorInfo) {
          this.disposeData(tensorInfo.dataId);
        };
        MathBackendWebGL2.prototype.readSync = function(dataId) {
          var texData = this.texData.get(dataId);
          var values = texData.values, dtype = texData.dtype, complexTensorInfos = texData.complexTensorInfos, slice2 = texData.slice, shape = texData.shape, isPacked = texData.isPacked;
          if (slice2 != null) {
            var program = void 0;
            if (isPacked) {
              program = new UnaryOpPackedProgram(shape, CLONE);
            } else {
              program = new UnaryOpProgram(shape, CLONE);
            }
            var res = this.runWebGLProgram(program, [{ dataId, shape, dtype }], dtype);
            var data = this.readSync(res.dataId);
            this.disposeIntermediateTensorInfo(res);
            return data;
          }
          if (values != null) {
            return this.convertAndCacheOnCPU(dataId);
          }
          if (dtype === "string") {
            return values;
          }
          var shouldTimeProgram = this.activeTimers != null;
          var start;
          if (shouldTimeProgram) {
            start = tf.util.now();
          }
          var result;
          if (dtype === "complex64") {
            var realValues = this.readSync(complexTensorInfos.real.dataId);
            var imagValues = this.readSync(complexTensorInfos.imag.dataId);
            result = tf.backend_util.mergeRealAndImagArrays(realValues, imagValues);
          } else {
            result = this.getValuesFromTexture(dataId);
          }
          if (shouldTimeProgram) {
            this.downloadWaitMs += tf.util.now() - start;
          }
          return this.convertAndCacheOnCPU(dataId, result);
        };
        MathBackendWebGL2.prototype.read = function(dataId) {
          return __awaiter(this, void 0, void 0, function() {
            var subscribers_1, texData, values, shape, slice2, dtype, complexTensorInfos, isPacked, program, res, data, buffer, tmpDownloadTarget, tmpData, vals, ps, realValues, imagValues, size, gl_1, dTypeVals, subscribers;
            var _b;
            return __generator(this, function(_c) {
              switch (_c.label) {
                case 0:
                  if (this.pendingRead.has(dataId)) {
                    subscribers_1 = this.pendingRead.get(dataId);
                    return [2, new Promise(function(resolve) {
                      return subscribers_1.push(resolve);
                    })];
                  }
                  texData = this.texData.get(dataId);
                  values = texData.values, shape = texData.shape, slice2 = texData.slice, dtype = texData.dtype, complexTensorInfos = texData.complexTensorInfos, isPacked = texData.isPacked;
                  if (slice2 != null) {
                    program = void 0;
                    if (isPacked) {
                      program = new UnaryOpPackedProgram(shape, CLONE);
                    } else {
                      program = new UnaryOpProgram(shape, CLONE);
                    }
                    res = this.runWebGLProgram(program, [{ dataId, shape, dtype }], dtype);
                    data = this.read(res.dataId);
                    this.disposeIntermediateTensorInfo(res);
                    return [2, data];
                  }
                  if (values != null) {
                    return [2, this.convertAndCacheOnCPU(dataId)];
                  }
                  if (tf.env().getBool("DEBUG")) {
                    if (!tf.env().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED") && tf.env().getNumber("WEBGL_VERSION") === 2) {
                      throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");
                    }
                  }
                  buffer = null;
                  if (dtype !== "complex64" && tf.env().get("WEBGL_BUFFER_SUPPORTED")) {
                    tmpDownloadTarget = this.decode(dataId);
                    tmpData = this.texData.get(tmpDownloadTarget.dataId);
                    buffer = (_b = this.gpgpu).createBufferFromTexture.apply(_b, __spreadArray([tmpData.texture.texture], __read(getDenseTexShape(shape)), false));
                  }
                  this.pendingRead.set(dataId, []);
                  if (!(dtype !== "complex64")) return [3, 2];
                  return [4, this.gpgpu.createAndWaitForFence()];
                case 1:
                  _c.sent();
                  _c.label = 2;
                case 2:
                  if (!(dtype === "complex64")) return [3, 4];
                  return [4, Promise.all([
                    this.read(complexTensorInfos.real.dataId),
                    this.read(complexTensorInfos.imag.dataId)
                  ])];
                case 3:
                  ps = _c.sent();
                  realValues = ps[0];
                  imagValues = ps[1];
                  vals = tf.backend_util.mergeRealAndImagArrays(realValues, imagValues);
                  return [3, 5];
                case 4:
                  if (buffer == null) {
                    vals = this.getValuesFromTexture(dataId);
                  } else {
                    size = tf.util.sizeFromShape(shape);
                    vals = this.gpgpu.downloadFloat32MatrixFromBuffer(buffer, size);
                  }
                  _c.label = 5;
                case 5:
                  if (tmpDownloadTarget != null) {
                    this.disposeIntermediateTensorInfo(tmpDownloadTarget);
                  }
                  if (buffer != null) {
                    gl_1 = this.gpgpu.gl;
                    callAndCheck(gl_1, function() {
                      return gl_1.deleteBuffer(buffer);
                    });
                  }
                  dTypeVals = this.convertAndCacheOnCPU(dataId, vals);
                  subscribers = this.pendingRead.get(dataId);
                  this.pendingRead.delete(dataId);
                  subscribers.forEach(function(resolve) {
                    return resolve(dTypeVals);
                  });
                  if (this.pendingDisposal.has(dataId)) {
                    this.pendingDisposal.delete(dataId);
                    if (this.disposeData(dataId)) {
                      tf.engine().removeDataId(dataId, this);
                    }
                    this.pendingDeletes--;
                  }
                  return [2, dTypeVals];
              }
            });
          });
        };
        MathBackendWebGL2.prototype.readToGPU = function(dataId, options) {
          if (options === void 0) {
            options = {};
          }
          var texData = this.texData.get(dataId);
          var values = texData.values, shape = texData.shape, slice2 = texData.slice, dtype = texData.dtype, isPacked = texData.isPacked, texture = texData.texture;
          if (dtype === "complex64") {
            throw new Error("Does not support reading texture for complex64 dtype.");
          }
          if (slice2 != null) {
            var program = void 0;
            if (isPacked) {
              program = new UnaryOpPackedProgram(shape, CLONE);
            } else {
              program = new UnaryOpProgram(shape, CLONE);
            }
            var res = this.runWebGLProgram(program, [{ dataId, shape, dtype }], dtype);
            var gpuResouorce = this.readToGPU(res, options);
            this.disposeIntermediateTensorInfo(res);
            return gpuResouorce;
          }
          if (texture == null) {
            if (values != null) {
              throw new Error("Data is not on GPU but on CPU.");
            } else {
              throw new Error("There is no data on GPU or CPU.");
            }
          }
          var tmpTarget = this.decode(dataId, options.customTexShape);
          var tensorRef = tf.engine().makeTensorFromTensorInfo(tmpTarget);
          var tmpData = this.texData.get(tmpTarget.dataId);
          return Object.assign({ tensorRef }, tmpData.texture);
        };
        MathBackendWebGL2.prototype.bufferSync = function(t) {
          var data = this.readSync(t.dataId);
          if (t.dtype === "string") {
            try {
              var strings = data.map(function(d) {
                return tf.util.decodeString(d);
              });
              return tf.buffer(t.shape, t.dtype, strings);
            } catch (_a2) {
              throw new Error("Failed to decode encoded string bytes into utf-8");
            }
          }
          return tf.buffer(t.shape, t.dtype, data);
        };
        MathBackendWebGL2.prototype.checkNumericalProblems = function(values) {
          if (values == null) {
            return;
          }
          for (var i = 0; i < values.length; i++) {
            var num = values[i];
            if (!canBeRepresented(num)) {
              if (tf.env().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")) {
                throw Error("The value ".concat(num, " cannot be represented with your ") + "current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'");
              }
              throw Error("The value ".concat(num, " cannot be represented on this device."));
            }
          }
        };
        MathBackendWebGL2.prototype.getValuesFromTexture = function(dataId) {
          var _b;
          var _c = this.texData.get(dataId), shape = _c.shape, dtype = _c.dtype, isPacked = _c.isPacked;
          var size = tf.util.sizeFromShape(shape);
          if (tf.env().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")) {
            var tmpTarget = this.decode(dataId);
            var tmpData_1 = this.texData.get(tmpTarget.dataId);
            var vals_1 = (_b = this.gpgpu).downloadMatrixFromPackedTexture.apply(_b, __spreadArray([tmpData_1.texture.texture], __read(getDenseTexShape(shape)), false)).subarray(0, size);
            this.disposeIntermediateTensorInfo(tmpTarget);
            return vals_1;
          }
          var shouldUsePackedProgram = tf.env().getBool("WEBGL_PACK") && isPacked === true;
          var outputShape = shouldUsePackedProgram ? getShapeAs3D(shape) : shape;
          var program = shouldUsePackedProgram ? new EncodeFloatPackedProgram(outputShape) : new EncodeFloatProgram(outputShape);
          var output = this.runWebGLProgram(program, [{ shape: outputShape, dtype, dataId }], "float32");
          var tmpData = this.texData.get(output.dataId);
          var vals = this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(tmpData.texture.texture, tmpData.texShape[0], tmpData.texShape[1]).subarray(0, size);
          this.disposeIntermediateTensorInfo(output);
          return vals;
        };
        MathBackendWebGL2.prototype.timerAvailable = function() {
          return tf.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0;
        };
        MathBackendWebGL2.prototype.time = function(f) {
          var _this = this;
          var oldActiveTimers = this.activeTimers;
          var newActiveTimers = [];
          var outerMostTime = false;
          if (this.programTimersStack == null) {
            this.programTimersStack = newActiveTimers;
            outerMostTime = true;
          } else {
            this.activeTimers.push(newActiveTimers);
          }
          this.activeTimers = newActiveTimers;
          f();
          var flattenedActiveTimerQueries = tf.util.flatten(this.activeTimers.map(function(d) {
            return d.query;
          })).filter(function(d) {
            return d != null;
          });
          var flattenedActiveTimerNames = tf.util.flatten(this.activeTimers.map(function(d) {
            return d.name;
          })).filter(function(d) {
            return d != null;
          });
          this.activeTimers = oldActiveTimers;
          if (outerMostTime) {
            this.programTimersStack = null;
          }
          var res = {
            uploadWaitMs: this.uploadWaitMs,
            downloadWaitMs: this.downloadWaitMs,
            kernelMs: null,
            wallMs: null
            // will be filled by the engine
          };
          return function() {
            return __awaiter(_this, void 0, void 0, function() {
              var kernelMs_1;
              return __generator(this, function(_b) {
                switch (_b.label) {
                  case 0:
                    if (!(tf.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0)) return [3, 2];
                    return [4, Promise.all(flattenedActiveTimerQueries)];
                  case 1:
                    kernelMs_1 = _b.sent();
                    res["kernelMs"] = tf.util.sum(kernelMs_1);
                    res["getExtraProfileInfo"] = function() {
                      return kernelMs_1.map(function(d, i) {
                        return { name: flattenedActiveTimerNames[i], ms: d };
                      }).map(function(d) {
                        return "".concat(d.name, ": ").concat(d.ms);
                      }).join(", ");
                    };
                    return [3, 3];
                  case 2:
                    res["kernelMs"] = {
                      error: "WebGL query timers are not supported in this environment."
                    };
                    _b.label = 3;
                  case 3:
                    this.uploadWaitMs = 0;
                    this.downloadWaitMs = 0;
                    return [2, res];
                }
              });
            });
          }();
        };
        MathBackendWebGL2.prototype.memory = function() {
          return {
            unreliable: false,
            numBytesInGPU: this.numBytesInGPU,
            numBytesInGPUAllocated: this.textureManager.numBytesAllocated,
            numBytesInGPUFree: this.textureManager.numBytesFree
          };
        };
        MathBackendWebGL2.prototype.startTimer = function() {
          if (tf.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0) {
            return this.gpgpu.beginQuery();
          }
          return { startMs: tf.util.now(), endMs: null };
        };
        MathBackendWebGL2.prototype.endTimer = function(query) {
          if (tf.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0) {
            this.gpgpu.endQuery();
            return query;
          }
          query.endMs = tf.util.now();
          return query;
        };
        MathBackendWebGL2.prototype.getQueryTime = function(query) {
          return __awaiter(this, void 0, void 0, function() {
            var timerQuery;
            return __generator(this, function(_b) {
              if (tf.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0) {
                return [2, this.gpgpu.waitForQueryAndGetTime(query)];
              }
              timerQuery = query;
              return [2, timerQuery.endMs - timerQuery.startMs];
            });
          });
        };
        MathBackendWebGL2.prototype.disposeData = function(dataId, force) {
          if (force === void 0) {
            force = false;
          }
          if (this.pendingDisposal.has(dataId)) {
            return false;
          }
          if (!this.texData.has(dataId)) {
            return true;
          }
          if (force) {
            this.texData.get(dataId).refCount = 0;
          } else {
            this.texData.get(dataId).refCount--;
          }
          if (!force && this.texData.get(dataId).refCount > 0) {
            return false;
          }
          if (this.pendingRead.has(dataId)) {
            this.pendingDisposal.add(dataId);
            this.pendingDeletes++;
            return false;
          }
          this.releaseGPUData(dataId);
          var complexTensorInfos = this.texData.get(dataId).complexTensorInfos;
          if (complexTensorInfos != null) {
            this.disposeData(complexTensorInfos.real.dataId, force);
            this.disposeData(complexTensorInfos.imag.dataId, force);
          }
          this.texData.delete(dataId);
          return true;
        };
        MathBackendWebGL2.prototype.releaseGPUData = function(dataId) {
          var _b = this.texData.get(dataId), texture = _b.texture, dtype = _b.dtype, texShape = _b.texShape, usage = _b.usage, isPacked = _b.isPacked, slice2 = _b.slice;
          var key = slice2 && slice2.origDataId || dataId;
          var refCount = this.dataRefCount.get(key);
          if (refCount > 1) {
            this.dataRefCount.set(key, refCount - 1);
          } else {
            this.dataRefCount.delete(key);
            if (texture != null) {
              this.numBytesInGPU -= this.computeBytes(texShape, dtype);
              this.textureManager.releaseTexture(texture, texShape, usage, isPacked);
            }
          }
          var texData = this.texData.get(dataId);
          texData.texture = null;
          texData.texShape = null;
          texData.isPacked = false;
          texData.slice = null;
        };
        MathBackendWebGL2.prototype.getTexture = function(dataId) {
          this.uploadToGPU(dataId);
          return this.texData.get(dataId).texture.texture;
        };
        MathBackendWebGL2.prototype.getDataInfo = function(dataId) {
          return this.texData.get(dataId);
        };
        MathBackendWebGL2.prototype.shouldExecuteOnCPU = function(inputs, sizeThreshold) {
          var _this = this;
          if (sizeThreshold === void 0) {
            sizeThreshold = CPU_HANDOFF_SIZE_THRESHOLD;
          }
          return tf.env().getBool("WEBGL_CPU_FORWARD") && inputs.every(function(input) {
            return _this.texData.get(input.dataId).texture == null && tf.util.sizeFromShape(input.shape) < sizeThreshold;
          });
        };
        MathBackendWebGL2.prototype.getGPGPUContext = function() {
          return this.gpgpu;
        };
        MathBackendWebGL2.prototype.where = function(condition) {
          tf.backend_util.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");
          var condVals = condition.dataSync();
          return whereImpl(condition.shape, condVals);
        };
        MathBackendWebGL2.prototype.packedUnaryOp = function(x, op, dtype) {
          var program = new UnaryOpPackedProgram(x.shape, op);
          var outInfo = this.compileAndRun(program, [x], dtype);
          return tf.engine().makeTensorFromTensorInfo(outInfo);
        };
        MathBackendWebGL2.prototype.abs = function(x) {
          if (this.shouldExecuteOnCPU([x]) && x.dtype !== "complex64") {
            var outValues = simpleAbsImplCPU(this.texData.get(x.dataId).values);
            return this.makeOutput(x.shape, x.dtype, outValues);
          }
          if (tf.env().getBool("WEBGL_PACK_UNARY_OPERATIONS")) {
            return this.packedUnaryOp(x, ABS$1, x.dtype);
          }
          var program = new UnaryOpProgram(x.shape, ABS$1);
          var outInfo = this.compileAndRun(program, [x]);
          return tf.engine().makeTensorFromTensorInfo(outInfo);
        };
        MathBackendWebGL2.prototype.makeTensorInfo = function(shape, dtype, values) {
          var dataId;
          if (dtype === "string" && values != null && values.length > 0 && tf.util.isString(values[0])) {
            var encodedValues = values.map(function(d) {
              return tf.util.encodeString(d);
            });
            dataId = this.write(encodedValues, shape, dtype);
          } else {
            dataId = this.write(values, shape, dtype);
          }
          this.texData.get(dataId).usage = null;
          return { dataId, shape, dtype };
        };
        MathBackendWebGL2.prototype.makeOutput = function(shape, dtype, values) {
          return tf.engine().makeTensorFromTensorInfo(this.makeTensorInfo(shape, dtype, values), this);
        };
        MathBackendWebGL2.prototype.unpackTensor = function(input) {
          var program = new UnpackProgram(input.shape);
          return this.runWebGLProgram(program, [input], input.dtype);
        };
        MathBackendWebGL2.prototype.packTensor = function(input) {
          var program = new PackProgram(input.shape);
          var preventEagerUnpackingOutput = true;
          return this.runWebGLProgram(program, [input], input.dtype, null, preventEagerUnpackingOutput);
        };
        MathBackendWebGL2.prototype.packedReshape = function(input, afterShape) {
          var input3DShape = __spreadArray([
            getBatchDim(input.shape)
          ], __read(getRowsCols(input.shape)), false);
          var input3D = {
            dtype: input.dtype,
            shape: input3DShape,
            dataId: input.dataId
          };
          var afterShapeAs3D = __spreadArray([
            getBatchDim(afterShape)
          ], __read(getRowsCols(afterShape)), false);
          var program = new ReshapePackedProgram(afterShapeAs3D, input3DShape);
          var preventEagerUnpackingOfOutput = true;
          var customValues = [input3DShape];
          var output = this.runWebGLProgram(program, [input3D], input.dtype, customValues, preventEagerUnpackingOfOutput);
          return { dataId: output.dataId, shape: afterShape, dtype: output.dtype };
        };
        MathBackendWebGL2.prototype.decode = function(dataId, customTexShape) {
          var texData = this.texData.get(dataId);
          var isPacked = texData.isPacked, shape = texData.shape, dtype = texData.dtype;
          if (customTexShape != null) {
            var size = tf.util.sizeFromShape(shape);
            var texSize = customTexShape[0] * customTexShape[1] * 4;
            tf.util.assert(size <= texSize, function() {
              return "customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.";
            });
          }
          var shapeAs3D = getShapeAs3D(shape);
          var program;
          if (isPacked) {
            program = new DecodeMatrixPackedProgram(shapeAs3D);
          } else {
            program = new DecodeMatrixProgram(shapeAs3D);
          }
          var preventEagerUnpackingOfOutput = true;
          var customValues = [customTexShape != null ? customTexShape : getDenseTexShape(shapeAs3D)];
          var out = this.runWebGLProgram(program, [{ shape: shapeAs3D, dtype, dataId }], dtype, customValues, preventEagerUnpackingOfOutput, customTexShape);
          return { dtype, shape, dataId: out.dataId };
        };
        MathBackendWebGL2.prototype.runWebGLProgram = function(program, inputs, outputDtype, customUniformValues, preventEagerUnpackingOfOutput, customTexShape) {
          var _this = this;
          if (preventEagerUnpackingOfOutput === void 0) {
            preventEagerUnpackingOfOutput = false;
          }
          var output = this.makeTensorInfo(program.outputShape, outputDtype);
          var outData = this.texData.get(output.dataId);
          if (program.packedOutput) {
            outData.isPacked = true;
          }
          if (program.outPackingScheme === PackingScheme.DENSE) {
            var texelShape = customTexShape != null ? customTexShape : getDenseTexShape(program.outputShape);
            outData.texShape = texelShape.map(function(d) {
              return d * 2;
            });
          }
          if (program.outTexUsage != null) {
            outData.usage = program.outTexUsage;
          }
          if (tf.util.sizeFromShape(output.shape) === 0) {
            outData.values = tf.util.getTypedArrayFromDType(output.dtype, 0);
            return output;
          }
          var dataToDispose = [];
          var inputsData = inputs.map(function(input) {
            if (input.dtype === "complex64") {
              throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");
            }
            var texData = _this.texData.get(input.dataId);
            if (texData.texture == null) {
              if (!program.packedInputs && tf.util.sizeFromShape(input.shape) <= tf.env().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM")) {
                return {
                  shape: input.shape,
                  texData: null,
                  isUniform: true,
                  uniformValues: texData.values
                };
              }
              if (program.packedInputs) {
                texData.isPacked = true;
                texData.shape = input.shape;
              }
            }
            _this.uploadToGPU(input.dataId);
            if (!!texData.isPacked !== !!program.packedInputs) {
              input = texData.isPacked ? _this.unpackTensor(input) : _this.packTensor(input);
              dataToDispose.push(input);
              texData = _this.texData.get(input.dataId);
            } else if (texData.isPacked && !isReshapeFree(texData.shape, input.shape)) {
              var savedInput = input;
              var targetShape = input.shape;
              input.shape = texData.shape;
              input = _this.packedReshape(input, targetShape);
              dataToDispose.push(input);
              texData = _this.texData.get(input.dataId);
              savedInput.shape = targetShape;
            }
            return { shape: input.shape, texData, isUniform: false };
          });
          this.uploadToGPU(output.dataId);
          var outputData = { shape: output.shape, texData: outData, isUniform: false };
          var key = makeShaderKey(program, inputsData, outputData);
          var binary = this.getAndSaveBinary(key, function() {
            return compileProgram(_this.gpgpu, program, inputsData, outputData);
          });
          var shouldTimeProgram = this.activeTimers != null;
          var query;
          if (shouldTimeProgram) {
            query = this.startTimer();
          }
          if (!tf.env().get("ENGINE_COMPILE_ONLY")) {
            runProgram(this.gpgpu, binary, inputsData, outputData, customUniformValues);
          }
          dataToDispose.forEach(function(info) {
            return _this.disposeIntermediateTensorInfo(info);
          });
          if (shouldTimeProgram) {
            query = this.endTimer(query);
            this.activeTimers.push({ name: program.constructor.name, query: this.getQueryTime(query) });
          }
          var glFlushThreshold = tf.env().getNumber("WEBGL_FLUSH_THRESHOLD");
          if (glFlushThreshold > 0) {
            var time = tf.util.now();
            if (time - this.lastGlFlushTime > glFlushThreshold) {
              this.gpgpu.gl.flush();
              this.lastGlFlushTime = time;
            }
          }
          if (!tf.env().getBool("WEBGL_LAZILY_UNPACK") && outData.isPacked && preventEagerUnpackingOfOutput === false) {
            var unpacked = this.unpackTensor(output);
            this.disposeIntermediateTensorInfo(output);
            return unpacked;
          }
          return output;
        };
        MathBackendWebGL2.prototype.compileAndRun = function(program, inputs, outputDtype, customUniformValues, preventEagerUnpackingOfOutput) {
          if (preventEagerUnpackingOfOutput === void 0) {
            preventEagerUnpackingOfOutput = false;
          }
          outputDtype = outputDtype || inputs[0].dtype;
          var outInfo = this.runWebGLProgram(program, inputs, outputDtype, customUniformValues, preventEagerUnpackingOfOutput);
          return outInfo;
        };
        MathBackendWebGL2.prototype.getAndSaveBinary = function(key, getBinary) {
          if (!(key in this.binaryCache)) {
            this.binaryCache[key] = getBinary();
          }
          return this.binaryCache[key];
        };
        MathBackendWebGL2.prototype.getTextureManager = function() {
          return this.textureManager;
        };
        MathBackendWebGL2.prototype.dispose = function() {
          var _this = this;
          if (this.disposed) {
            return;
          }
          if (!tf.env().getBool("IS_TEST")) {
            var allKeys = Object.keys(this.binaryCache);
            allKeys.forEach(function(key) {
              _this.gpgpu.deleteProgram(_this.binaryCache[key].webGLProgram);
              delete _this.binaryCache[key];
            });
          }
          this.textureManager.dispose();
          if (this.canvas != null && (typeof HTMLCanvasElement !== "undefined" && this.canvas instanceof HTMLCanvasElement)) {
            this.canvas.remove();
          } else {
            this.canvas = null;
          }
          if (this.gpgpuCreatedLocally) {
            this.gpgpu.program = null;
            this.gpgpu.dispose();
          }
          this.disposed = true;
        };
        MathBackendWebGL2.prototype.floatPrecision = function() {
          var _this = this;
          if (this.floatPrecisionValue == null) {
            this.floatPrecisionValue = tf.tidy(function() {
              if (!tf.env().get("WEBGL_RENDER_FLOAT32_ENABLED")) {
                var debugFlag = tf.env().getBool("DEBUG");
                tf.env().set("DEBUG", false);
                var underflowCheckValue = _this.abs(tf.scalar(1e-8)).dataSync()[0];
                tf.env().set("DEBUG", debugFlag);
                if (underflowCheckValue > 0) {
                  return 32;
                }
              }
              return 16;
            });
          }
          return this.floatPrecisionValue;
        };
        MathBackendWebGL2.prototype.epsilon = function() {
          return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;
        };
        MathBackendWebGL2.prototype.uploadToGPU = function(dataId) {
          var _b;
          var texData = this.texData.get(dataId);
          var shape = texData.shape, dtype = texData.dtype, values = texData.values, texture = texData.texture, usage = texData.usage, isPacked = texData.isPacked;
          if (texture != null) {
            return;
          }
          var shouldTimeProgram = this.activeTimers != null;
          var start;
          if (shouldTimeProgram) {
            start = tf.util.now();
          }
          var texShape = texData.texShape;
          if (texShape == null) {
            texShape = getTextureShapeFromLogicalShape(shape, isPacked);
            texData.texShape = texShape;
          }
          if (values != null) {
            var shapeAs3D = getShapeAs3D(shape);
            var program = void 0;
            var width = texShape[1], height = texShape[0];
            var isByteArray = values instanceof Uint8Array || values instanceof Uint8ClampedArray;
            if (isPacked || !isByteArray) {
              _b = __read(getPackedMatrixTextureShapeWidthHeight(texShape[0], texShape[1]), 2), width = _b[0], height = _b[1];
            }
            if (isPacked) {
              program = new EncodeMatrixPackedProgram(shapeAs3D, isByteArray);
            } else {
              program = new EncodeMatrixProgram(shapeAs3D, isByteArray);
            }
            var tempDenseInputTexShape = isByteArray ? [height, width] : texShape;
            var tempDenseInputHandle = this.makeTensorInfo(tempDenseInputTexShape, dtype);
            var tempDenseInputTexData = this.texData.get(tempDenseInputHandle.dataId);
            if (isByteArray) {
              tempDenseInputTexData.usage = TextureUsage.PIXELS;
            } else {
              tempDenseInputTexData.usage = TextureUsage.UPLOAD;
            }
            tempDenseInputTexData.texShape = tempDenseInputTexShape;
            this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(tempDenseInputHandle.dataId), width, height, values);
            var customValues = [[height, width]];
            var preventEagerUnpacking = true;
            var encodedOutputTarget = this.runWebGLProgram(program, [tempDenseInputHandle], dtype, customValues, preventEagerUnpacking);
            var outputTexData = this.texData.get(encodedOutputTarget.dataId);
            texData.texShape = outputTexData.texShape;
            texData.isPacked = outputTexData.isPacked;
            texData.usage = outputTexData.usage;
            if (!tf.env().get("ENGINE_COMPILE_ONLY")) {
              texData.texture = outputTexData.texture;
              texData.values = null;
              this.texData.delete(encodedOutputTarget.dataId);
            } else {
              this.disposeData(encodedOutputTarget.dataId);
            }
            this.disposeIntermediateTensorInfo(tempDenseInputHandle);
            if (shouldTimeProgram) {
              this.uploadWaitMs += tf.util.now() - start;
            }
          } else {
            var newTexture = this.acquireTexture(texShape, usage, dtype, isPacked);
            texData.texture = newTexture;
          }
        };
        MathBackendWebGL2.prototype.convertAndCacheOnCPU = function(dataId, float32Values) {
          var texData = this.texData.get(dataId);
          var dtype = texData.dtype;
          if (float32Values != null) {
            texData.values = float32ToTypedArray(float32Values, dtype);
          }
          return texData.values;
        };
        MathBackendWebGL2.prototype.acquireTexture = function(texShape, texType, dtype, isPacked) {
          this.numBytesInGPU += this.computeBytes(texShape, dtype);
          if (!this.warnedAboutMemory && this.numBytesInGPU > this.numMBBeforeWarning * 1024 * 1024) {
            var mb = (this.numBytesInGPU / 1024 / 1024).toFixed(2);
            this.warnedAboutMemory = true;
            console.warn("High memory usage in GPU: ".concat(mb, " MB, ") + "most likely due to a memory leak");
          }
          return this.textureManager.acquireTexture(texShape, texType, isPacked);
        };
        MathBackendWebGL2.prototype.computeBytes = function(shape, dtype) {
          return shape[0] * shape[1] * tf.util.bytesPerElement(dtype);
        };
        MathBackendWebGL2.prototype.checkCompileCompletion = function() {
          var e_12, _b;
          try {
            for (var _c = __values(Object.entries(this.binaryCache)), _d = _c.next(); !_d.done; _d = _c.next()) {
              var _e = __read(_d.value, 2), binary = _e[1];
              this.checkCompletion_(binary);
            }
          } catch (e_1_1) {
            e_12 = { error: e_1_1 };
          } finally {
            try {
              if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
            } finally {
              if (e_12) throw e_12.error;
            }
          }
        };
        MathBackendWebGL2.prototype.checkCompileCompletionAsync = function() {
          return __awaiter(this, void 0, void 0, function() {
            var ps, _b, _c, _d, binary, _loop_1, _e, _f, _g, binary;
            var e_2, _h, e_3, _j;
            var _this = this;
            return __generator(this, function(_k) {
              ps = [];
              if (this.gpgpu.parallelCompilationExtension) {
                try {
                  for (_b = __values(Object.entries(this.binaryCache)), _c = _b.next(); !_c.done; _c = _b.next()) {
                    _d = __read(_c.value, 2), binary = _d[1];
                    ps.push(this.checkCompletionAsync_(binary));
                  }
                } catch (e_2_1) {
                  e_2 = { error: e_2_1 };
                } finally {
                  try {
                    if (_c && !_c.done && (_h = _b.return)) _h.call(_b);
                  } finally {
                    if (e_2) throw e_2.error;
                  }
                }
                return [2, Promise.all(ps)];
              } else {
                _loop_1 = function(binary2) {
                  var p = new Promise(function(resolve) {
                    try {
                      _this.checkCompletion_(binary2);
                      resolve(true);
                    } catch (error) {
                      throw error;
                    }
                  });
                  ps.push(p);
                };
                try {
                  for (_e = __values(Object.entries(this.binaryCache)), _f = _e.next(); !_f.done; _f = _e.next()) {
                    _g = __read(_f.value, 2), binary = _g[1];
                    _loop_1(binary);
                  }
                } catch (e_3_1) {
                  e_3 = { error: e_3_1 };
                } finally {
                  try {
                    if (_f && !_f.done && (_j = _e.return)) _j.call(_e);
                  } finally {
                    if (e_3) throw e_3.error;
                  }
                }
                return [2, Promise.all(ps)];
              }
            });
          });
        };
        MathBackendWebGL2.prototype.checkCompletionAsync_ = function(binary) {
          return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  if (!this.gpgpu.gl.getProgramParameter(binary.webGLProgram, this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)) return [3, 1];
                  return [2, this.checkCompletion_(binary)];
                case 1:
                  return [4, tf.nextFrame()];
                case 2:
                  _b.sent();
                  return [2, this.checkCompletionAsync_(binary)];
              }
            });
          });
        };
        MathBackendWebGL2.prototype.checkCompletion_ = function(binary) {
          if (this.gpgpu.gl.getProgramParameter(binary.webGLProgram, this.gpgpu.gl.LINK_STATUS) === false) {
            console.log(this.gpgpu.gl.getProgramInfoLog(binary.webGLProgram));
            if (this.gpgpu.gl.getShaderParameter(binary.fragmentShader, this.gpgpu.gl.COMPILE_STATUS) === false) {
              logShaderSourceAndInfoLog(binary.source, this.gpgpu.gl.getShaderInfoLog(binary.fragmentShader));
              throw new Error("Failed to compile fragment shader.");
            }
            throw new Error("Failed to link vertex and fragment shaders.");
          }
          return true;
        };
        MathBackendWebGL2.prototype.getUniformLocations = function() {
          var e_4, _b;
          try {
            for (var _c = __values(Object.values(this.binaryCache)), _d = _c.next(); !_d.done; _d = _c.next()) {
              var binary = _d.value;
              this.gpgpu.buildVao(binary.webGLProgram);
              var _e = getUniformLocations(this.gpgpu, binary.program, binary.webGLProgram), variablesLocations = _e.variablesLocations, customUniformLocations = _e.customUniformLocations, infLoc = _e.infLoc, nanLoc = _e.nanLoc, outShapeLocation = _e.outShapeLocation, outShapeStridesLocation = _e.outShapeStridesLocation, outTexShapeLocation = _e.outTexShapeLocation;
              binary.variablesLocations = variablesLocations;
              binary.customUniformLocations = customUniformLocations;
              binary.infLoc = infLoc;
              binary.nanLoc = nanLoc;
              binary.outShapeLocation = outShapeLocation;
              binary.outShapeStridesLocation = outShapeStridesLocation;
              binary.outTexShapeLocation = outTexShapeLocation;
            }
          } catch (e_4_1) {
            e_4 = { error: e_4_1 };
          } finally {
            try {
              if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
            } finally {
              if (e_4) throw e_4.error;
            }
          }
        };
        MathBackendWebGL2.prototype.createTensorFromGPUData = function(values, shape, dtype) {
          values.channels = values.channels || "RGBA";
          var texture = values.texture, height = values.height, width = values.width, channels = values.channels;
          var backend = tf.engine().backend;
          if (!backend.gpgpu.gl.isTexture(texture)) {
            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)'.");
          }
          var dataId = backend.writeTexture(texture, shape, dtype, height, width, channels);
          return tf.engine().makeTensorFromDataId(dataId, shape, dtype, backend);
        };
        return MathBackendWebGL2;
      }(tf.KernelBackend)
    );
    MathBackendWebGL.nextDataId = 0;
    function float32ToTypedArray(a, dtype) {
      if (dtype === "float32" || dtype === "complex64") {
        return a;
      } else if (dtype === "int32" || dtype === "bool") {
        var result = dtype === "int32" ? new Int32Array(a.length) : new Uint8Array(a.length);
        for (var i = 0; i < result.length; ++i) {
          result[i] = Math.round(a[i]);
        }
        return result;
      } else {
        throw new Error("Unknown dtype ".concat(dtype));
      }
    }
    var version = "4.22.0";
    function forceHalfFloat() {
      tf.env().set("WEBGL_FORCE_F16_TEXTURES", true);
    }
    if (tf.device_util.isBrowser()) {
      tf.registerBackend(
        "webgl",
        function() {
          return new MathBackendWebGL();
        },
        2
        /* priority */
      );
    }
    var webgl = { forceHalfFloat };
    var CHECK_NAN_SNIPPET = "\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n";
    var BinaryOpProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function BinaryOpProgram2(op, aShape, bShape) {
          this.variableNames = ["A", "B"];
          this.outputShape = tf.backend_util.assertAndGetBroadcastShape(aShape, bShape);
          this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);
          this.userCode = "\n      float binaryOperation(float a, float b) {\n        ".concat(op, "\n      }\n\n      void main() {\n        float a = getAAtOutCoords();\n        float b = getBAtOutCoords();\n        setOutput(binaryOperation(a, b));\n      }\n    ");
        }
        return BinaryOpProgram2;
      }()
    );
    var CHECK_NAN_SNIPPET_PACKED = "\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";
    var BinaryOpPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function BinaryOpPackedProgram2(op, aShape, bShape, checkOutOfBounds) {
          if (checkOutOfBounds === void 0) {
            checkOutOfBounds = false;
          }
          this.variableNames = ["A", "B"];
          this.supportsBroadcasting = true;
          this.packedInputs = true;
          this.packedOutput = true;
          this.outputShape = tf.backend_util.assertAndGetBroadcastShape(aShape, bShape);
          var rank = this.outputShape.length;
          this.enableShapeUniforms = useShapeUniforms(rank);
          var checkOutOfBoundsString = "";
          if (checkOutOfBounds) {
            if (rank === 0 || tf.util.sizeFromShape(this.outputShape) === 1) {
              checkOutOfBoundsString = "\n          result.y = 0.;\n          result.z = 0.;\n          result.w = 0.;\n        ";
            } else {
              var dtype = getCoordsDataType(rank);
              checkOutOfBoundsString = "\n          ".concat(dtype, " coords = getOutputCoords();\n        ");
              if (rank === 1) {
                if (this.enableShapeUniforms) {
                  checkOutOfBoundsString += "\n            result.y = (coords + 1) >= outShape ? 0. : result.y;\n            result.z = 0.;\n            result.w = 0.;\n          ";
                } else {
                  checkOutOfBoundsString += "\n            result.y = (coords + 1) >= ".concat(this.outputShape[0], " ? 0. : result.y;\n            result.z = 0.;\n            result.w = 0.;\n          ");
                }
              } else {
                var channels = getChannels("coords", rank);
                if (this.enableShapeUniforms) {
                  checkOutOfBoundsString += "\n            bool nextRowOutOfBounds =\n              (".concat(channels[rank - 2], " + 1) >= outShape[").concat(rank, " - 2];\n            bool nextColOutOfBounds =\n              (").concat(channels[rank - 1], " + 1) >= outShape[").concat(rank, " - 1];\n            result.y = nextColOutOfBounds ? 0. : result.y;\n            result.z = nextRowOutOfBounds ? 0. : result.z;\n            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n          ");
                } else {
                  checkOutOfBoundsString += "\n            bool nextRowOutOfBounds =\n              (".concat(channels[rank - 2], " + 1) >= ").concat(this.outputShape[rank - 2], ";\n            bool nextColOutOfBounds =\n              (").concat(channels[rank - 1], " + 1) >= ").concat(this.outputShape[rank - 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        ".concat(op, "\n      }\n\n      void main() {\n        vec4 a = getAAtOutCoords();\n        vec4 b = getBAtOutCoords();\n\n        vec4 result = binaryOperation(a, b);\n        ").concat(checkOutOfBoundsString, "\n\n        setOutput(result);\n      }\n    ");
        }
        return BinaryOpPackedProgram2;
      }()
    );
    function identity(args) {
      var inputs = args.inputs, backend = args.backend;
      var x = inputs.x;
      backend.incRef(x.dataId);
      return { dataId: x.dataId, shape: x.shape, dtype: x.dtype };
    }
    var identityConfig = {
      kernelName: tf.Identity,
      backendName: "webgl",
      kernelFunc: identity
    };
    function complex(args) {
      var inputs = args.inputs, backend = args.backend;
      var real2 = inputs.real, imag2 = inputs.imag;
      var complexInfo = backend.makeTensorInfo(real2.shape, "complex64");
      var complex2 = backend.texData.get(complexInfo.dataId);
      var realTensorInfo = identity({ inputs: { x: real2 }, backend });
      var imagTensorInfo = identity({ inputs: { x: imag2 }, backend });
      complex2.complexTensorInfos = { real: realTensorInfo, imag: imagTensorInfo };
      return complexInfo;
    }
    var complexConfig = {
      kernelName: tf.Complex,
      backendName: "webgl",
      kernelFunc: complex
    };
    var LEAKYRELU = "return (a < 0.) ? b * a : a;";
    var LEAKYRELU_PACKED = "\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";
    function leakyRelu(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var alpha = attrs.alpha;
      var $alpha = backend.makeTensorInfo([], "float32", tf.util.createScalarValue(alpha, "float32"));
      var program = tf.env().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new BinaryOpPackedProgram(LEAKYRELU_PACKED, x.shape, $alpha.shape) : new BinaryOpProgram(LEAKYRELU, x.shape, $alpha.shape);
      var result = backend.runWebGLProgram(program, [x, $alpha], "float32");
      backend.disposeIntermediateTensorInfo($alpha);
      return result;
    }
    var leakyReluConfig = {
      kernelName: tf.LeakyRelu,
      backendName: "webgl",
      kernelFunc: leakyRelu
    };
    var PRELU = "return (a < 0.) ? b * a : a;";
    var PRELU_PACKED = "\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";
    function prelu(args) {
      var inputs = args.inputs, backend = args.backend;
      var x = inputs.x, alpha = inputs.alpha;
      var program = tf.env().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new BinaryOpPackedProgram(PRELU_PACKED, x.shape, alpha.shape) : new BinaryOpProgram(PRELU, x.shape, alpha.shape);
      return backend.runWebGLProgram(program, [x, alpha], "float32");
    }
    var preluConfig = {
      kernelName: tf.Prelu,
      backendName: "webgl",
      kernelFunc: prelu
    };
    var CHECK_NAN_SNIPPET_UNARY = "if (isnan(x)) return x;";
    function unaryKernelFunc(_a2) {
      var opSnippet = _a2.opSnippet, packedOpSnippet = _a2.packedOpSnippet, cpuKernelImpl = _a2.cpuKernelImpl, dtype = _a2.dtype;
      return function(_a3) {
        var inputs = _a3.inputs, backend = _a3.backend;
        var x = inputs.x;
        var webglBackend = backend;
        var $dtype = dtype || x.dtype;
        if (webglBackend.shouldExecuteOnCPU([x]) && cpuKernelImpl != null) {
          var xData = webglBackend.texData.get(x.dataId);
          var outValues = cpuKernelImpl(xData.values, $dtype);
          return webglBackend.makeTensorInfo(x.shape, $dtype, outValues);
        }
        var shouldUsePackedProgram = tf.env().getBool("WEBGL_PACK_UNARY_OPERATIONS") && packedOpSnippet != null;
        var program;
        if (shouldUsePackedProgram) {
          program = new UnaryOpPackedProgram(x.shape, packedOpSnippet);
        } else {
          program = new UnaryOpProgram(x.shape, opSnippet);
        }
        return webglBackend.runWebGLProgram(program, [x], $dtype);
      };
    }
    function binaryKernelFunc(_a2) {
      var opSnippet = _a2.opSnippet, packedOpSnippet = _a2.packedOpSnippet, _b = _a2.checkOutOfBounds, checkOutOfBounds = _b === void 0 ? false : _b, _c = _a2.supportsComplex, supportsComplex = _c === void 0 ? false : _c, cpuKernelImpl = _a2.cpuKernelImpl, dtype = _a2.dtype;
      return function(_a3) {
        var inputs = _a3.inputs, backend = _a3.backend;
        var a = inputs.a, b = inputs.b;
        var webglBackend = backend;
        if (supportsComplex && a.dtype === "complex64") {
          var aData = webglBackend.texData.get(a.dataId);
          var bData = webglBackend.texData.get(b.dataId);
          var _b2 = __read([
            [aData.complexTensorInfos.real, bData.complexTensorInfos.real],
            [aData.complexTensorInfos.imag, bData.complexTensorInfos.imag]
          ].map(function(complexParts) {
            var _a4 = __read(complexParts, 2), aPart = _a4[0], bPart = _a4[1];
            var aHandle = {
              dataId: aPart.dataId,
              dtype: aPart.dtype,
              shape: a.shape
            };
            var bHandle = {
              dataId: bPart.dataId,
              dtype: bPart.dtype,
              shape: b.shape
            };
            var program2 = new BinaryOpProgram(opSnippet, a.shape, b.shape);
            return webglBackend.runWebGLProgram(program2, [aHandle, bHandle], tf.upcastType(aPart.dtype, bPart.dtype));
          }), 2), real2 = _b2[0], imag2 = _b2[1];
          var complexOutput = complex({ inputs: { real: real2, imag: imag2 }, backend: webglBackend });
          webglBackend.disposeIntermediateTensorInfo(real2);
          webglBackend.disposeIntermediateTensorInfo(imag2);
          return complexOutput;
        }
        var $dtype = dtype || tf.upcastType(a.dtype, b.dtype);
        if ((a.dtype === "string" || b.dtype === "string" || webglBackend.shouldExecuteOnCPU([a, b])) && cpuKernelImpl != null) {
          var aVals = webglBackend.texData.get(a.dataId).values;
          var bVals = webglBackend.texData.get(b.dataId).values;
          var decodedAVals = a.dtype === "string" ? (
            // tslint:disable-next-line: no-any
            tf.backend_util.fromUint8ToStringArray(aVals)
          ) : aVals;
          var decodedBVals = a.dtype === "string" ? (
            // tslint:disable-next-line: no-any
            tf.backend_util.fromUint8ToStringArray(bVals)
          ) : bVals;
          var _c2 = __read(cpuKernelImpl(a.shape, b.shape, decodedAVals, decodedBVals, $dtype), 2), outValues = _c2[0], outShape = _c2[1];
          var out = webglBackend.makeTensorInfo(outShape, $dtype);
          var outData = webglBackend.texData.get(out.dataId);
          outData.values = outValues;
          return out;
        }
        var shouldUsePackedProgram = tf.env().getBool("WEBGL_PACK_BINARY_OPERATIONS") && packedOpSnippet != null;
        var program;
        if (shouldUsePackedProgram) {
          program = new BinaryOpPackedProgram(packedOpSnippet, a.shape, b.shape, checkOutOfBounds);
        } else {
          program = new BinaryOpProgram(opSnippet, a.shape, b.shape);
        }
        return webglBackend.runWebGLProgram(program, [a, b], $dtype);
      };
    }
    function mapActivationToShaderProgram(activation, packed) {
      if (packed === void 0) {
        packed = false;
      }
      if (activation === "linear") {
        if (packed) {
          return LINEAR;
        }
        return LINEAR$1;
      } else if (activation === "relu") {
        if (packed) {
          return RELU$1;
        }
        return RELU$2;
      } else if (activation === "elu") {
        if (packed) {
          return ELU$1;
        }
        return ELU$2;
      } else if (activation === "relu6") {
        if (packed) {
          return RELU6$1;
        }
        return RELU6$2;
      } else if (activation === "prelu") {
        if (packed) {
          return PRELU_PACKED;
        }
        return PRELU;
      } else if (activation === "leakyrelu") {
        if (packed) {
          return LEAKYRELU_PACKED;
        }
        return LEAKYRELU;
      } else if (activation === "sigmoid") {
        if (packed) {
          return SIGMOID$1;
        }
        return SIGMOID$2;
      }
      throw new Error("Activation ".concat(activation, " has not been implemented for the WebGL backend."));
    }
    var MatMulPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function MatMulPackedProgram2(aShape, bShape, outputShape, transposeA, transposeB, addBias, activation, hasPreluActivation, hasLeakyreluActivation) {
          if (transposeA === void 0) {
            transposeA = false;
          }
          if (transposeB === void 0) {
            transposeB = false;
          }
          if (addBias === void 0) {
            addBias = false;
          }
          if (activation === void 0) {
            activation = null;
          }
          if (hasPreluActivation === void 0) {
            hasPreluActivation = false;
          }
          if (hasLeakyreluActivation === void 0) {
            hasLeakyreluActivation = false;
          }
          this.variableNames = ["matrixA", "matrixB"];
          this.packedInputs = true;
          this.packedOutput = true;
          this.outputShape = outputShape;
          this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);
          var sharedDim = transposeA ? aShape[1] : aShape[2];
          var sharedDimensionPacked = Math.ceil(sharedDim / 2);
          var aSample = transposeA ? "i * 2, rc.y" : "rc.y, i * 2";
          var bSample = transposeB ? "rc.z, i * 2" : "i * 2, rc.z";
          var aSwizzle = transposeA ? ["a.xxyy", "a.zzww"] : ["a.xxzz", "a.yyww"];
          var bSwizzle = transposeB ? ["b.xzxz", "b.ywyw"] : ["b.xyxy", "b.zwzw"];
          var activationSnippet = "", applyActivationSnippet = "";
          if (activation) {
            if (hasPreluActivation) {
              activationSnippet = "vec4 activation(vec4 a) {\n          vec4 b = getPreluActivationWeightsAtOutCoords();\n          ".concat(activation, "\n        }");
            } else if (hasLeakyreluActivation) {
              activationSnippet = "vec4 activation(vec4 a) {\n          vec4 b = getLeakyreluAlphaAtOutCoords();\n          ".concat(activation, "\n        }");
            } else {
              activationSnippet = "vec4 activation(vec4 x) {\n          ".concat(activation, "\n        }");
            }
            applyActivationSnippet = "result = activation(result);";
          }
          var addBiasSnippet = addBias ? "result += getBiasAtOutCoords();" : "";
          if (addBias) {
            this.variableNames.push("bias");
          }
          if (hasPreluActivation) {
            this.variableNames.push("preluActivationWeights");
          }
          if (hasLeakyreluActivation) {
            this.variableNames.push("leakyreluAlpha");
          }
          var batchASnippet = "rc.x";
          var batchBSnippet = "rc.x";
          if (aShape[0] < bShape[0]) {
            batchASnippet = "imod(rc.x, ".concat(aShape[0], ")");
          } else if (bShape[0] < aShape[0]) {
            batchBSnippet = "imod(rc.x, ".concat(bShape[0], ")");
          }
          this.userCode = "\n      ".concat(activationSnippet, "\n      // Don't use uniform for sharedDimensionPacked for performance.\n      const float sharedDimension = ").concat(sharedDimensionPacked, ".0;\n\n      vec4 dot2x2ARowBCol(ivec3 rc) {\n        vec4 result = vec4(0);\n        int batchA = ").concat(batchASnippet, ";\n        int batchB = ").concat(batchBSnippet, ";\n        for (int i = 0; i < ").concat(sharedDimensionPacked, "; i++) {\n          vec4 a = getMatrixA(batchA, ").concat(aSample, ");\n          vec4 b = getMatrixB(batchB, ").concat(bSample, ");\n\n          // These swizzled products need to be separately added.\n          // See: https://github.com/tensorflow/tfjs/issues/1735\n          result += (").concat(aSwizzle[0], " * ").concat(bSwizzle[0], ");\n          result += (").concat(aSwizzle[1], " * ").concat(bSwizzle[1], ");\n        }\n        return result;\n      }\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n        vec4 result = dot2x2ARowBCol(rc);\n\n        ").concat(addBiasSnippet, "\n\n        ").concat(applyActivationSnippet, "\n\n        setOutput(result);\n      }\n    ");
        }
        return MatMulPackedProgram2;
      }()
    );
    var COMPLEX_MULTIPLY = {
      REAL: "return areal * breal - aimag * bimag;",
      IMAG: "return areal * bimag + aimag * breal;"
    };
    var BinaryOpComplexProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function BinaryOpComplexProgram2(op, aShape, bShape) {
          this.variableNames = ["AReal", "AImag", "BReal", "BImag"];
          this.outputShape = tf.backend_util.assertAndGetBroadcastShape(aShape, bShape);
          this.userCode = "\n      float binaryOpComplex(\n          float areal, float aimag, float breal, float bimag) {\n        ".concat(op, "\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    ");
        }
        return BinaryOpComplexProgram2;
      }()
    );
    var MUL = "return a * b;";
    function multiply(args) {
      var inputs = args.inputs, backend = args.backend;
      var a = inputs.a, b = inputs.b;
      var dtype = tf.backend_util.upcastType(a.dtype, b.dtype);
      if (a.dtype === "complex64") {
        var aData = backend.texData.get(a.dataId);
        var bData = backend.texData.get(b.dataId);
        var realProgram = new BinaryOpComplexProgram(COMPLEX_MULTIPLY.REAL, a.shape, b.shape);
        var imagProgram = new BinaryOpComplexProgram(COMPLEX_MULTIPLY.IMAG, a.shape, b.shape);
        var inputs_1 = [
          {
            dataId: aData.complexTensorInfos.real.dataId,
            dtype: aData.complexTensorInfos.real.dtype,
            shape: a.shape
          },
          {
            dataId: aData.complexTensorInfos.imag.dataId,
            dtype: aData.complexTensorInfos.imag.dtype,
            shape: a.shape
          },
          {
            dataId: bData.complexTensorInfos.real.dataId,
            dtype: bData.complexTensorInfos.real.dtype,
            shape: b.shape
          },
          {
            dataId: bData.complexTensorInfos.imag.dataId,
            dtype: bData.complexTensorInfos.imag.dtype,
            shape: b.shape
          }
        ];
        var realPart = backend.runWebGLProgram(realProgram, inputs_1, "float32");
        var imagPart = backend.runWebGLProgram(imagProgram, inputs_1, "float32");
        var complexOutput = complex({ inputs: { real: realPart, imag: imagPart }, backend });
        backend.disposeIntermediateTensorInfo(realPart);
        backend.disposeIntermediateTensorInfo(imagPart);
        return complexOutput;
      }
      if (backend.shouldExecuteOnCPU([a, b])) {
        var aData = backend.texData.get(a.dataId);
        var bData = backend.texData.get(b.dataId);
        var _a2 = __read(multiplyImplCPU(a.shape, b.shape, aData.values, bData.values, dtype), 2), outValues = _a2[0], outShape = _a2[1];
        var out = backend.makeTensorInfo(outShape, dtype);
        var outData = backend.texData.get(out.dataId);
        outData.values = outValues;
        return out;
      }
      var program;
      if (tf.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")) {
        program = new BinaryOpPackedProgram(MUL, a.shape, b.shape);
      } else {
        program = new BinaryOpProgram(MUL, a.shape, b.shape);
      }
      return backend.runWebGLProgram(program, [a, b], dtype);
    }
    var multiplyConfig = {
      kernelName: tf.Multiply,
      backendName: "webgl",
      kernelFunc: multiply
    };
    function packedReshape(input, afterShape, backend) {
      var input3DShape = __spreadArray([getBatchDim(input.shape)], __read(getRowsCols(input.shape)), false);
      var input3D = {
        dtype: input.dtype,
        shape: input3DShape,
        dataId: input.dataId
      };
      var afterShapeAs3D = __spreadArray([getBatchDim(afterShape)], __read(getRowsCols(afterShape)), false);
      var program = new ReshapePackedProgram(afterShapeAs3D, input3DShape);
      var preventEagerUnpackingOfOutput = true;
      var customValues = [input3DShape];
      var output = backend.runWebGLProgram(program, [input3D], input.dtype, customValues, preventEagerUnpackingOfOutput);
      return { dataId: output.dataId, shape: afterShape, dtype: output.dtype };
    }
    function reshape(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var shape = attrs.shape;
      var webglBackend = backend;
      var xSize = tf.util.sizeFromShape(x.shape);
      var $shape = tf.util.inferFromImplicitShape(shape, xSize);
      var $xSize = tf.util.sizeFromShape($shape);
      tf.util.assert(xSize === $xSize, function() {
        return "The new shape (".concat($shape, ") has ").concat($xSize, " elements and the old ") + "shape (".concat(x.shape, ") has ").concat(xSize, " elements. The new shape and old ") + "shape must have the same number of elements.";
      });
      var xTexData = webglBackend.texData.get(x.dataId);
      if (xTexData.isPacked && !isReshapeFree(x.shape, $shape) && !(xTexData.texture !== null && isReshapeFree(xTexData.shape, $shape))) {
        return packedReshape(x, $shape, webglBackend);
      }
      webglBackend.incRef(x.dataId);
      return { dataId: x.dataId, shape: $shape, dtype: x.dtype };
    }
    var reshapeConfig = {
      kernelName: tf.Reshape,
      backendName: "webgl",
      kernelFunc: reshape
    };
    var MeanProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function MeanProgram2(reduceInfo, divisor) {
          this.variableNames = ["x"];
          var windowSize = reduceInfo.windowSize, batchSize = reduceInfo.batchSize, inSize = reduceInfo.inSize, outSize = reduceInfo.outSize;
          this.outputShape = [batchSize, outSize];
          var windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;
          var windowSizeVec4Remainder = windowSize % 4;
          var updateSnippet = "sumValue += dot(values, ones);";
          if (divisor != null) {
            var denominator = 1 / divisor;
            updateSnippet = "sumValue += dot(values * ".concat(tf.util.isInt(denominator) ? denominator.toPrecision(2) : denominator, ", ones);");
          }
          var checkOutOfBounds = "";
          if (inSize % windowSize > 0) {
            checkOutOfBounds = "\n        if (inIdx < 0 || inIdx >= ".concat(inSize, ") {\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        ".concat(checkOutOfBounds, "\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 * ").concat(windowSize, ";\n\n        float sumValue = 0.0;\n\n        for (int i = 0; i < ").concat(windowSizeNearestVec4, "; 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          ").concat(updateSnippet, "\n        }\n\n        int inIdx = inOffset + ").concat(windowSizeNearestVec4, ";\n        if (").concat(windowSizeVec4Remainder === 1, ") {\n          vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n          ").concat(updateSnippet, "\n        } else if (").concat(windowSizeVec4Remainder === 2, ") {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1), 0.0, 0.0);\n\n          ").concat(updateSnippet, "\n        } else if (").concat(windowSizeVec4Remainder === 3, ") {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2), 0.0);\n\n          ").concat(updateSnippet, "\n        }\n        setOutput(sumValue);\n      }\n    ");
        }
        return MeanProgram2;
      }()
    );
    var ReduceProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ReduceProgram2(reduceInfo, reduceType) {
          this.variableNames = ["x"];
          var windowSize = reduceInfo.windowSize, batchSize = reduceInfo.batchSize, inSize = reduceInfo.inSize, outSize = reduceInfo.outSize;
          this.outputShape = [batchSize, outSize];
          var initializationValue = "0.0";
          var compareOp = "";
          if (reduceType === "prod") {
            initializationValue = "1.0";
          } else if (reduceType === "min") {
            initializationValue = "1.0 / 1e-20";
            compareOp = "min";
          } else if (reduceType === "max") {
            initializationValue = "-1.0 / 1e-20";
            compareOp = "max";
          }
          var returnValue = "".concat(reduceType, "(").concat(reduceType, "(").concat(reduceType, "(") + "minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";
          if (reduceType === "sum") {
            returnValue = "sumValue";
          } else if (reduceType === "prod") {
            returnValue = "prodValue";
          } else if (reduceType === "all") {
            returnValue = "allValue";
          } else if (reduceType === "any") {
            returnValue = "anyValue";
          }
          var windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;
          var windowSizeVec4Remainder = windowSize % 4;
          var updateSnippet = "\n      if (".concat(reduceType === "sum", ") {\n        sumValue += dot(values, ones);\n      } else if (").concat(reduceType === "prod", ") {\n        vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n        prodValue *= tmp[0] * tmp[1];\n      } else {\n        minMaxValue = ").concat(compareOp, "(values, minMaxValue);\n        if (").concat(reduceType === "min", " || ").concat(reduceType === "max", ") {\n          minMaxValue = ").concat(compareOp, "(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    ");
          var vecType = "vec4";
          if (reduceType === "all") {
            initializationValue = "1.0";
            updateSnippet = "\n        bool reducedAllValue = all(values);\n        float floatedReducedAllValue = float(reducedAllValue);\n        allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n      ";
            vecType = "bvec4";
          } else if (reduceType === "any") {
            initializationValue = "0.0";
            updateSnippet = "\n        bool reducedAnyValue = any(values);\n        float floatedReducedAnyValue = float(reducedAnyValue);\n        anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n      ";
            vecType = "bvec4";
          }
          var checkOutOfBounds = "";
          if (inSize % windowSize > 0) {
            checkOutOfBounds = "\n        if (inIdx < 0 || inIdx >= ".concat(inSize, ") {\n          return initializationValue;\n        }\n      ");
          }
          this.userCode = "\n      const float initializationValue = ".concat(initializationValue, ";\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float getValue(int batch, int inIdx) {\n        ").concat(checkOutOfBounds, "\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 * ").concat(windowSize, ";\n\n        vec4 minMaxValue = vec4(").concat(initializationValue, ");\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 < ").concat(windowSizeNearestVec4, "; i += 4) {\n          int inIdx = inOffset + i;\n          ").concat(vecType, " values = ").concat(vecType, "(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          ").concat(updateSnippet, "\n        }\n\n        int inIdx = inOffset + ").concat(windowSizeNearestVec4, ";\n        if (").concat(windowSizeVec4Remainder === 1, ") {\n          ").concat(vecType, " values = ").concat(vecType, "(\n            getValue(batch, inIdx),\n            initializationValue,\n            initializationValue,\n            initializationValue\n          );\n\n          ").concat(updateSnippet, "\n        } else if (").concat(windowSizeVec4Remainder === 2, ") {\n          ").concat(vecType, " values = ").concat(vecType, "(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            initializationValue,\n            initializationValue\n          );\n\n          ").concat(updateSnippet, "\n        } else if (").concat(windowSizeVec4Remainder === 3, ") {\n          ").concat(vecType, " values = ").concat(vecType, "(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            initializationValue\n          );\n\n          ").concat(updateSnippet, "\n        }\n        setOutput(").concat(returnValue, ");\n      }\n    ");
        }
        return ReduceProgram2;
      }()
    );
    function getReductionStages(inShape) {
      var stages = [];
      while (stages.length === 0 || stages[stages.length - 1].outSize !== 1) {
        var outSize = stages.length ? stages[stages.length - 1].outSize : inShape[1];
        var windowSize = tf.backend_util.computeOptimalWindowSize(outSize);
        stages.push({
          inSize: outSize,
          windowSize,
          outSize: Math.ceil(outSize / windowSize)
        });
      }
      return stages;
    }
    function reduce(x, dtype, reductionType, backend) {
      var reductionStages = getReductionStages(x.shape);
      var result = x;
      for (var i = 0; i < reductionStages.length; i++) {
        var _a2 = reductionStages[i], inSize = _a2.inSize, windowSize = _a2.windowSize, outSize = _a2.outSize;
        var program = void 0;
        var previousResult = void 0;
        if (reductionType === "mean") {
          program = i === 0 ? new MeanProgram({ windowSize, inSize, batchSize: x.shape[0], outSize }, inSize) : new MeanProgram({ windowSize, inSize, batchSize: x.shape[0], outSize });
        } else {
          program = new ReduceProgram({ windowSize, inSize, batchSize: x.shape[0], outSize }, reductionType);
        }
        previousResult = result;
        result = backend.runWebGLProgram(program, [result], dtype);
        if (previousResult.dataId !== x.dataId) {
          backend.disposeIntermediateTensorInfo(previousResult);
        }
      }
      return result;
    }
    var TransposeProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function TransposeProgram2(aShape, newDim) {
          this.variableNames = ["A"];
          var outputShape = new Array(aShape.length);
          for (var i = 0; i < outputShape.length; i++) {
            outputShape[i] = aShape[newDim[i]];
          }
          this.outputShape = outputShape;
          this.rank = outputShape.length;
          var dtype = getCoordsDataType(this.rank);
          var switched = getSwitchedCoords(newDim);
          this.userCode = "\n    void main() {\n      ".concat(dtype, " resRC = getOutputCoords();\n      setOutput(getA(").concat(switched, "));\n    }\n    ");
        }
        return TransposeProgram2;
      }()
    );
    function getSwitchedCoords(newDim) {
      var rank = newDim.length;
      if (rank > 6) {
        throw Error("Transpose for rank ".concat(rank, " is not yet supported"));
      }
      var originalOrder = ["resRC.x", "resRC.y", "resRC.z", "resRC.w", "resRC.u", "resRC.v"];
      var switchedCoords = new Array(rank);
      for (var i = 0; i < newDim.length; i++) {
        switchedCoords[newDim[i]] = originalOrder[i];
      }
      return switchedCoords.join();
    }
    var TransposePackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function TransposePackedProgram2(aShape, newDim) {
          this.variableNames = ["A"];
          this.packedInputs = true;
          this.packedOutput = true;
          var outputShape = new Array(aShape.length);
          for (var i = 0; i < outputShape.length; i++) {
            outputShape[i] = aShape[newDim[i]];
          }
          this.outputShape = outputShape;
          this.rank = outputShape.length;
          if (this.rank > 6) {
            throw Error("Packed transpose for rank ".concat(this.rank, " is not yet supported."));
          }
          var dtype = getCoordsDataType(this.rank);
          var outputOrder = getVecChannels("rc", this.rank);
          var switchedOrder = new Array(this.rank);
          for (var i = 0; i < newDim.length; i++) {
            switchedOrder[newDim[i]] = outputOrder[i];
          }
          var innerDims = "vec2(".concat(switchedOrder.slice(-2).join(), ")");
          var nextColumn = "++".concat(outputOrder[this.rank - 1], " < ").concat(outputShape[this.rank - 1]);
          var getc = "getChannel(getA(".concat(switchedOrder.join(), "), ").concat(innerDims, ")");
          this.userCode = "\n    void main() {\n      ".concat(dtype, " rc = getOutputCoords();\n      vec4 result = vec4(0.);\n      result[0] = ").concat(getc, ";\n      if(").concat(nextColumn, ") {\n        result[1] = ").concat(getc, ";\n      }\n      --").concat(outputOrder[this.rank - 1], ";\n      if(++").concat(outputOrder[this.rank - 2], " < ").concat(outputShape[this.rank - 2], ") {\n        result[2] = ").concat(getc, ";\n        if(").concat(nextColumn, ") {\n          result[3] = ").concat(getc, ";\n        }\n      }\n      setOutput(result);\n    }\n    ");
        }
        return TransposePackedProgram2;
      }()
    );
    function transposeImpl(x, perm, backend) {
      var program = tf.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new TransposePackedProgram(x.shape, perm) : new TransposeProgram(x.shape, perm);
      return backend.runWebGLProgram(program, [x], x.dtype);
    }
    function sumImpl(x, axis, keepDims, backend) {
      var reductionIndices = axis;
      var xRank = x.shape.length;
      var origAxes = tf.util.parseAxisParam(reductionIndices, x.shape);
      var axes = origAxes;
      var permutedAxes = tf.backend_util.getAxesPermutation(axes, xRank);
      var sumInputIsTransposed = permutedAxes != null;
      var sumInput = x;
      if (sumInputIsTransposed) {
        sumInput = transposeImpl(x, permutedAxes, backend);
        axes = tf.backend_util.getInnerMostAxes(axes.length, xRank);
      }
      tf.backend_util.assertAxesAreInnerMostDims("sum", axes, xRank);
      var _a2 = __read(tf.backend_util.computeOutAndReduceShapes(sumInput.shape, axes), 2), sumOutShape = _a2[0], reduceShape = _a2[1];
      var outShape = sumOutShape;
      if (keepDims) {
        outShape = tf.backend_util.expandShapeToKeepDim(sumOutShape, origAxes);
      }
      var inSize = tf.util.sizeFromShape(reduceShape);
      var xSize = tf.util.sizeFromShape(x.shape);
      var batchSize = xSize / inSize;
      var reshapedInput = reshape({ inputs: { x: sumInput }, attrs: { shape: [batchSize, inSize] }, backend });
      var outType = tf.sumOutType(x.dtype);
      var reduced = reduce(reshapedInput, outType, "sum", backend);
      var out = reshape({ inputs: { x: reduced }, attrs: { shape: outShape }, backend });
      backend.disposeIntermediateTensorInfo(reshapedInput);
      backend.disposeIntermediateTensorInfo(reduced);
      if (sumInputIsTransposed) {
        backend.disposeIntermediateTensorInfo(sumInput);
      }
      return out;
    }
    function sum(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis, keepDims = attrs.keepDims;
      return sumImpl(x, axis, keepDims, backend);
    }
    var sumConfig = {
      kernelName: tf.Sum,
      backendName: "webgl",
      kernelFunc: sum
    };
    function transpose(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var perm = attrs.perm;
      var webglBackend = backend;
      var xRank = x.shape.length;
      var newShape = new Array(xRank);
      for (var i = 0; i < newShape.length; i++) {
        newShape[i] = x.shape[perm[i]];
      }
      var out;
      if (webglBackend.shouldExecuteOnCPU([x])) {
        var xTexData = webglBackend.texData.get(x.dataId);
        var values = xTexData.values;
        var outValues = transposeImplCPU(values, x.shape, x.dtype, perm, newShape);
        out = webglBackend.makeTensorInfo(newShape, x.dtype);
        var outData = webglBackend.texData.get(out.dataId);
        outData.values = outValues;
      } else {
        out = transposeImpl(x, perm, webglBackend);
      }
      return out;
    }
    var transposeConfig = {
      kernelName: tf.Transpose,
      backendName: "webgl",
      kernelFunc: transpose
    };
    var MATMUL_SHARED_DIM_THRESHOLD = 1e3;
    function batchMatMulImpl(_a2) {
      var e_12, _b;
      var a = _a2.a, b = _a2.b, transposeA = _a2.transposeA, transposeB = _a2.transposeB, backend = _a2.backend, _c = _a2.bias, bias = _c === void 0 ? null : _c, _d = _a2.preluActivationWeights, preluActivationWeights = _d === void 0 ? null : _d, _e = _a2.leakyreluAlpha, leakyreluAlpha = _e === void 0 ? 0 : _e, _f = _a2.activation, activation = _f === void 0 ? null : _f;
      var aRank = a.shape.length;
      var bRank = b.shape.length;
      var innerShapeA = transposeA ? a.shape[aRank - 2] : a.shape[aRank - 1];
      var innerShapeB = transposeB ? b.shape[bRank - 1] : b.shape[bRank - 2];
      var outerShapeA = transposeA ? a.shape[aRank - 1] : a.shape[aRank - 2];
      var outerShapeB = transposeB ? b.shape[bRank - 2] : b.shape[bRank - 1];
      var outerDimsA = a.shape.slice(0, -2);
      var outerDimsB = b.shape.slice(0, -2);
      var batchDimA = tf.util.sizeFromShape(outerDimsA);
      var batchDimB = tf.util.sizeFromShape(outerDimsB);
      var outShapeOuterDims = tf.broadcast_util.assertAndGetBroadcastShape(a.shape.slice(0, -2), b.shape.slice(0, -2));
      var outShape = outShapeOuterDims.concat([outerShapeA, outerShapeB]);
      tf.util.assert(innerShapeA === innerShapeB, function() {
        return "Error in matMul: inner shapes (".concat(innerShapeA, ") and (") + "".concat(innerShapeB, ") of Tensors with shapes ").concat(a.shape, " and ") + "".concat(b.shape, " and transposeA=").concat(transposeA) + " and transposeB=".concat(transposeB, " must match.");
      });
      var a3dShape = transposeA ? [batchDimA, innerShapeA, outerShapeA] : [batchDimA, outerShapeA, innerShapeA];
      var b3dShape = transposeB ? [batchDimB, outerShapeB, innerShapeB] : [batchDimB, innerShapeB, outerShapeB];
      var a3d = reshape({ inputs: { x: a }, backend, attrs: { shape: a3dShape } });
      var b3d = reshape({ inputs: { x: b }, backend, attrs: { shape: b3dShape } });
      var intermediates = [a3d, b3d];
      var batchDim = Math.max(batchDimA, batchDimB);
      var sharedDim = transposeA ? a3d.shape[1] : a3d.shape[2];
      var hasBias = bias != null;
      var hasPreluActivationWeights = preluActivationWeights != null;
      var hasLeakyreluAlpha = activation === "leakyrelu";
      var fusedActivation = activation != null ? mapActivationToShaderProgram(activation, true) : null;
      var containsFusedOps = hasBias || hasPreluActivationWeights || hasLeakyreluAlpha || fusedActivation != null;
      var out;
      if ((outerShapeA === 1 || outerShapeB === 1) && sharedDim > MATMUL_SHARED_DIM_THRESHOLD && containsFusedOps === false) {
        var aVec = a3d;
        var bVec = b3d;
        if (transposeA) {
          aVec = transpose({ inputs: { x: a3d }, backend, attrs: { perm: [0, 2, 1] } });
          intermediates.push(aVec);
        }
        if (transposeB) {
          bVec = transpose({ inputs: { x: b3d }, backend, attrs: { perm: [0, 2, 1] } });
          intermediates.push(bVec);
        }
        var shouldReshapeA = outerShapeB !== 1;
        var shouldReshapeB = outerShapeB === 1;
        var aVec3d = aVec;
        if (shouldReshapeA) {
          aVec3d = reshape({
            inputs: { x: aVec },
            backend,
            attrs: { shape: [batchDim, sharedDim, 1] }
          });
          intermediates.push(aVec3d);
        }
        var axis = outerShapeB === 1 ? 2 : 1;
        var bVec3d = bVec;
        if (shouldReshapeB) {
          bVec3d = reshape({
            inputs: { x: bVec },
            backend,
            attrs: { shape: [batchDim, 1, sharedDim] }
          });
          intermediates.push(bVec3d);
        }
        var product = multiply({ inputs: { a: aVec3d, b: bVec3d }, backend });
        out = sum({ inputs: { x: product }, backend, attrs: { axis, keepDims: true } });
        intermediates.push(product);
      } else {
        var dtype = tf.upcastType(a.dtype, b.dtype);
        var program = new MatMulPackedProgram(a3dShape, b3dShape, [batchDim, outerShapeA, outerShapeB], transposeA, transposeB, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
        var inputs = [a3d, b3d];
        if (bias != null) {
          inputs.push(bias);
        }
        if (hasPreluActivationWeights) {
          inputs.push(preluActivationWeights);
        }
        if (hasLeakyreluAlpha) {
          var $leakyreluAlpha = backend.makeTensorInfo([], "float32", tf.util.createScalarValue(leakyreluAlpha, "float32"));
          inputs.push($leakyreluAlpha);
          intermediates.push($leakyreluAlpha);
        }
        out = backend.runWebGLProgram(program, inputs, dtype);
      }
      var outReshaped = reshape({ inputs: { x: out }, backend, attrs: { shape: outShape } });
      intermediates.push(out);
      try {
        for (var intermediates_1 = __values(intermediates), intermediates_1_1 = intermediates_1.next(); !intermediates_1_1.done; intermediates_1_1 = intermediates_1.next()) {
          var i = intermediates_1_1.value;
          backend.disposeIntermediateTensorInfo(i);
        }
      } catch (e_1_1) {
        e_12 = { error: e_1_1 };
      } finally {
        try {
          if (intermediates_1_1 && !intermediates_1_1.done && (_b = intermediates_1.return)) _b.call(intermediates_1);
        } finally {
          if (e_12) throw e_12.error;
        }
      }
      return outReshaped;
    }
    function _fusedMatMul(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var a = inputs.a, b = inputs.b, bias = inputs.bias, preluActivationWeights = inputs.preluActivationWeights;
      var transposeA = attrs.transposeA, transposeB = attrs.transposeB, activation = attrs.activation, leakyreluAlpha = attrs.leakyreluAlpha;
      return batchMatMulImpl({
        a,
        b,
        transposeA,
        transposeB,
        backend,
        bias,
        preluActivationWeights,
        leakyreluAlpha,
        activation
      });
    }
    var _fusedMatMulConfig = {
      kernelName: tf._FusedMatMul,
      backendName: "webgl",
      kernelFunc: _fusedMatMul
    };
    var ABS = "return abs(x);";
    function abs(args) {
      var inputs = args.inputs, backend = args.backend;
      var x = inputs.x;
      if (backend.shouldExecuteOnCPU([x]) && x.dtype !== "complex64") {
        var xData = backend.texData.get(x.dataId);
        var outValues = simpleAbsImplCPU(xData.values);
        return backend.makeTensorInfo(x.shape, x.dtype, outValues);
      }
      var program;
      if (tf.env().getBool("WEBGL_PACK_UNARY_OPERATIONS")) {
        program = new UnaryOpPackedProgram(x.shape, ABS);
      } else {
        program = new UnaryOpProgram(x.shape, ABS);
      }
      return backend.runWebGLProgram(program, [x], x.dtype);
    }
    var absConfig = {
      kernelName: tf.Abs,
      backendName: "webgl",
      kernelFunc: abs
    };
    var ACOS = CHECK_NAN_SNIPPET$1 + "\n  if (abs(x) > 1.) {\n    return NAN;\n  }\n  return acos(x);\n";
    var acos = unaryKernelFunc({ opSnippet: ACOS });
    var acosConfig = {
      kernelName: tf.Acos,
      backendName: "webgl",
      kernelFunc: acos
    };
    var ACOSH = CHECK_NAN_SNIPPET$1 + "\n  if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));";
    var acosh = unaryKernelFunc({ opSnippet: ACOSH });
    var acoshConfig = {
      kernelName: tf.Acosh,
      backendName: "webgl",
      kernelFunc: acosh
    };
    var ADD = "return a + b;";
    var addKernelFunc = binaryKernelFunc({
      opSnippet: ADD,
      packedOpSnippet: ADD,
      supportsComplex: true,
      cpuKernelImpl: addImplCPU
    });
    var addConfig = {
      kernelName: tf.Add,
      backendName: "webgl",
      kernelFunc: addKernelFunc
    };
    var AddNProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function AddNProgram2(outputShape, shapes) {
          this.outputShape = [];
          this.outputShape = outputShape;
          this.variableNames = shapes.map(function(_, i) {
            return "T".concat(i);
          });
          var snippets = [];
          this.variableNames.forEach(function(variable) {
            snippets.push("float v".concat(variable, " = get").concat(variable, "AtOutCoords();"));
          });
          var operation = this.variableNames.map(function(variable) {
            return "v".concat(variable);
          }).join(" + ");
          this.userCode = "\n      void main() {\n        ".concat(snippets.join("\n        "), "\n\n        float result = ").concat(operation, ";\n        setOutput(result);\n      }\n    ");
        }
        return AddNProgram2;
      }()
    );
    var AddNPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function AddNPackedProgram2(outputShape, shapes) {
          this.outputShape = [];
          this.packedInputs = true;
          this.packedOutput = true;
          this.outputShape = outputShape;
          this.variableNames = shapes.map(function(_, i) {
            return "T".concat(i);
          });
          var snippets = [];
          this.variableNames.forEach(function(variable) {
            snippets.push("vec4 v".concat(variable, " = get").concat(variable, "AtOutCoords();"));
          });
          var operation = this.variableNames.map(function(variable) {
            return "v".concat(variable);
          }).join(" + ");
          this.userCode = "\n      void main() {\n        ".concat(snippets.join("\n        "), "\n\n        vec4 result = ").concat(operation, ";\n        setOutput(result);\n      }\n    ");
        }
        return AddNPackedProgram2;
      }()
    );
    function addN(args) {
      var inputs = args.inputs, backend = args.backend;
      var tensors = inputs;
      if (tensors.length === 1) {
        return identity({ inputs: { x: tensors[0] }, backend });
      }
      if (tensors.length > tf.env().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")) {
        var midIndex = Math.floor(tensors.length / 2);
        var leftSide = addN({ inputs: tensors.slice(0, midIndex), backend });
        var rightSide = addN({ inputs: tensors.slice(midIndex), backend });
        return addN({ inputs: [leftSide, rightSide], backend });
      }
      var dtype = tensors.map(function(t) {
        return t.dtype;
      }).reduce(function(d1, d2) {
        return tf.upcastType(d1, d2);
      });
      var shapes = tensors.map(function(t) {
        return t.shape;
      });
      var usePackedOp = tf.env().getBool("WEBGL_PACK");
      var program = usePackedOp ? new AddNPackedProgram(tensors[0].shape, shapes) : new AddNProgram(tensors[0].shape, shapes);
      return backend.runWebGLProgram(program, tensors, dtype);
    }
    var addNConfig = {
      kernelName: tf.AddN,
      backendName: "webgl",
      kernelFunc: addN
    };
    function all(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis, keepDims = attrs.keepDims;
      var xRank = x.shape.length;
      var origAxes = tf.util.parseAxisParam(axis, x.shape);
      var axes = origAxes;
      var permutedAxes = tf.backend_util.getAxesPermutation(axes, xRank);
      var permutedX = x;
      if (permutedAxes != null) {
        permutedX = transpose({ inputs: { x }, backend, attrs: { perm: permutedAxes } });
        axes = tf.backend_util.getInnerMostAxes(axes.length, xRank);
      }
      tf.backend_util.assertAxesAreInnerMostDims("all", axes, xRank);
      var _a2 = __read(tf.backend_util.computeOutAndReduceShapes(permutedX.shape, axes), 2), outShape = _a2[0], reduceShape = _a2[1];
      var inSize = tf.util.sizeFromShape(reduceShape);
      var a2D = reshape({ inputs: { x: permutedX }, backend, attrs: { shape: [-1, inSize] } });
      var reduced = reduce(a2D, a2D.dtype, "all", backend);
      var res;
      if (keepDims) {
        var newShape = tf.backend_util.expandShapeToKeepDim(outShape, origAxes);
        res = reshape({ inputs: { x: reduced }, backend, attrs: { shape: newShape } });
      } else {
        res = reshape({ inputs: { x: reduced }, backend, attrs: { shape: outShape } });
      }
      backend.disposeIntermediateTensorInfo(a2D);
      backend.disposeIntermediateTensorInfo(reduced);
      if (permutedAxes != null) {
        backend.disposeIntermediateTensorInfo(permutedX);
      }
      return res;
    }
    var allConfig = {
      kernelName: tf.All,
      backendName: "webgl",
      kernelFunc: all
    };
    function any(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis, keepDims = attrs.keepDims;
      var xRank = x.shape.length;
      var origAxes = tf.util.parseAxisParam(axis, x.shape);
      var axes = origAxes;
      var permutedAxes = tf.backend_util.getAxesPermutation(axes, xRank);
      var permutedX = x;
      if (permutedAxes != null) {
        permutedX = transpose({ inputs: { x }, backend, attrs: { perm: permutedAxes } });
        axes = tf.backend_util.getInnerMostAxes(axes.length, xRank);
      }
      tf.backend_util.assertAxesAreInnerMostDims("any", axes, xRank);
      var _a2 = __read(tf.backend_util.computeOutAndReduceShapes(permutedX.shape, axes), 2), outShape = _a2[0], reduceShape = _a2[1];
      var inSize = tf.util.sizeFromShape(reduceShape);
      var a2D = reshape({ inputs: { x: permutedX }, backend, attrs: { shape: [-1, inSize] } });
      var reduced = reduce(a2D, a2D.dtype, "any", backend);
      var res;
      if (keepDims) {
        var newShape = tf.backend_util.expandShapeToKeepDim(outShape, origAxes);
        res = reshape({ inputs: { x: reduced }, backend, attrs: { shape: newShape } });
      } else {
        res = reshape({ inputs: { x: reduced }, backend, attrs: { shape: outShape } });
      }
      backend.disposeIntermediateTensorInfo(a2D);
      backend.disposeIntermediateTensorInfo(reduced);
      if (permutedAxes != null) {
        backend.disposeIntermediateTensorInfo(permutedX);
      }
      return res;
    }
    var anyConfig = {
      kernelName: tf.Any,
      backendName: "webgl",
      kernelFunc: any
    };
    var ArgMinMaxProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ArgMinMaxProgram2(reduceInfo, op, firstPass) {
          this.variableNames = ["A"];
          var windowSize = reduceInfo.windowSize, batchSize = reduceInfo.batchSize, outSize = reduceInfo.outSize;
          if (!firstPass) {
            this.variableNames.push("bestIndicesA");
          }
          this.outputShape = [batchSize, outSize];
          var compOp = op === "max" ? ">" : "<";
          var indexSnippet = firstPass ? "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 * ".concat(windowSize, ";\n\n        int bestIndex = inOffset;\n        float bestValue = getA(batch, bestIndex);\n\n        for (int i = 0; i < ").concat(windowSize, "; i++) {\n          int inIdx = ").concat(indexSnippet, ";\n          float candidate = getA(batch, inIdx);\n          if (candidate ").concat(compOp, " bestValue) {\n            bestValue = candidate;\n            bestIndex = inIdx;\n          }\n        }\n        setOutput(float(bestIndex));\n      }\n    ");
        }
        return ArgMinMaxProgram2;
      }()
    );
    var ArgMinMaxPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ArgMinMaxPackedProgram2(shape, windowSize, op, firstPass) {
          this.variableNames = ["A"];
          this.packedInputs = true;
          this.packedOutput = true;
          tf.util.assert(shape.length > 2, function() {
            return "Packed arg".concat(op.charAt(0).toUpperCase() + op.slice(1), " supports only inputs with rank above 2.");
          });
          var inSize = shape[shape.length - 1];
          var outSize = Math.ceil(inSize / windowSize);
          this.outputShape = shape.slice(0, -1);
          if (outSize > 1) {
            this.outputShape.push(outSize);
          }
          if (!firstPass) {
            this.variableNames.push("bestIndicesA");
          }
          var outShape = this.outputShape;
          var rank = outShape.length;
          var dtype = getCoordsDataType(rank);
          var coords2 = getChannels("coords", rank);
          var sourceLocSetup;
          var sourceRank;
          if (outSize === 1) {
            sourceRank = rank + 1;
            var sourceLocDType = getCoordsDataType(sourceRank);
            sourceLocSetup = "\n        ".concat(sourceLocDType, " sourceLocR = ").concat(sourceLocDType, "(").concat(coords2.join(), ", 0);\n        ++").concat(coords2[rank - 1], ";\n        ").concat(sourceLocDType, " sourceLocG = ").concat(sourceLocDType, "(").concat(coords2.join(), ", 0);\n        ++").concat(coords2[rank - 2], ";\n        ").concat(sourceLocDType, " sourceLocA = ").concat(sourceLocDType, "(").concat(coords2.join(), ", 0);\n        --").concat(coords2[rank - 1], ";\n        ").concat(sourceLocDType, " sourceLocB = ").concat(sourceLocDType, "(").concat(coords2.join(), ", 0);\n        --").concat(coords2[rank - 2], ";");
          } else {
            sourceRank = rank;
            sourceLocSetup = "\n        ".concat(dtype, " sourceLocR = coords;\n        ++").concat(coords2[rank - 1], ";\n        ").concat(dtype, " sourceLocG = coords;\n        ++").concat(coords2[rank - 2], ";\n        ").concat(dtype, " sourceLocA = coords;\n        --").concat(coords2[rank - 1], ";\n        ").concat(dtype, " sourceLocB = coords;\n        --").concat(coords2[rank - 2], ";");
          }
          var channels = ["x", "y", "z", "w", "u", "v"].slice(0, sourceRank);
          var inChannel = "." + channels[sourceRank - 1];
          var intChannels = channels.map(function(x) {
            return "int " + x;
          });
          var srcRCoords = getChannels("sourceLocR", sourceRank - 1).concat("inIdx.r");
          var srcGCoords = getChannels("sourceLocG", sourceRank - 1).concat("inIdx.g");
          var srcBCoords = getChannels("sourceLocB", sourceRank - 1).concat("inIdx.b");
          var srcACoords = getChannels("sourceLocA", sourceRank - 1).concat("inIdx.a");
          var compOp = op === "max" ? "greaterThan" : "lessThan";
          var fetchCandidateIdx = firstPass ? "" : "\n          inIdx = round(vec4(getBestIndicesAChannel(".concat(srcRCoords.join(), "),\n                             getBestIndicesAChannel(").concat(srcGCoords.join(), "),\n                             getBestIndicesAChannel(").concat(srcBCoords.join(), "),\n                             getBestIndicesAChannel(").concat(srcACoords.join(), ")));");
          var fetchValue = "vec4(\n            getAChannel(".concat(srcRCoords.join(), "),\n            hasNextCol ? getAChannel(").concat(srcGCoords.join(), ") : 0.,\n            hasNextRow ? getAChannel(").concat(srcBCoords.join(), ") : 0.,\n            hasNextRow && hasNextCol ? getAChannel(").concat(srcACoords.join(), ") : 0.)");
          var getBestIndicesAChannelSnippet = firstPass ? "" : "\n      float getBestIndicesAChannel(".concat(intChannels.join(), ") {\n        return getChannel(getBestIndicesA(").concat(channels.join(), "),\n                                          vec2(").concat(channels.slice(-2).join(), "));\n      }");
          this.userCode = "\n      float getAChannel(".concat(intChannels.join(), ") {\n        return getChannel(getA(").concat(channels.join(), "),\n                               vec2(").concat(channels.slice(-2).join(), "));\n      }\n      ").concat(getBestIndicesAChannelSnippet, "\n      void main() {\n        ").concat(dtype, " coords = getOutputCoords();\n        bool hasNextCol = ").concat(coords2[rank - 1], " < ").concat(outShape[rank - 1] - 1, ";\n        bool hasNextRow = ").concat(coords2[rank - 2], " < ").concat(outShape[rank - 2] - 1, ";\n        ").concat(sourceLocSetup, "\n        ivec4 srcIdx = ivec4(sourceLocR").concat(inChannel, ", sourceLocG").concat(inChannel, ",\n          sourceLocB").concat(inChannel, ", sourceLocA").concat(inChannel, ") * ").concat(windowSize, ";\n        ivec4 inIdx = srcIdx;\n        vec4 bestIndex = vec4(inIdx);\n        vec4 bestValue = ").concat(fetchValue, ";\n\n        for (int i = 0; i < ").concat(windowSize, "; i++) {\n          inIdx = srcIdx;\n          ").concat(fetchCandidateIdx, "\n          vec4 candidate = ").concat(fetchValue, ";\n          bvec4 nan = isnan(candidate);\n          bvec4 replace = bvec4(\n            vec4(").concat(compOp, "(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    ");
        }
        return ArgMinMaxPackedProgram2;
      }()
    );
    function argReduce(backend, x, reduceType, bestIndicesA) {
      if (bestIndicesA === void 0) {
        bestIndicesA = null;
      }
      var batchSize = x.shape[0];
      var inSize = x.shape[1];
      if (bestIndicesA != null) {
        batchSize = bestIndicesA.shape[0];
        inSize = bestIndicesA.shape[1];
      }
      var windowSize = tf.backend_util.computeOptimalWindowSize(inSize);
      var reduceInfo = { windowSize, inSize, batchSize, outSize: Math.ceil(inSize / windowSize) };
      var program = new ArgMinMaxProgram(reduceInfo, reduceType, bestIndicesA == null);
      var inputs = [x];
      if (bestIndicesA != null) {
        inputs.push(bestIndicesA);
      }
      var output = backend.runWebGLProgram(program, inputs, "int32");
      if (output.shape[1] === 1) {
        return output;
      }
      var result = argReduce(backend, x, reduceType, output);
      backend.disposeIntermediateTensorInfo(output);
      return result;
    }
    function argReducePacked(backend, x, reduceType, bestIndicesA) {
      if (bestIndicesA === void 0) {
        bestIndicesA = null;
      }
      var inShape = bestIndicesA != null ? bestIndicesA.shape : x.shape;
      var inSize = inShape[inShape.length - 1];
      var windowSize = tf.backend_util.computeOptimalWindowSize(inSize);
      var program = new ArgMinMaxPackedProgram(inShape, windowSize, reduceType, bestIndicesA == null);
      var inputs = bestIndicesA == null ? [x] : [x, bestIndicesA];
      var output = backend.runWebGLProgram(program, inputs, "int32");
      if (output.shape.length === x.shape.length) {
        var result = argReducePacked(backend, x, reduceType, output);
        backend.disposeIntermediateTensorInfo(output);
        return result;
      }
      return output;
    }
    function argMinMaxReduce(backend, x, axis, reduceType) {
      var axes = [axis];
      tf.backend_util.assertAxesAreInnerMostDims("arg" + reduceType.charAt(0).toUpperCase() + reduceType.slice(1), axes, x.shape.length);
      if (!tf.env().getBool("WEBGL_PACK_REDUCE") || x.shape.length <= 2) {
        var intermediateTensorInfos = [];
        var xtexData = backend.texData.get(x.dataId);
        var xIsPacked = xtexData !== null && xtexData.isPacked;
        var xUnPacked = x;
        if (xIsPacked) {
          xUnPacked = backend.unpackTensor(x);
          intermediateTensorInfos.push(xUnPacked);
        }
        var _a2 = __read(tf.backend_util.computeOutAndReduceShapes(xUnPacked.shape, axes), 2), outShape = _a2[0], reduceShape = _a2[1];
        var inSize = tf.util.sizeFromShape(reduceShape);
        var a2D = reshape({ inputs: { x: xUnPacked }, backend, attrs: { shape: [-1, inSize] } });
        intermediateTensorInfos.push(a2D);
        var reduced = argReduce(backend, a2D, reduceType);
        intermediateTensorInfos.push(reduced);
        var reshaped = reshape({ inputs: { x: reduced }, backend, attrs: { shape: outShape } });
        intermediateTensorInfos.forEach(function(t) {
          return backend.disposeIntermediateTensorInfo(t);
        });
        return reshaped;
      }
      return argReducePacked(backend, x, reduceType);
    }
    function argMax(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis;
      var axes = tf.util.parseAxisParam(axis, x.shape);
      var permutedAxes = tf.backend_util.getAxesPermutation(axes, x.shape.length);
      var $x = x;
      var intermediateTensorInfos = [];
      if (permutedAxes != null) {
        $x = transpose({ inputs: { x }, backend, attrs: { perm: permutedAxes } });
        intermediateTensorInfos.push($x);
        axes = tf.backend_util.getInnerMostAxes(axes.length, $x.shape.length);
      }
      tf.backend_util.assertAxesAreInnerMostDims("argMax", [axes[0]], $x.shape.length);
      var out = argMinMaxReduce(backend, $x, axes[0], "max");
      intermediateTensorInfos.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return out;
    }
    var argMaxConfig = {
      kernelName: tf.ArgMax,
      backendName: "webgl",
      kernelFunc: argMax
    };
    function argMin(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis;
      var axes = tf.util.parseAxisParam(axis, x.shape);
      var permutedAxes = tf.backend_util.getAxesPermutation(axes, x.shape.length);
      var $x = x;
      var intermediateTensorInfos = [];
      if (permutedAxes != null) {
        $x = transpose({ inputs: { x }, backend, attrs: { perm: permutedAxes } });
        intermediateTensorInfos.push($x);
        axes = tf.backend_util.getInnerMostAxes(axes.length, $x.shape.length);
      }
      tf.backend_util.assertAxesAreInnerMostDims("argMin", [axes[0]], $x.shape.length);
      var out = argMinMaxReduce(backend, $x, axes[0], "min");
      intermediateTensorInfos.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return out;
    }
    var argMinConfig = {
      kernelName: tf.ArgMin,
      backendName: "webgl",
      kernelFunc: argMin
    };
    var ASIN = CHECK_NAN_SNIPPET$1 + "\n  if (abs(x) > 1.) {\n    return NAN;\n  }\n  return asin(x);\n";
    var asin = unaryKernelFunc({ opSnippet: ASIN });
    var asinConfig = {
      kernelName: tf.Asin,
      backendName: "webgl",
      kernelFunc: asin
    };
    var ASINH = CHECK_NAN_SNIPPET$1 + "return log(x + sqrt(x * x + 1.0));";
    var asinh = unaryKernelFunc({ opSnippet: ASINH });
    var asinhConfig = {
      kernelName: tf.Asinh,
      backendName: "webgl",
      kernelFunc: asinh
    };
    var ATAN = CHECK_NAN_SNIPPET$1 + "\n  return atan(x);\n";
    var atan = unaryKernelFunc({ opSnippet: ATAN });
    var atanConfig = {
      kernelName: tf.Atan,
      backendName: "webgl",
      kernelFunc: atan
    };
    var ATAN2 = CHECK_NAN_SNIPPET + "\n  return atan(a, b);\n";
    var ATAN2_PACKED = "\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  " + CHECK_NAN_SNIPPET_PACKED + "\n  return result;\n";
    var atan2 = binaryKernelFunc({ opSnippet: ATAN2, packedOpSnippet: ATAN2_PACKED });
    var atan2Config = {
      kernelName: tf.Atan2,
      backendName: "webgl",
      kernelFunc: atan2
    };
    var ATANH = CHECK_NAN_SNIPPET$1 + "\n  if ((x < -1.0) || (x > 1.0)) return NAN;\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;";
    var atanh = unaryKernelFunc({ opSnippet: ATANH });
    var atanhConfig = {
      kernelName: tf.Atanh,
      backendName: "webgl",
      kernelFunc: atanh
    };
    var Pool2DProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function Pool2DProgram2(convInfo, poolType, computePositions, flattenPositions, includeBatchInIndex) {
          if (flattenPositions === void 0) {
            flattenPositions = false;
          }
          if (includeBatchInIndex === void 0) {
            includeBatchInIndex = false;
          }
          this.variableNames = ["x"];
          if (poolType === "avg" && computePositions) {
            throw new Error("Cannot compute positions for average pool.");
          }
          var filterWidth = convInfo.filterWidth;
          var strideHeight = convInfo.strideHeight;
          var strideWidth = convInfo.strideWidth;
          var dilationHeight = convInfo.dilationHeight;
          var dilationWidth = convInfo.dilationWidth;
          var effectiveFilterHeight = convInfo.effectiveFilterHeight;
          var effectiveFilterWidth = convInfo.effectiveFilterWidth;
          var padTop = convInfo.padInfo.top;
          var padLeft = convInfo.padInfo.left;
          this.outputShape = convInfo.outShape;
          var isAvgPool = poolType === "avg";
          var batchFlattenPositionStr = "((batch  * ".concat(convInfo.inHeight, " + xR) * ").concat(convInfo.inWidth, " + xC) * ").concat(convInfo.inChannels, " + d");
          var flattenPositionStr = "(xR * ".concat(convInfo.inWidth, " + xC) * ").concat(convInfo.inChannels, " + d");
          var initializationValue = "0.0";
          if (!isAvgPool) {
            initializationValue = "-1.0 / 1e-20";
          }
          if (computePositions) {
            var compareOp_1 = ">=";
            this.userCode = "\n        const ivec2 strides = ivec2(".concat(strideHeight, ", ").concat(strideWidth, ");\n        const ivec2 pads = ivec2(").concat(padTop, ", ").concat(padLeft, ");\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 < ").concat(effectiveFilterHeight, ";\n              wR += ").concat(dilationHeight, ") {\n            int xR = xRCorner + wR;\n\n            if (xR < 0 || xR >= ").concat(convInfo.inHeight, ") {\n              continue;\n            }\n\n            for (int wC = 0; wC < ").concat(effectiveFilterWidth, ";\n                wC += ").concat(dilationWidth, ") {\n              int xC = xCCorner + wC;\n\n              if (xC < 0 || xC >= ").concat(convInfo.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 ").concat(compareOp_1, " currMinMaxValue) {\n                minMaxValue = value;\n                minMaxValueFound = 1.0;\n                minMaxPosition = ").concat(flattenPositions ? includeBatchInIndex ? batchFlattenPositionStr : flattenPositionStr : "wR * ".concat(effectiveFilterWidth, " + wC"), ";\n              }\n            }\n          }\n          setOutput(float(minMaxPosition));\n        }\n      ");
            return;
          }
          var compareOp = "max";
          var returnValue = "".concat(poolType, "(").concat(poolType, "(").concat(poolType, "(") + "minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";
          if (poolType === "avg") {
            returnValue = "avgValue / max(count, 1.0)";
          }
          var filterWidthNearestVec4 = Math.floor(filterWidth / 4) * 4;
          var filterWidthVec4Remainder = filterWidth % 4;
          var updateSnippet = "\n      if (".concat(isAvgPool, ") {\n        avgValue += dot(values, ones);\n      } else {\n        minMaxValue = ").concat(compareOp, "(values, minMaxValue);\n      }\n    ");
          this.userCode = "\n      const ivec2 strides = ivec2(".concat(strideHeight, ", ").concat(strideWidth, ");\n      const ivec2 pads = ivec2(").concat(padTop, ", ").concat(padLeft, ");\n      const float initializationValue = ").concat(initializationValue, ";\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 >= ").concat(convInfo.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(").concat(initializationValue, ");\n        float avgValue = 0.0;\n        count = 0.0;\n\n        for (int wR = 0; wR < ").concat(effectiveFilterHeight, ";\n            wR += ").concat(dilationHeight, ") {\n          int xR = xRCorner + wR;\n\n          if (xR < 0 || xR >= ").concat(convInfo.inHeight, ") {\n            continue;\n          }\n\n          for (int wC = 0; wC < ").concat(filterWidthNearestVec4, "; wC += 4) {\n            int xC = xCCorner + wC * ").concat(dilationWidth, ";\n\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + ").concat(dilationWidth, ", d),\n              getValue(batch, xR, xC + 2 * ").concat(dilationWidth, ", d),\n              getValue(batch, xR, xC + 3 * ").concat(dilationWidth, ", d)\n            );\n\n            ").concat(updateSnippet, "\n          }\n\n          int xC = xCCorner + ").concat(filterWidthNearestVec4, ";\n          if (").concat(filterWidthVec4Remainder === 1, ") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              initializationValue,\n              initializationValue,\n              initializationValue\n            );\n\n            ").concat(updateSnippet, "\n          } else if (").concat(filterWidthVec4Remainder === 2, ") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + ").concat(dilationWidth, ", d),\n              initializationValue,\n              initializationValue\n            );\n\n            ").concat(updateSnippet, "\n          } else if (").concat(filterWidthVec4Remainder === 3, ") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + ").concat(dilationWidth, ", d),\n              getValue(batch, xR, xC + 2 * ").concat(dilationWidth, ", d),\n              initializationValue\n            );\n\n            ").concat(updateSnippet, "\n          }\n        }\n        setOutput(").concat(returnValue, ");\n      }\n    ");
        }
        return Pool2DProgram2;
      }()
    );
    var Pool3DProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function Pool3DProgram2(convInfo, poolType, computePositions, flattenPositions, includeBatchInIndex) {
          if (flattenPositions === void 0) {
            flattenPositions = false;
          }
          if (includeBatchInIndex === void 0) {
            includeBatchInIndex = false;
          }
          this.variableNames = ["x"];
          if (poolType === "avg" && computePositions) {
            throw new Error("Cannot compute positions for average pool.");
          }
          var filterWidth = convInfo.filterWidth;
          var strideDepth = convInfo.strideDepth;
          var strideHeight = convInfo.strideHeight;
          var strideWidth = convInfo.strideWidth;
          var dilationDepth = convInfo.dilationDepth;
          var dilationHeight = convInfo.dilationHeight;
          var dilationWidth = convInfo.dilationWidth;
          var effectiveFilterDepth = convInfo.effectiveFilterDepth;
          var effectiveFilterHeight = convInfo.effectiveFilterHeight;
          var effectiveFilterWidth = convInfo.effectiveFilterWidth;
          var padFront = convInfo.padInfo.front;
          var padTop = convInfo.padInfo.top;
          var padLeft = convInfo.padInfo.left;
          this.outputShape = convInfo.outShape;
          var isAvgPool = poolType === "avg";
          var initializationValue = "0.0";
          if (!isAvgPool) {
            initializationValue = "-1.0 / 1e-20";
          }
          if (computePositions) {
            var compareOp_2 = ">=";
            this.userCode = "\n        const ivec3 strides =\n            ivec3(".concat(strideDepth, ", ").concat(strideHeight, ", ").concat(strideWidth, ");\n        const ivec3 pads = ivec3(").concat(padFront, ", ").concat(padTop, ", ").concat(padLeft, ");\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 < ").concat(effectiveFilterDepth, ";\n              wD += ").concat(dilationDepth, ") {\n            int xD = xDCorner + wD;\n\n            if (xD < 0 || xD >= ").concat(convInfo.inDepth, ") {\n              continue;\n            }\n\n            for (int wR = 0; wR < ").concat(effectiveFilterHeight, ";\n                wR += ").concat(dilationHeight, ") {\n              int xR = xRCorner + wR;\n\n              if (xR < 0 || xR >= ").concat(convInfo.inHeight, ") {\n                continue;\n              }\n\n              for (int wC = 0; wC < ").concat(effectiveFilterWidth, ";\n                  wC += ").concat(dilationWidth, ") {\n                int xC = xCCorner + wC;\n\n                if (xC < 0 || xC >= ").concat(convInfo.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 ").concat(compareOp_2, " currMinMaxValue) {\n                  minMaxValue = value;\n                  minMaxValueFound = 1.0;\n                  minMaxPosition = ").concat(flattenPositions ? includeBatchInIndex ? "(((batch * ".concat(convInfo.inDepth, " + xD) * ").concat(convInfo.inHeight, " + xR) * ").concat(convInfo.inWidth, " + xC) * ").concat(convInfo.inChannels, " + ch") : "((xD * ".concat(convInfo.inHeight, " + xR) * ").concat(convInfo.inWidth, " + xC) * ").concat(convInfo.inChannels, " + ch") : "wD * ".concat(effectiveFilterHeight, " * ").concat(effectiveFilterWidth, " +\n                      wR * ").concat(effectiveFilterWidth, " + wC"), ";\n                }\n              }\n            }\n          }\n          setOutput(float(minMaxPosition));\n        }\n      ");
            return;
          }
          var compareOp = "max";
          var returnValue = "".concat(poolType, "(").concat(poolType, "(").concat(poolType, "(") + "minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";
          if (poolType === "avg") {
            returnValue = "avgValue / max(count, 1.0)";
          }
          var filterWidthNearestVec4 = Math.floor(filterWidth / 4) * 4;
          var filterWidthVec4Remainder = filterWidth % 4;
          var updateSnippet = "\n      if (".concat(isAvgPool, ") {\n        avgValue += dot(values, ones);\n      } else {\n        minMaxValue = ").concat(compareOp, "(values, minMaxValue);\n      }\n    ");
          this.userCode = "\n      const ivec3 strides =\n        ivec3(".concat(strideDepth, ", ").concat(strideHeight, ", ").concat(strideWidth, ");\n      const ivec3 pads = ivec3(").concat(padFront, ", ").concat(padTop, ", ").concat(padLeft, ");\n      const float initializationValue = ").concat(initializationValue, ";\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 >= ").concat(convInfo.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(").concat(initializationValue, ");\n        float avgValue = 0.0;\n        count = 0.0;\n\n        for (int wD = 0; wD < ").concat(effectiveFilterDepth, ";\n            wD += ").concat(dilationDepth, ") {\n          int xD = xDCorner + wD;\n\n          if (xD < 0 || xD >= ").concat(convInfo.inDepth, ") {\n            continue;\n          }\n\n          for (int wR = 0; wR < ").concat(effectiveFilterHeight, ";\n            wR += ").concat(dilationHeight, ") {\n            int xR = xRCorner + wR;\n\n            if (xR < 0 || xR >= ").concat(convInfo.inHeight, ") {\n              continue;\n            }\n\n            for (int wC = 0; wC < ").concat(filterWidthNearestVec4, "; wC += 4) {\n              int xC = xCCorner + wC * ").concat(dilationWidth, ";\n\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                getValue(batch, xD, xR, xC + ").concat(dilationWidth, ", ch),\n                getValue(batch, xD, xR, xC + 2 * ").concat(dilationWidth, ", ch),\n                getValue(batch, xD, xR, xC + 3 * ").concat(dilationWidth, ", ch)\n              );\n\n              ").concat(updateSnippet, "\n            }\n\n            int xC = xCCorner + ").concat(filterWidthNearestVec4, ";\n            if (").concat(filterWidthVec4Remainder === 1, ") {\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                initializationValue,\n                initializationValue,\n                initializationValue\n              );\n\n              ").concat(updateSnippet, "\n            } else if (").concat(filterWidthVec4Remainder === 2, ") {\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                getValue(batch, xD, xR, xC + ").concat(dilationWidth, ", ch),\n                initializationValue,\n                initializationValue\n              );\n\n              ").concat(updateSnippet, "\n            } else if (").concat(filterWidthVec4Remainder === 3, ") {\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                getValue(batch, xD, xR, xC + ").concat(dilationWidth, ", ch),\n                getValue(batch, xD, xR, xC + 2 * ").concat(dilationWidth, ", ch),\n                initializationValue\n              );\n\n              ").concat(updateSnippet, "\n            }\n          }\n        }\n        setOutput(").concat(returnValue, ");\n      }\n    ");
        }
        return Pool3DProgram2;
      }()
    );
    function avgPool(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      assertNotComplex(x, "avgPool");
      var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
      var dilations = 1;
      tf.util.assert(tf.backend_util.eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in avgPool: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      var convInfo = tf.backend_util.computePool2DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode);
      if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 && tf.util.arraysEqual(convInfo.inShape, convInfo.outShape)) {
        return identity({ inputs: { x }, backend });
      }
      var avgPoolProgram = new Pool2DProgram(convInfo, "avg", false);
      return backend.runWebGLProgram(avgPoolProgram, [x], "float32");
    }
    var avgPoolConfig = {
      kernelName: tf.AvgPool,
      backendName: "webgl",
      kernelFunc: avgPool
    };
    function avgPool3D(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode, dataFormat = attrs.dataFormat;
      var dilations = [1, 1, 1];
      var convInfo = tf.backend_util.computePool3DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode, dataFormat);
      var avgPoolProgram = new Pool3DProgram(convInfo, "avg", false);
      return backend.runWebGLProgram(avgPoolProgram, [x], "float32");
    }
    var avgPool3DConfig = {
      kernelName: tf.AvgPool3D,
      backendName: "webgl",
      kernelFunc: avgPool3D
    };
    var AvgPool2DBackpropProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function AvgPool2DBackpropProgram2(convInfo) {
          this.variableNames = ["dy"];
          this.outputShape = convInfo.inShape;
          var filterHeight = convInfo.filterHeight;
          var filterWidth = convInfo.filterWidth;
          var strideHeight = convInfo.strideHeight;
          var strideWidth = convInfo.strideWidth;
          var dilationHeight = convInfo.dilationHeight;
          var dilationWidth = convInfo.dilationWidth;
          var effectiveFilterHeight = convInfo.effectiveFilterHeight;
          var effectiveFilterWidth = convInfo.effectiveFilterWidth;
          var padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
          var padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
          var avgMultiplier = 1 / (filterHeight * filterWidth);
          this.userCode = "\n      const ivec2 pads = ivec2(".concat(padTop, ", ").concat(padLeft, ");\n      const float avgMultiplier = float(").concat(avgMultiplier, ");\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 < ").concat(effectiveFilterHeight, ";\n            wR += ").concat(dilationHeight, ") {\n          float dyR = float(dyRCorner + wR) / ").concat(strideHeight, ".0;\n\n          if (dyR < 0.0 || dyR >= ").concat(convInfo.outHeight, ".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          for (int wC = 0; wC < ").concat(effectiveFilterWidth, ";\n            wC+= ").concat(dilationWidth, ") {\n            float dyC = float(dyCCorner + wC) / ").concat(strideWidth, ".0;\n\n            if (dyC < 0.0 || dyC >= ").concat(convInfo.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    ");
        }
        return AvgPool2DBackpropProgram2;
      }()
    );
    var AvgPool3DBackpropProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function AvgPool3DBackpropProgram2(convInfo) {
          this.variableNames = ["dy"];
          this.outputShape = convInfo.inShape;
          var filterDepth = convInfo.filterDepth;
          var filterHeight = convInfo.filterHeight;
          var filterWidth = convInfo.filterWidth;
          var strideDepth = convInfo.strideDepth;
          var strideHeight = convInfo.strideHeight;
          var strideWidth = convInfo.strideWidth;
          var dilationDepth = convInfo.dilationDepth;
          var dilationHeight = convInfo.dilationHeight;
          var dilationWidth = convInfo.dilationWidth;
          var effectiveFilterDepth = convInfo.effectiveFilterDepth;
          var effectiveFilterHeight = convInfo.effectiveFilterHeight;
          var effectiveFilterWidth = convInfo.effectiveFilterWidth;
          var padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;
          var padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
          var padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
          var avgMultiplier = 1 / (filterDepth * filterHeight * filterWidth);
          this.userCode = "\n      const ivec3 pads = ivec3(".concat(padFront, ", ").concat(padTop, ", ").concat(padLeft, ");\n      const float avgMultiplier = float(").concat(avgMultiplier, ");\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 < ").concat(effectiveFilterDepth, ";\n            wD += ").concat(dilationDepth, ") {\n          float dyD = float(dyDCorner + wD) / ").concat(strideDepth, ".0;\n\n          if (dyD < 0.0 || dyD >= ").concat(convInfo.outDepth, ".0 || fract(dyD) > 0.0) {\n            continue;\n          }\n          int idyD = int(dyD);\n\n          for (int wR = 0; wR < ").concat(effectiveFilterHeight, ";\n              wR += ").concat(dilationHeight, ") {\n            float dyR = float(dyRCorner + wR) / ").concat(strideHeight, ".0;\n\n            if (dyR < 0.0 || dyR >= ").concat(convInfo.outHeight, ".0 ||\n                fract(dyR) > 0.0) {\n              continue;\n            }\n            int idyR = int(dyR);\n\n            for (int wC = 0; wC < ").concat(effectiveFilterWidth, ";\n                wC += ").concat(dilationWidth, ") {\n              float dyC = float(dyCCorner + wC) / ").concat(strideWidth, ".0;\n\n              if (dyC < 0.0 || dyC >= ").concat(convInfo.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    ");
        }
        return AvgPool3DBackpropProgram2;
      }()
    );
    function avgPool3DGrad(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var dy = inputs.dy, input = inputs.input;
      var x = input;
      var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
      var dilations = [1, 1, 1];
      var convInfo = tf.backend_util.computePool3DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode);
      var avgPoolBackpropProgram = new AvgPool3DBackpropProgram(convInfo);
      return backend.runWebGLProgram(avgPoolBackpropProgram, [dy], x.dtype);
    }
    var avgPool3DGradConfig = {
      kernelName: tf.AvgPool3DGrad,
      backendName: "webgl",
      kernelFunc: avgPool3DGrad
    };
    function avgPoolGrad(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var dy = inputs.dy, input = inputs.input;
      var x = input;
      assertNotComplex([dy, input], "avgPoolGrad");
      var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad;
      var convInfo = tf.backend_util.computePool2DInfo(x.shape, filterSize, strides, 1, pad);
      var avgPoolBackpropProgram = new AvgPool2DBackpropProgram(convInfo);
      return backend.runWebGLProgram(avgPoolBackpropProgram, [dy], x.dtype);
    }
    var avgPoolGradConfig = {
      kernelName: tf.AvgPoolGrad,
      backendName: "webgl",
      kernelFunc: avgPoolGrad
    };
    function batchMatMul(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var a = inputs.a, b = inputs.b;
      var transposeA = attrs.transposeA, transposeB = attrs.transposeB;
      return batchMatMulImpl({ a, b, transposeA, transposeB, backend });
    }
    var batchMatMulConfig = {
      kernelName: tf.BatchMatMul,
      backendName: "webgl",
      kernelFunc: batchMatMul
    };
    var BatchNormProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function BatchNormProgram2(xShape, meanShape, varianceShape, offsetShape, scaleShape, varianceEpsilon) {
          this.outputShape = [];
          this.variableNames = ["x", "mean", "variance"];
          tf.backend_util.assertAndGetBroadcastShape(xShape, meanShape);
          tf.backend_util.assertAndGetBroadcastShape(xShape, varianceShape);
          var offsetSnippet = "0.0";
          if (offsetShape != null) {
            tf.backend_util.assertAndGetBroadcastShape(xShape, offsetShape);
            this.variableNames.push("offset");
            offsetSnippet = "getOffsetAtOutCoords()";
          }
          var scaleSnippet = "1.0";
          if (scaleShape != null) {
            tf.backend_util.assertAndGetBroadcastShape(xShape, scaleShape);
            this.variableNames.push("scale");
            scaleSnippet = "getScaleAtOutCoords()";
          }
          this.outputShape = xShape;
          this.userCode = "\n      void main() {\n        float x = getXAtOutCoords();\n        float mean = getMeanAtOutCoords();\n        float variance = getVarianceAtOutCoords();\n        float offset = ".concat(offsetSnippet, ";\n        float scale = ").concat(scaleSnippet, ";\n        float inv = scale * inversesqrt(variance + float(").concat(varianceEpsilon, "));\n        setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n      }\n    ");
        }
        return BatchNormProgram2;
      }()
    );
    var BatchNormPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function BatchNormPackedProgram2(xShape, meanShape, varianceShape, offsetShape, scaleShape, varianceEpsilon) {
          this.packedInputs = true;
          this.packedOutput = true;
          this.variableNames = ["x", "mean", "variance"];
          tf.backend_util.assertAndGetBroadcastShape(xShape, meanShape);
          tf.backend_util.assertAndGetBroadcastShape(xShape, varianceShape);
          var offsetSnippet = "vec4(0.0)";
          if (offsetShape != null) {
            tf.backend_util.assertAndGetBroadcastShape(xShape, offsetShape);
            this.variableNames.push("offset");
            offsetSnippet = "getOffsetAtOutCoords()";
          }
          var scaleSnippet = "vec4(1.0)";
          if (scaleShape != null) {
            tf.backend_util.assertAndGetBroadcastShape(xShape, scaleShape);
            this.variableNames.push("scale");
            scaleSnippet = "getScaleAtOutCoords()";
          }
          this.outputShape = xShape;
          this.userCode = "\n      void main() {\n        vec4 offset = ".concat(offsetSnippet, ";\n        vec4 scale = ").concat(scaleSnippet, ";\n\n        vec4 x = getXAtOutCoords();\n        vec4 mean = getMeanAtOutCoords();\n        vec4 variance = getVarianceAtOutCoords();\n\n        vec4 inv = scale * inversesqrt(variance + vec4(").concat(varianceEpsilon, "));\n\n        setOutput((x - mean) * inv + offset);\n      }\n    ");
        }
        return BatchNormPackedProgram2;
      }()
    );
    var batchNorm = function(_a2) {
      var inputs = _a2.inputs, backend = _a2.backend, attrs = _a2.attrs;
      var x = inputs.x, mean = inputs.mean, variance = inputs.variance, offset = inputs.offset, scale = inputs.scale;
      tf.util.assert(mean.shape.length === variance.shape.length, function() {
        return "Batch normalization gradient requires mean and variance to have equal ranks.";
      });
      tf.util.assert(offset == null || mean.shape.length === offset.shape.length, function() {
        return "Batch normalization gradient requires mean and offset to have equal ranks.";
      });
      tf.util.assert(scale == null || mean.shape.length === scale.shape.length, function() {
        return "Batch normalization gradient requires mean and scale to have equal ranks.";
      });
      var varianceEpsilon = attrs.varianceEpsilon;
      if (varianceEpsilon == null) {
        varianceEpsilon = 1e-3;
      }
      var finalInputs = [x, mean, variance];
      var offsetShape = null;
      if (offset != null) {
        offsetShape = offset.shape;
        finalInputs.push(offset);
      }
      var scaleShape = null;
      if (scale != null) {
        scaleShape = scale.shape;
        finalInputs.push(scale);
      }
      var program = tf.env().getBool("WEBGL_PACK_NORMALIZATION") ? new BatchNormPackedProgram(x.shape, mean.shape, variance.shape, offsetShape, scaleShape, varianceEpsilon) : new BatchNormProgram(x.shape, mean.shape, variance.shape, offsetShape, scaleShape, varianceEpsilon);
      var output = backend.runWebGLProgram(program, finalInputs, finalInputs[0].dtype);
      return output;
    };
    var batchNormConfig = {
      kernelName: tf.FusedBatchNorm,
      backendName: "webgl",
      kernelFunc: batchNorm
    };
    var SliceProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function SliceProgram2(destSize) {
          this.variableNames = ["source"];
          this.outputShape = destSize;
          this.rank = destSize.length;
          var dtype = getCoordsDataType(this.rank);
          this.customUniforms = [{ name: "start", arrayIndex: this.rank, type: "int" }];
          var sourceCoords = getCoords$1(this.rank);
          var body;
          var coordSum = destSize.map(function(_, i) {
            return "sourceLoc.".concat(coords[i], " = start[").concat(i, "] + coords.").concat(coords[i], ";");
          });
          body = "\n        ".concat(dtype, " sourceLoc;\n        ").concat(dtype, " coords = getOutputCoords();\n        ").concat(coordSum.join("\n"), "\n      ");
          this.userCode = "\n      void main() {\n        ".concat(body, "\n        setOutput(getSource(").concat(sourceCoords, "));\n      }\n    ");
        }
        return SliceProgram2;
      }()
    );
    var coords = ["x", "y", "z", "w", "u", "v"];
    function getCoords$1(rank) {
      if (rank === 1) {
        return "sourceLoc";
      } else if (rank <= 6) {
        return coords.slice(0, rank).map(function(x) {
          return "sourceLoc." + x;
        }).join(",");
      } else {
        throw Error("Slicing for rank ".concat(rank, " is not yet supported"));
      }
    }
    var SlicePackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function SlicePackedProgram2(destSize) {
          this.variableNames = ["source"];
          this.packedInputs = true;
          this.packedOutput = true;
          this.outputShape = destSize;
          this.rank = destSize.length;
          this.customUniforms = [{ name: "start", arrayIndex: this.rank, type: "int" }];
          var dtype = getCoordsDataType(this.rank);
          var coords2 = getChannels("coords", this.rank);
          var sourceLoc = getChannels("sourceLoc", this.rank);
          var innerDims = this.rank === 1 ? "sourceLoc" : "vec2(".concat(sourceLoc.slice(-2).join(), ")");
          var getChannel = "getChannel(getSource(".concat(sourceLoc.join(), "), ").concat(innerDims, ")");
          var upperRow = "\n      result.x = ".concat(getChannel, ";\n      if (++").concat(coords2[this.rank - 1], " < ").concat(destSize[this.rank - 1], ") {\n        ++").concat(sourceLoc[this.rank - 1], ";\n        result.y = ").concat(getChannel, ";\n        --").concat(sourceLoc[this.rank - 1], ";\n      }\n    ");
          var lowerRow = this.rank === 1 ? "" : "\n      --".concat(coords2[this.rank - 1], ";\n      if (++").concat(coords2[this.rank - 2], " < ").concat(destSize[this.rank - 2], ") {\n        ++").concat(sourceLoc[this.rank - 2], ";\n        result.z = ").concat(getChannel, ";\n        if (++").concat(coords2[this.rank - 1], " < ").concat(destSize[this.rank - 1], ") {\n          ++").concat(sourceLoc[this.rank - 1], ";\n          result.w = ").concat(getChannel, ";\n        }\n      }\n    ");
          var sourceLocSetup = this.rank <= 4 ? "sourceLoc = coords +\n            ".concat(dtype, "(").concat(destSize.map(function(_, i) {
            return "start[".concat(i, "]");
          }).join(), ");") : destSize.map(function(_, i) {
            return "".concat(sourceLoc[i], " = ").concat(coords2[i], " + start[").concat(i, "];");
          }).join("\n");
          this.userCode = "\n      void main() {\n        ".concat(dtype, " coords = getOutputCoords();\n        ").concat(dtype, " sourceLoc;\n        ").concat(sourceLocSetup, "\n        vec4 result = vec4(0.);\n        ").concat(upperRow, "\n        ").concat(lowerRow, "\n        setOutput(result);\n      }\n    ");
        }
        return SlicePackedProgram2;
      }()
    );
    function shallowSlice(x, begin, size, backend) {
      var xTexData = backend.texData.get(x.dataId);
      var t = backend.makeTensorInfo(size, x.dtype);
      var newTexData = backend.texData.get(t.dataId);
      Object.assign(newTexData, xTexData);
      newTexData.refCount = 1;
      newTexData.shape = size;
      newTexData.dtype = x.dtype;
      var flatOffset = tf.slice_util.computeFlatOffset(begin, tf.util.computeStrides(x.shape));
      if (xTexData.slice) {
        flatOffset += xTexData.slice.flatOffset;
      }
      newTexData.slice = {
        flatOffset,
        // Point to the original dataId, which is used to do ref counting.
        origDataId: xTexData.slice && xTexData.slice.origDataId || x.dataId
      };
      var refCount = backend.dataRefCount.get(newTexData.slice.origDataId) || 1;
      backend.dataRefCount.set(newTexData.slice.origDataId, refCount + 1);
      return t;
    }
    function slice(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var begin = attrs.begin, size = attrs.size;
      var _a2 = __read(tf.slice_util.parseSliceParams(x, begin, size), 2), $begin = _a2[0], $size = _a2[1];
      tf.slice_util.assertParamsValid(x, $begin, $size);
      if (tf.util.sizeFromShape($size) === 0) {
        return backend.makeTensorInfo($size, x.dtype, []);
      }
      if (backend.shouldExecuteOnCPU([x]) || x.dtype === "string") {
        var xTexData = backend.texData.get(x.dataId);
        var outValues = sliceImplCPU(xTexData.values, $begin, $size, x.shape, x.dtype);
        return backend.makeTensorInfo($size, x.dtype, outValues);
      }
      var isPacked = backend.texData.get(x.dataId).isPacked;
      var isContinous = tf.slice_util.isSliceContinous(x.shape, $begin, $size);
      if (isPacked || !isContinous) {
        var program = tf.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new SlicePackedProgram($size) : new SliceProgram($size);
        var customValues = [$begin];
        return backend.runWebGLProgram(program, [x], x.dtype, customValues);
      }
      backend.uploadToGPU(x.dataId);
      return shallowSlice(x, $begin, $size, backend);
    }
    var sliceConfig = {
      kernelName: tf.Slice,
      backendName: "webgl",
      kernelFunc: slice
    };
    var batchToSpaceND = function(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var blockShape = attrs.blockShape, crops = attrs.crops;
      tf.util.assert(x.shape.length <= 4, function() {
        return "batchToSpaceND for rank > 4 with a WebGL backend not implemented yet";
      });
      var prod2 = blockShape.reduce(function(a, b) {
        return a * b;
      });
      var reshaped = tf.backend_util.getReshaped(x.shape, blockShape, prod2);
      var permuted = tf.backend_util.getPermuted(reshaped.length, blockShape.length);
      var reshapedPermuted = tf.backend_util.getReshapedPermuted(x.shape, blockShape, prod2);
      var sliceBeginCoords = tf.backend_util.getSliceBeginCoords(crops, blockShape.length);
      var sliceSize = tf.backend_util.getSliceSize(reshapedPermuted, crops, blockShape.length);
      var toDispose = [];
      var reshapedIntermediate = reshape({ inputs: { x }, backend, attrs: { shape: reshaped } });
      var transposedIntermediate = transpose({ inputs: { x: reshapedIntermediate }, backend, attrs: { perm: permuted } });
      var reshapedIntermediate2 = reshape({
        inputs: { x: transposedIntermediate },
        backend,
        attrs: { shape: reshapedPermuted }
      });
      var sliced = slice({
        inputs: { x: reshapedIntermediate2 },
        backend,
        attrs: { begin: sliceBeginCoords, size: sliceSize }
      });
      toDispose.push(reshapedIntermediate);
      toDispose.push(transposedIntermediate);
      toDispose.push(reshapedIntermediate2);
      toDispose.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return sliced;
    };
    var batchToSpaceNDConfig = {
      kernelName: tf.BatchToSpaceND,
      backendName: "webgl",
      kernelFunc: batchToSpaceND
    };
    function bincount(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, weights = inputs.weights;
      var size = attrs.size;
      var xVals = backend.readSync(x.dataId);
      var weightsVals = backend.readSync(weights.dataId);
      var outVals = bincountImplCPU(xVals, weightsVals, weights.dtype, weights.shape, size);
      return backend.makeTensorInfo([size], weights.dtype, outVals);
    }
    var bincountConfig = {
      kernelName: tf.Bincount,
      backendName: "webgl",
      kernelFunc: bincount
    };
    var BITWISEAND = "\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";
    var BITWISEAND_UNPACKED = "\n  return float(int(a.r) & int(b.r));\n";
    function bitwiseAnd(args) {
      var inputs = args.inputs, backend = args.backend;
      var a = inputs.a, b = inputs.b;
      var shouldUsePackedProgram = tf.env().getBool("WEBGL_PACK_BINARY_OPERATIONS");
      var versionNumber = tf.env().getNumber("WEBGL_VERSION");
      if (backend.shouldExecuteOnCPU([a, b]) || versionNumber === 1) {
        var aVals = backend.texData.get(a.dataId).values;
        var bVals = backend.texData.get(b.dataId).values;
        var _a2 = __read(bitwiseAndImplCPU(a.shape, b.shape, aVals, bVals, a.dtype), 2), outValues = _a2[0], outShape = _a2[1];
        var out = backend.makeTensorInfo(outShape, a.dtype);
        var outData = backend.texData.get(out.dataId);
        outData.values = outValues;
        return out;
      }
      var program;
      if (shouldUsePackedProgram) {
        program = new BinaryOpPackedProgram(BITWISEAND, a.shape, b.shape, false);
      } else {
        program = new BinaryOpProgram(BITWISEAND_UNPACKED, a.shape, b.shape);
      }
      return backend.runWebGLProgram(program, [a, b], a.dtype);
    }
    var bitwiseAndConfig = {
      kernelName: tf.BitwiseAnd,
      backendName: "webgl",
      kernelFunc: bitwiseAnd
    };
    function broadcastArgs(args) {
      var inputs = args.inputs, backend = args.backend;
      var s0 = inputs.s0, s1 = inputs.s1;
      var s0Vals = backend.readSync(s0.dataId);
      var s1Vals = backend.readSync(s1.dataId);
      var broadcastShape = tf.backend_util.assertAndGetBroadcastShape(Array.from(s0Vals), Array.from(s1Vals));
      return backend.makeTensorInfo([broadcastShape.length], "int32", Int32Array.from(broadcastShape));
    }
    var broadcastArgsConfig = {
      kernelName: tf.BroadcastArgs,
      backendName: "webgl",
      kernelFunc: broadcastArgs
    };
    var NOT_EQUAL = "return float(a != b);";
    var notEqual = binaryKernelFunc({ opSnippet: NOT_EQUAL, cpuKernelImpl: notEqualImplCPU, dtype: "bool" });
    var notEqualConfig = {
      kernelName: tf.NotEqual,
      backendName: "webgl",
      kernelFunc: notEqual
    };
    function real(args) {
      var inputs = args.inputs, backend = args.backend;
      var input = inputs.input;
      var inputData = backend.texData.get(input.dataId);
      return identity({ inputs: { x: inputData.complexTensorInfos.real }, backend });
    }
    var realConfig = {
      kernelName: tf.Real,
      backendName: "webgl",
      kernelFunc: real
    };
    var TO_INT = "return float(int(x));";
    function int(input, backend) {
      var program = new UnaryOpProgram(input.shape, TO_INT);
      var output = backend.runWebGLProgram(program, [input], "int32");
      return { dataId: output.dataId, shape: output.shape, dtype: output.dtype };
    }
    function cast(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var dtype = attrs.dtype;
      if (dtype === "complex64") {
        if (x.dtype === "complex64") {
          return identity({ inputs: { x }, backend });
        }
        var zerosTensor = tf__namespace.zeros(x.shape);
        var floatX = cast({ inputs: { x }, backend, attrs: { dtype: "float32" } });
        var result = complex({ inputs: { real: floatX, imag: zerosTensor }, backend });
        zerosTensor.dispose();
        backend.disposeIntermediateTensorInfo(floatX);
        return result;
      }
      if (x.dtype === "complex64") {
        var realPart = real({ inputs: { input: x }, backend });
        var result = cast({ inputs: { x: realPart }, backend, attrs: { dtype } });
        backend.disposeIntermediateTensorInfo(realPart);
        return result;
      }
      if (!tf.util.hasEncodingLoss(x.dtype, dtype)) {
        var result = identity({ inputs: { x }, backend });
        return { dataId: result.dataId, shape: result.shape, dtype };
      }
      if (backend.shouldExecuteOnCPU([x])) {
        var values = backend.texData.get(x.dataId).values;
        var _a2 = __read(castImplCPU(values, x.shape, x.dtype, dtype), 3), resultShape = _a2[0], resultType = _a2[1], resultData = _a2[2];
        return backend.makeTensorInfo(resultShape, resultType, resultData);
      }
      if (dtype === "int32") {
        return int(x, backend);
      }
      if (dtype === "bool") {
        var zerosTensorInfo = backend.makeTensorInfo([], "bool", tf.util.getTypedArrayFromDType("bool", 1));
        var binaryInputs = { a: x, b: zerosTensorInfo };
        var result = notEqual({ inputs: binaryInputs, backend });
        backend.disposeIntermediateTensorInfo(zerosTensorInfo);
        return result;
      }
      throw new Error("Error in Cast: failed to cast ".concat(x.dtype, " to ").concat(dtype));
    }
    var castConfig = {
      kernelName: tf.Cast,
      backendName: "webgl",
      kernelFunc: cast
    };
    var CEIL = "return ceil(x);";
    var ceil = unaryKernelFunc({ opSnippet: CEIL, packedOpSnippet: CEIL, cpuKernelImpl: ceilImplCPU });
    var ceilConfig = {
      kernelName: tf.Ceil,
      backendName: "webgl",
      kernelFunc: ceil
    };
    var ClipProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ClipProgram2(aShape) {
          this.variableNames = ["A"];
          this.customUniforms = [
            { name: "minVal", type: "float" },
            { name: "maxVal", type: "float" }
          ];
          this.outputShape = aShape;
          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    ";
        }
        return ClipProgram2;
      }()
    );
    var ClipPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ClipPackedProgram2(aShape) {
          this.variableNames = ["A"];
          this.packedInputs = true;
          this.packedOutput = true;
          this.customUniforms = [
            { name: "minVal", type: "float" },
            { name: "maxVal", type: "float" }
          ];
          this.outputShape = aShape;
          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    ";
        }
        return ClipPackedProgram2;
      }()
    );
    function clipByValue(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var clipValueMin = attrs.clipValueMin, clipValueMax = attrs.clipValueMax;
      var program;
      if (tf.env().getBool("WEBGL_PACK_CLIP")) {
        program = new ClipPackedProgram(x.shape);
      } else {
        program = new ClipProgram(x.shape);
      }
      var customValues = [[clipValueMin], [clipValueMax]];
      return backend.runWebGLProgram(program, [x], x.dtype, customValues);
    }
    var clipByValueConfig = {
      kernelName: tf.ClipByValue,
      backendName: "webgl",
      kernelFunc: clipByValue
    };
    var ComplexAbsProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ComplexAbsProgram2(shape) {
          this.variableNames = ["real", "imag"];
          this.outputShape = shape;
          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    ";
        }
        return ComplexAbsProgram2;
      }()
    );
    function makeComplexComponentTensorInfo(complexTensor, complexPart) {
      return {
        dataId: complexPart.dataId,
        dtype: complexPart.dtype,
        shape: complexTensor.shape
      };
    }
    function complexAbs(args) {
      var inputs = args.inputs, backend = args.backend;
      var x = inputs.x;
      var xData = backend.texData.get(x.dataId);
      var program = new ComplexAbsProgram(x.shape);
      var programInputs = [
        makeComplexComponentTensorInfo(x, xData.complexTensorInfos.real),
        makeComplexComponentTensorInfo(x, xData.complexTensorInfos.imag)
      ];
      return backend.runWebGLProgram(program, programInputs, programInputs[0].dtype);
    }
    var complexAbsConfig = {
      kernelName: tf.ComplexAbs,
      backendName: "webgl",
      kernelFunc: complexAbs
    };
    var ConcatProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ConcatProgram2(shapes) {
          this.outputShape = [];
          this.outputShape = tf.backend_util.computeOutShape(
            shapes,
            1
            /* axis */
          );
          this.variableNames = shapes.map(function(_, i2) {
            return "T".concat(i2);
          });
          var offsets = new Array(shapes.length - 1);
          offsets[0] = shapes[0][1];
          for (var i = 1; i < offsets.length; i++) {
            offsets[i] = offsets[i - 1] + shapes[i][1];
          }
          var snippets = ["if (yC < ".concat(offsets[0], ") setOutput(getT0(yR, yC));")];
          for (var i = 1; i < offsets.length; i++) {
            var shift = offsets[i - 1];
            snippets.push("else if (yC < ".concat(offsets[i], ") ") + "setOutput(getT".concat(i, "(yR, yC-").concat(shift, "));"));
          }
          var lastIndex = offsets.length;
          var lastShift = offsets[offsets.length - 1];
          snippets.push("else setOutput(getT".concat(lastIndex, "(yR, yC-").concat(lastShift, "));"));
          this.userCode = "\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int yR = coords.x;\n        int yC = coords.y;\n\n        ".concat(snippets.join("\n        "), "\n      }\n    ");
        }
        return ConcatProgram2;
      }()
    );
    var ConcatPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ConcatPackedProgram2(shapes, axis) {
          this.packedInputs = true;
          this.packedOutput = true;
          this.outputShape = [];
          this.outputShape = tf.backend_util.computeOutShape(shapes, axis);
          var shape = this.outputShape;
          var rank = shape.length;
          var dtype = getCoordsDataType(rank);
          var coords2 = getChannels("coords", rank);
          var channels = ["x", "y", "z", "w", "u", "v"].slice(0, rank);
          this.variableNames = shapes.map(function(_, i2) {
            return "T".concat(i2);
          });
          var offsets = new Array(shapes.length - 1);
          offsets[0] = shapes[0][axis];
          for (var i = 1; i < offsets.length; i++) {
            offsets[i] = offsets[i - 1] + shapes[i][axis];
          }
          var channel = channels[axis];
          var lastChannels = channels.slice(-2);
          var allChannels = channels.join();
          var getValueSnippet = "if (".concat(channel, " < ").concat(offsets[0], ") {\n        return getChannel(\n            getT0(").concat(allChannels, "), vec2(").concat(lastChannels.join(), "));\n        }");
          for (var i = 1; i < offsets.length; i++) {
            var shift_1 = offsets[i - 1];
            getValueSnippet += "\n        if (".concat(channel, " < ").concat(offsets[i], "  && ").concat(channel, " >= ").concat(offsets[i - 1], ") {\n          return getChannel(\n            getT").concat(i, "(").concat(shiftedChannels(channels, channel, shift_1), "),\n            vec2(").concat(shiftedChannels(lastChannels, channel, shift_1), "));\n        }");
          }
          var lastIndex = offsets.length;
          var shift = offsets[offsets.length - 1];
          getValueSnippet += "\n        return getChannel(\n          getT".concat(lastIndex, "(").concat(shiftedChannels(channels, channel, shift), "),\n          vec2(").concat(shiftedChannels(lastChannels, channel, shift), "));");
          this.userCode = "\n      float getValue(".concat(channels.map(function(x) {
            return "int " + x;
          }), ") {\n        ").concat(getValueSnippet, "\n      }\n\n      void main() {\n        ").concat(dtype, " coords = getOutputCoords();\n        vec4 result = vec4(getValue(").concat(coords2, "), 0., 0., 0.);\n\n        ").concat(coords2[rank - 1], " = ").concat(coords2[rank - 1], " + 1;\n        if (").concat(coords2[rank - 1], " < ").concat(shape[rank - 1], ") {\n          result.g = getValue(").concat(coords2, ");\n        }\n\n        ").concat(coords2[rank - 2], " = ").concat(coords2[rank - 2], " + 1;\n        if (").concat(coords2[rank - 2], " < ").concat(shape[rank - 2], ") {\n          result.a = getValue(").concat(coords2, ");\n        }\n\n        ").concat(coords2[rank - 1], " = ").concat(coords2[rank - 1], " - 1;\n        if (").concat(coords2[rank - 2], " < ").concat(shape[rank - 2], " &&\n            ").concat(coords2[rank - 1], " < ").concat(shape[rank - 1], ") {\n          result.b = getValue(").concat(coords2, ");\n        }\n        setOutput(result);\n      }\n    ");
        }
        return ConcatPackedProgram2;
      }()
    );
    function shiftedChannels(channels, channel, shift) {
      var channelIdx = channels.indexOf(channel);
      var res = channels.map(function(c, idx) {
        if (idx === channelIdx) {
          return "".concat(c, " - ").concat(shift);
        } else {
          return c;
        }
      });
      return res.join();
    }
    function imag(args) {
      var inputs = args.inputs, backend = args.backend;
      var input = inputs.input;
      var inputData = backend.texData.get(input.dataId);
      return identity({ inputs: { x: inputData.complexTensorInfos.imag }, backend });
    }
    var imagConfig = {
      kernelName: tf.Imag,
      backendName: "webgl",
      kernelFunc: imag
    };
    function concatImpl(inputs, axis, backend) {
      var e_12, _a2;
      var dtype = inputs[0].dtype;
      if (dtype === "complex64") {
        var reals = inputs.map(function(t) {
          return real({ inputs: { input: t }, backend });
        });
        var imags = inputs.map(function(t) {
          return imag({ inputs: { input: t }, backend });
        });
        var realConcated = concatImpl(reals, axis, backend);
        var imagConcated = concatImpl(imags, axis, backend);
        var result_1 = complex({ inputs: { real: realConcated, imag: imagConcated }, backend });
        reals.forEach(function(r) {
          return backend.disposeIntermediateTensorInfo(r);
        });
        imags.forEach(function(i2) {
          return backend.disposeIntermediateTensorInfo(i2);
        });
        backend.disposeIntermediateTensorInfo(realConcated);
        backend.disposeIntermediateTensorInfo(imagConcated);
        return result_1;
      }
      var runOnCpu = backend.shouldExecuteOnCPU(inputs);
      if (dtype === "string") {
        runOnCpu = true;
      }
      if (runOnCpu) {
        var tensors2D_1 = inputs.map(function(t) {
          var innerSize = tf.util.sizeFromShape(t.shape.slice(axis));
          var shape = [-1, innerSize];
          return reshape({ inputs: { x: t }, backend, attrs: { shape } });
        });
        var inputsValShapes = tensors2D_1.map(function(t) {
          return { vals: backend.readSync(t.dataId), shape: t.shape };
        });
        var outShape_1 = tf.backend_util.computeOutShape(
          tensors2D_1.map(function(t) {
            return t.shape;
          }),
          1
          /* axis */
        );
        var simplyConcat = tensors2D_1[0].shape[0] === 1;
        var outVals = concatImplCPU(inputsValShapes, outShape_1, dtype, simplyConcat);
        var finalOutShape = tf.backend_util.computeOutShape(inputs.map(function(t) {
          return t.shape;
        }), axis);
        var outInfo = backend.makeTensorInfo(finalOutShape, dtype, outVals);
        tensors2D_1.forEach(function(t) {
          return backend.disposeIntermediateTensorInfo(t);
        });
        return outInfo;
      }
      var $inputs = inputs.filter(function(t) {
        return tf.util.sizeFromShape(t.shape) > 0;
      });
      var shouldPack = tf.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS") && $inputs[0].shape.length > 1;
      if ($inputs.length === 1) {
        var program_1 = shouldPack ? new UnaryOpProgram(inputs[0].shape, CLONE) : new UnaryOpPackedProgram(inputs[0].shape, CLONE);
        return backend.runWebGLProgram(program_1, inputs, dtype);
      }
      var maxTexturesInShader = tf.env().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");
      if ($inputs.length > maxTexturesInShader) {
        var reducedInputs = [];
        for (var i = 0; i < $inputs.length; i += maxTexturesInShader) {
          var subArray = $inputs.slice(i, i + maxTexturesInShader);
          reducedInputs.push(concatImpl(subArray, axis, backend));
        }
        var result_2 = concatImpl(reducedInputs, axis, backend);
        try {
          for (var reducedInputs_1 = __values(reducedInputs), reducedInputs_1_1 = reducedInputs_1.next(); !reducedInputs_1_1.done; reducedInputs_1_1 = reducedInputs_1.next()) {
            var i = reducedInputs_1_1.value;
            backend.disposeIntermediateTensorInfo(i);
          }
        } catch (e_1_1) {
          e_12 = { error: e_1_1 };
        } finally {
          try {
            if (reducedInputs_1_1 && !reducedInputs_1_1.done && (_a2 = reducedInputs_1.return)) _a2.call(reducedInputs_1);
          } finally {
            if (e_12) throw e_12.error;
          }
        }
        return result_2;
      }
      if (shouldPack) {
        var program_2 = new ConcatPackedProgram($inputs.map(function(t) {
          return t.shape;
        }), axis);
        return backend.runWebGLProgram(program_2, $inputs, dtype);
      }
      var _b = computeTensors2D($inputs, axis, backend), tensors2D = _b.tensors2D, outShape = _b.outShape;
      var program = new ConcatProgram(tensors2D.map(function(t) {
        return t.shape;
      }));
      var result = backend.runWebGLProgram(program, tensors2D, dtype);
      tensors2D.forEach(function(r) {
        return backend.disposeIntermediateTensorInfo(r);
      });
      var reshapedResult = reshape({ inputs: { x: result }, attrs: { shape: outShape }, backend });
      backend.disposeIntermediateTensorInfo(result);
      return reshapedResult;
    }
    function computeTensors2D(inputs, axis, backend) {
      var outShape = tf.backend_util.computeOutShape(inputs.map(function(t) {
        return t.shape;
      }), axis);
      var tensors2D = inputs.map(function(x) {
        return reshape({
          inputs: { x },
          attrs: { shape: [-1, tf.util.sizeFromShape(x.shape.slice(axis))] },
          backend
        });
      });
      return { tensors2D, outShape };
    }
    function concat(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var axis = attrs.axis;
      var $axis = tf.util.parseAxisParam(axis, inputs[0].shape)[0];
      var shapes = inputs.map(function(t) {
        return t.shape;
      });
      tf.backend_util.assertParamsConsistent(shapes, $axis);
      var outShape = tf.backend_util.computeOutShape(inputs.map(function(t) {
        return t.shape;
      }), $axis);
      if (tf.util.sizeFromShape(outShape) === 0) {
        return backend.makeTensorInfo(outShape, inputs[0].dtype, []);
      }
      var $inputs = inputs.filter(function(t) {
        return tf.util.sizeFromShape(t.shape) > 0;
      });
      if ($inputs.length === 1) {
        return identity({ inputs: { x: $inputs[0] }, backend });
      }
      return concatImpl($inputs, $axis, backend);
    }
    var concatConfig = {
      kernelName: tf.Concat,
      backendName: "webgl",
      kernelFunc: concat
    };
    var Conv2DProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function Conv2DProgram2(convInfo, addBias, activation, hasPreluActivationWeights, hasLeakyreluAlpha) {
          if (addBias === void 0) {
            addBias = false;
          }
          if (activation === void 0) {
            activation = null;
          }
          if (hasPreluActivationWeights === void 0) {
            hasPreluActivationWeights = false;
          }
          if (hasLeakyreluAlpha === void 0) {
            hasLeakyreluAlpha = false;
          }
          this.variableNames = ["x", "W"];
          this.outputShape = convInfo.outShape;
          var padTop = convInfo.padInfo.top;
          var padLeft = convInfo.padInfo.left;
          var strideHeight = convInfo.strideHeight;
          var strideWidth = convInfo.strideWidth;
          var dilationHeight = convInfo.dilationHeight;
          var dilationWidth = convInfo.dilationWidth;
          var filterHeight = convInfo.filterHeight;
          var filterWidth = convInfo.filterWidth;
          var inputDepthNearestVec4 = Math.floor(convInfo.inChannels / 4) * 4;
          var inputDepthVec4Remainder = convInfo.inChannels % 4;
          var isChannelsLast = convInfo.dataFormat === "channelsLast";
          var rowDim = isChannelsLast ? 1 : 2;
          var colDim = isChannelsLast ? 2 : 3;
          var channelDim = isChannelsLast ? 3 : 1;
          var activationSnippet = "", applyActivationSnippet = "";
          if (activation) {
            if (hasPreluActivationWeights) {
              activationSnippet = "float activation(float a) {\n          float b = getPreluActivationWeightsAtOutCoords();\n          ".concat(activation, "\n        }");
            } else if (hasLeakyreluAlpha) {
              activationSnippet = "float activation(float a) {\n          float b = getLeakyreluAlphaAtOutCoords();\n          ".concat(activation, "\n        }");
            } else {
              activationSnippet = "\n          float activation(float x) {\n            ".concat(activation, "\n          }\n        ");
            }
            applyActivationSnippet = "result = activation(result);";
          }
          var addBiasSnippet = addBias ? "result += getBiasAtOutCoords();" : "";
          if (addBias) {
            this.variableNames.push("bias");
          }
          if (hasPreluActivationWeights) {
            this.variableNames.push("preluActivationWeights");
          }
          if (hasLeakyreluAlpha) {
            this.variableNames.push("leakyreluAlpha");
          }
          this.userCode = "\n      ".concat(activationSnippet, "\n\n      const ivec2 strides = ivec2(").concat(strideHeight, ", ").concat(strideWidth, ");\n      const ivec2 pads = ivec2(").concat(padTop, ", ").concat(padLeft, ");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d2 = coords[").concat(channelDim, "];\n\n        ivec2 xRCCorner =\n            ivec2(coords[").concat(rowDim, "], coords[").concat(colDim, "]) * 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 < ").concat(filterHeight, "; wR++) {\n          int xR = xRCorner + wR * ").concat(dilationHeight, ";\n\n          if (xR < 0 || xR >= ").concat(convInfo.inHeight, ") {\n            continue;\n          }\n\n          for (int wC = 0; wC < ").concat(filterWidth, "; wC++) {\n            int xC = xCCorner + wC * ").concat(dilationWidth, ";\n\n            if (xC < 0 || xC >= ").concat(convInfo.inWidth, ") {\n              continue;\n            }\n\n            for (int d1 = 0; d1 < ").concat(inputDepthNearestVec4, "; 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 (").concat(isChannelsLast, ") {\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 (").concat(inputDepthVec4Remainder === 1, ") {\n\n              if (").concat(isChannelsLast, ") {\n                dotProd +=\n                    getX(batch, xR, xC, ").concat(inputDepthNearestVec4, ") *\n                    getW(wR, wC, ").concat(inputDepthNearestVec4, ", d2);\n              } else {\n                dotProd +=\n                    getX(batch, ").concat(inputDepthNearestVec4, ", xR, xC) *\n                    getW(wR, wC, ").concat(inputDepthNearestVec4, ", d2);\n              }\n\n            } else if (").concat(inputDepthVec4Remainder === 2, ") {\n              vec2 wValues = vec2(\n                getW(wR, wC, ").concat(inputDepthNearestVec4, ", d2),\n                getW(wR, wC, ").concat(inputDepthNearestVec4, " + 1, d2)\n              );\n\n              if (").concat(isChannelsLast, ") {\n                vec2 xValues = vec2(\n                  getX(batch, xR, xC, ").concat(inputDepthNearestVec4, "),\n                  getX(batch, xR, xC, ").concat(inputDepthNearestVec4, " + 1)\n                );\n                dotProd += dot(xValues, wValues);\n              } else {\n                vec2 xValues = vec2(\n                  getX(batch, ").concat(inputDepthNearestVec4, ", xR, xC),\n                  getX(batch, ").concat(inputDepthNearestVec4, " + 1, xR, xC)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n\n            } else if (").concat(inputDepthVec4Remainder === 3, ") {\n              vec3 wValues = vec3(\n                getW(wR, wC, ").concat(inputDepthNearestVec4, ", d2),\n                getW(wR, wC, ").concat(inputDepthNearestVec4, " + 1, d2),\n                getW(wR, wC, ").concat(inputDepthNearestVec4, " + 2, d2)\n              );\n\n              if (").concat(isChannelsLast, ") {\n                vec3 xValues = vec3(\n                  getX(batch, xR, xC, ").concat(inputDepthNearestVec4, "),\n                  getX(batch, xR, xC, ").concat(inputDepthNearestVec4, " + 1),\n                  getX(batch, xR, xC, ").concat(inputDepthNearestVec4, " + 2)\n                );\n                dotProd += dot(xValues, wValues);\n              } else {\n                vec3 xValues = vec3(\n                  getX(batch, ").concat(inputDepthNearestVec4, ", xR, xC),\n                  getX(batch, ").concat(inputDepthNearestVec4, " + 1, xR, xC),\n                  getX(batch, ").concat(inputDepthNearestVec4, " + 2, xR, xC)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n\n            }\n          }\n        }\n\n        float result = dotProd;\n        ").concat(addBiasSnippet, "\n        ").concat(applyActivationSnippet, "\n        setOutput(result);\n      }\n    ");
        }
        return Conv2DProgram2;
      }()
    );
    var Conv3DProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function Conv3DProgram2(convInfo) {
          this.variableNames = ["x", "W"];
          this.outputShape = convInfo.outShape;
          var padFront = convInfo.padInfo.front;
          var padTop = convInfo.padInfo.top;
          var padLeft = convInfo.padInfo.left;
          var strideDepth = convInfo.strideDepth;
          var strideHeight = convInfo.strideHeight;
          var strideWidth = convInfo.strideWidth;
          var dilationDepth = convInfo.dilationDepth;
          var dilationHeight = convInfo.dilationHeight;
          var dilationWidth = convInfo.dilationWidth;
          var filterDepth = convInfo.filterDepth;
          var filterHeight = convInfo.filterHeight;
          var filterWidth = convInfo.filterWidth;
          var inputDepthNearestVec4 = Math.floor(convInfo.inChannels / 4) * 4;
          var inputDepthVec4Remainder = convInfo.inChannels % 4;
          this.userCode = "\n      const ivec3 strides = ivec3(".concat(strideDepth, ", ").concat(strideHeight, ", ").concat(strideWidth, ");\n      const ivec3 pads = ivec3(").concat(padFront, ", ").concat(padTop, ", ").concat(padLeft, ");\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 < ").concat(filterDepth, "; wF++) {\n          int xF = xFCorner + wF * ").concat(dilationDepth, ";\n\n          if (xF < 0 || xF >= ").concat(convInfo.inDepth, ") {\n            continue;\n          }\n\n          for (int wR = 0; wR < ").concat(filterHeight, "; wR++) {\n            int xR = xRCorner + wR * ").concat(dilationHeight, ";\n\n            if (xR < 0 || xR >= ").concat(convInfo.inHeight, ") {\n              continue;\n            }\n\n            for (int wC = 0; wC < ").concat(filterWidth, "; wC++) {\n              int xC = xCCorner + wC * ").concat(dilationWidth, ";\n\n              if (xC < 0 || xC >= ").concat(convInfo.inWidth, ") {\n                continue;\n              }\n\n              for (int d1 = 0; d1 < ").concat(inputDepthNearestVec4, "; 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 (").concat(inputDepthVec4Remainder === 1, ") {\n                dotProd +=\n                  getX(batch, xF, xR, xC, ").concat(inputDepthNearestVec4, ") *\n                  getW(wF, wR, wC, ").concat(inputDepthNearestVec4, ", d2);\n              } else if (").concat(inputDepthVec4Remainder === 2, ") {\n                vec2 xValues = vec2(\n                  getX(batch, xF, xR, xC, ").concat(inputDepthNearestVec4, "),\n                  getX(batch, xF, xR, xC, ").concat(inputDepthNearestVec4, " + 1)\n                );\n                vec2 wValues = vec2(\n                  getW(wF, wR, wC, ").concat(inputDepthNearestVec4, ", d2),\n                  getW(wF, wR, wC, ").concat(inputDepthNearestVec4, " + 1, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              } else if (").concat(inputDepthVec4Remainder === 3, ") {\n                vec3 xValues = vec3(\n                  getX(batch, xF, xR, xC, ").concat(inputDepthNearestVec4, "),\n                  getX(batch, xF, xR, xC, ").concat(inputDepthNearestVec4, " + 1),\n                  getX(batch, xF, xR, xC, ").concat(inputDepthNearestVec4, " + 2)\n                );\n                vec3 wValues = vec3(\n                  getW(wF, wR, wC, ").concat(inputDepthNearestVec4, ", d2),\n                  getW(wF, wR, wC, ").concat(inputDepthNearestVec4, " + 1, d2),\n                  getW(wF, wR, wC, ").concat(inputDepthNearestVec4, " + 2, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    ");
        }
        return Conv3DProgram2;
      }()
    );
    var Conv2DPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function Conv2DPackedProgram2(convInfo, addBias, activation, hasPreluActivation, hasLeakyReluAlpha) {
          if (addBias === void 0) {
            addBias = false;
          }
          if (activation === void 0) {
            activation = null;
          }
          if (hasPreluActivation === void 0) {
            hasPreluActivation = false;
          }
          if (hasLeakyReluAlpha === void 0) {
            hasLeakyReluAlpha = false;
          }
          this.variableNames = ["x", "W"];
          this.packedInputs = true;
          this.packedOutput = true;
          this.customUniforms = [
            { name: "pads", type: "ivec2" },
            { name: "strides", type: "ivec2" },
            { name: "dilations", type: "ivec2" },
            { name: "inDims", type: "ivec2" }
          ];
          this.outputShape = convInfo.outShape;
          this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);
          var padLeft = convInfo.padInfo.left;
          var strideWidth = convInfo.strideWidth;
          var dilationWidth = convInfo.dilationWidth;
          var filterHeight = convInfo.filterHeight;
          var filterWidth = convInfo.filterWidth;
          var texelsAcross = filterWidth;
          var mainLoop = "\n       int xR; int xC; int xCOffset;\n       vec4 wTexel; vec4 previous; vec4 final;";
          for (var c = 0; c < filterWidth; c++) {
            mainLoop += "\n           vec4 xTexelC".concat(c * 2, ";\n           int xTexelC").concat(c * 2, "Ready;\n           vec4 xTexelC").concat(c * 2 + 1, ";\n           int xTexelC").concat(c * 2 + 1, "Ready;\n           vec4 xC").concat(c, ";");
          }
          mainLoop += "\n     for (int r = 0; r < ".concat(filterHeight, "; r++) {\n      for (int d1 = 0; d1 < ").concat(convInfo.inChannels, "; d1 += 2) {\n       ");
          for (var c = 0; c < filterWidth; c++) {
            mainLoop += "\n           xTexelC".concat(c * 2, " = vec4(0.0);\n           xTexelC").concat(c * 2, "Ready = 0;\n           xTexelC").concat(c * 2 + 1, " = vec4(0.0);\n           xTexelC").concat(c * 2 + 1, "Ready = 0;\n           xC").concat(c, " = vec4(0.0);");
          }
          mainLoop += "\n         xR = xRCorner + r * dilations[0];\n         if (xR >=0 && xR < inDims[0]) {\n       ";
          for (var texelC = 0; texelC < (texelsAcross + 1) / 2; texelC++) {
            var colIndex = texelC * 2;
            mainLoop += "\n           xC = xCCorner + ".concat(colIndex * dilationWidth, ";\n           ");
            if (strideWidth === 1) {
              if (colIndex < filterWidth) {
                if (padLeft % 2 === 1) {
                  mainLoop += "\n                 xCOffset = xC + 1;\n                 if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC".concat(colIndex, "Ready == 0) {\n                   xTexelC").concat(colIndex, " = 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").concat(colIndex, ".zw = vec2(0.0);\n                   }\n                   xTexelC").concat(colIndex, "Ready = 1;\n                 }\n               ");
                  if (dilationWidth === 1 && colIndex > 0) {
                    mainLoop += "\n                 xC".concat(colIndex, " = vec4(xTexelC").concat(colIndex - 2, ".zw, xTexelC").concat(colIndex, ".xy);\n                 ");
                  } else {
                    mainLoop += "\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".concat(colIndex, " = vec4(previous.zw, xTexelC").concat(colIndex, ".xy);\n                   } else {\n                     xC").concat(colIndex, " = vec4(0.0, 0.0, xTexelC").concat(colIndex, ".xy);\n                   }\n                   ");
                  }
                } else {
                  mainLoop += "\n                 if (xC >= 0 && xC < inDims[1] && xTexelC".concat(colIndex, "Ready == 0) {\n                   xTexelC").concat(colIndex, " = getX(batch, xR, xC, d1);\n                   if (xC + 1 >= inDims[1]) {\n                     xTexelC").concat(colIndex, ".zw = vec2(0.0);\n                   }\n                   xTexelC").concat(colIndex, "Ready = 1;\n                 }\n\n                 xC").concat(colIndex, " = xTexelC").concat(colIndex, ";\n                 ");
                }
                if (colIndex + 1 < filterWidth) {
                  var nextTexelOffset = padLeft % 2 === 0 ? tf.util.nearestLargerEven(dilationWidth) : dilationWidth;
                  if (dilationWidth % 2 === 0 && padLeft % 2 === 1 || dilationWidth % 2 !== 0 && padLeft % 2 !== 1) {
                    mainLoop += "\n                   xCOffset = xC + imod(pads[1], 2) + ".concat(nextTexelOffset, ";\n\n                   if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC").concat(colIndex + 1, "Ready == 0) {\n                     xTexelC").concat(colIndex + 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").concat(colIndex + 1, ".zw = vec2(0.0);\n                     }\n                     xTexelC").concat(colIndex + 1, "Ready = 1;\n                   }\n                   ");
                    if (dilationWidth > 1) {
                      mainLoop += "\n                     xCOffset -= 2;\n                     if (xCOffset >= 0 && xCOffset < inDims[1]) {\n                      previous = getX(batch, xR, xCOffset, d1);\n                      xC".concat(colIndex + 1, " = vec4(previous.zw, xTexelC").concat(colIndex + 1, ".xy);\n                     } else {\n                      xC").concat(colIndex + 1, " = vec4(0.0, 0.0, xTexelC").concat(colIndex + 1, ".xy);\n                     }\n                     ");
                    } else {
                      mainLoop += "\n                     xC".concat(colIndex + 1, " = vec4(xTexelC").concat(colIndex, ".zw, xTexelC").concat(colIndex + 1, ".xy);\n                     ");
                    }
                  } else {
                    if (nextTexelOffset === 1) {
                      mainLoop += "\n                     xC".concat(colIndex + 1, " = xTexelC").concat(colIndex, ";\n                     ");
                    } else {
                      mainLoop += "\n                     xCOffset = xC + ".concat(nextTexelOffset, ";\n\n                     if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC").concat(colIndex + 1, "Ready == 0) {\n                       xTexelC").concat(colIndex + 1, " = getX(batch, xR, xCOffset, d1);\n                       if (xCOffset + 1 >= inDims[1]) {\n                         xTexelC").concat(colIndex + 1, ".zw = vec2(0.0);\n                       }\n                       xTexelC").concat(colIndex + 1, "Ready = 1;\n                     }\n\n                     xC").concat(colIndex + 1, " = xTexelC").concat(colIndex + 1, ";\n                     ");
                    }
                  }
                }
              }
            } else {
              if (colIndex < filterWidth) {
                if (padLeft % 2 === 1) {
                  mainLoop += "\n                 xCOffset = xC + 1 - strides[1];\n                 if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC".concat(colIndex, "Ready == 0) {\n                   xTexelC").concat(colIndex, " = 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").concat(colIndex, ".zw = vec2(0.0);\n                   }\n                   xTexelC").concat(colIndex, "Ready = 1;\n                 }\n\n                 if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC").concat(colIndex + 1, "Ready == 0) {\n                   xTexelC").concat(colIndex + 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").concat(colIndex + 1, ".zw = vec2(0.0);\n                   }\n                   xTexelC").concat(colIndex + 1, "Ready = 1;\n                 }\n\n                 xC").concat(colIndex, " = vec4(xTexelC").concat(colIndex, ".zw, xTexelC").concat(colIndex + 1, ".zw);\n               ");
                  if (colIndex + 1 < filterWidth) {
                    mainLoop += "\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".concat(colIndex + 1, " = vec4(xTexelC").concat(colIndex + 1, ".xy, final.xy);\n                 ");
                  }
                } else {
                  mainLoop += "\n                 if(xC >= 0 && xC < inDims[1] && xTexelC".concat(colIndex, "Ready == 0) {\n                   xTexelC").concat(colIndex, " = getX(batch, xR, xC, d1);\n                   if (xC + 1 >= inDims[1]) {\n                     xTexelC").concat(colIndex, ".zw = vec2(0.0);\n                   }\n                   xTexelC").concat(colIndex, "Ready = 1;\n                 }\n\n                 xCOffset = xC + strides[1];\n                 if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC").concat(colIndex + 1, "Ready == 0) {\n                   xTexelC").concat(colIndex + 1, " = getX(batch, xR, xCOffset, d1);\n                   if (xCOffset + 1 >= inDims[1]) {\n                     xTexelC").concat(colIndex + 1, ".zw = vec2(0.);\n                   }\n                   xTexelC").concat(colIndex + 1, "Ready = 1;\n                 }\n\n                 xC").concat(colIndex, " = vec4(\n                   xTexelC").concat(colIndex, ".xy, xTexelC").concat(colIndex + 1, ".xy);\n               ");
                  if (colIndex + 1 < filterWidth) {
                    mainLoop += "\n                   xC".concat(colIndex + 1, " = vec4(xTexelC").concat(colIndex, ".zw, xTexelC").concat(colIndex + 1, ".zw);\n                 ");
                  }
                }
              }
            }
            if (colIndex < filterWidth) {
              mainLoop += "\n             wTexel = getW(r, ".concat(colIndex, ", d1, d2);\n             dotProd += xC").concat(colIndex, ".xxzz * vec4(wTexel.xy, wTexel.xy);\n             if(d1 + 1 < ").concat(convInfo.inChannels, ") {\n               dotProd += xC").concat(colIndex, ".yyww * vec4(wTexel.zw, wTexel.zw);\n             }\n           ");
              if (colIndex + 1 < filterWidth) {
                mainLoop += "\n               wTexel = getW(r, ".concat(colIndex + 1, ", d1, d2);\n               dotProd += xC").concat(colIndex + 1, ".xxzz * vec4(wTexel.xy, wTexel.xy);\n               if(d1 + 1 < ").concat(convInfo.inChannels, ") {\n                 dotProd += xC").concat(colIndex + 1, ".yyww * vec4(wTexel.zw, wTexel.zw);\n               }\n             ");
              }
            }
          }
          mainLoop += "\n     }\n   ";
          mainLoop += "\n     }\n   ";
          mainLoop += "\n     }\n   ";
          var activationSnippet = "", applyActivationSnippet = "";
          if (activation) {
            if (hasPreluActivation) {
              activationSnippet = "vec4 activation(vec4 a) {\n           vec4 b = getPreluActivationWeightsAtOutCoords();\n           ".concat(activation, "\n         }");
            } else if (hasLeakyReluAlpha) {
              activationSnippet = "vec4 activation(vec4 a) {\n           vec4 b = getLeakyreluAlphaAtOutCoords();\n           ".concat(activation, "\n         }");
            } else {
              activationSnippet = "vec4 activation(vec4 x) {\n           ".concat(activation, "\n         }");
            }
            applyActivationSnippet = "result = activation(result);";
          }
          var addBiasSnippet = addBias ? "result += getBiasAtOutCoords();" : "";
          if (addBias) {
            this.variableNames.push("bias");
          }
          if (hasPreluActivation) {
            this.variableNames.push("preluActivationWeights");
          }
          if (hasLeakyReluAlpha) {
            this.variableNames.push("leakyreluAlpha");
          }
          this.userCode = "\n       ".concat(activationSnippet, "\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         ").concat(mainLoop, "\n\n         vec4 result = dotProd - vec4(0.000000000000001);\n         ").concat(addBiasSnippet, "\n         ").concat(applyActivationSnippet, "\n         setOutput(result);\n       }\n     ");
        }
        return Conv2DPackedProgram2;
      }()
    );
    var Im2ColPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function Im2ColPackedProgram2(outputShape, convInfo) {
          this.variableNames = ["A"];
          this.packedInputs = true;
          this.packedOutput = true;
          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 = outputShape;
          this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);
          var dataFormat = convInfo.dataFormat;
          var glsl = getGlslDifferences();
          var isChannelsLast = dataFormat === "channelsLast";
          var rowDim = isChannelsLast ? 1 : 2;
          var colDim = isChannelsLast ? 2 : 3;
          var boundsCheckingSnippet = this.enableShapeUniforms ? "if(blockIndex < outShape[2] && pos < outShape[1]) {" : "if(blockIndex < ".concat(outputShape[2], " && pos < ").concat(outputShape[1], ") {");
          var unrolled = "";
          for (var row = 0; row <= 1; row++) {
            for (var col = 0; col <= 1; col++) {
              unrolled += "\n          blockIndex = rc.z + ".concat(col, ";\n          pos = rc.y + ").concat(row, ";\n\n          ").concat(boundsCheckingSnippet, "\n            offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];\n            d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);\n\n            if(d0 < inputShape[").concat(rowDim, "] && 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[").concat(colDim, "] && d1 >= 0) {\n\n                ch = imod(pos, inChannels);\n\n                if (").concat(isChannelsLast, ") {\n                  innerDims = vec2(d1, ch);\n                  result[").concat(row * 2 + col, "] = getChannel(\n                    getA(rc.x, d0, int(innerDims.x),\n                    int(innerDims.y)), innerDims);\n                } else {\n                  innerDims = vec2(d0, d1);\n                  result[").concat(row * 2 + col, "] = 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        ".concat(unrolled, "\n\n        ").concat(glsl.output, " = result;\n      }\n    ");
        }
        return Im2ColPackedProgram2;
      }()
    );
    function getShapeForBatchMatMul(shape, isChannelsLast) {
      var length = shape.length;
      if (length >= 3) {
        return isChannelsLast ? __spreadArray(__spreadArray([], __read(
          shape.slice(0, -3)
          /* batch */
        ), false), [
          shape[length - 3] * shape[length - 2],
          shape[length - 1]
          /* channel */
        ], false) : __spreadArray(__spreadArray([], __read(
          shape.slice(0, -3)
          /* batch */
        ), false), [
          shape[length - 3],
          shape[length - 2] * shape[length - 1]
          /* height * width */
        ], false);
      } else if (!isChannelsLast && length === 1 && shape[0] > 1) {
        return [shape[0], 1];
      } else {
        return null;
      }
    }
    function conv2dByMatMul(_a2) {
      var e_12, _b;
      var x = _a2.x, filter = _a2.filter, convInfo = _a2.convInfo, backend = _a2.backend, _c = _a2.bias, bias = _c === void 0 ? null : _c, _d = _a2.preluActivationWeights, preluActivationWeights = _d === void 0 ? null : _d, _e = _a2.leakyreluAlpha, leakyreluAlpha = _e === void 0 ? 0 : _e, _f = _a2.activation, activation = _f === void 0 ? null : _f;
      var xShape = x.shape;
      var xTexData = backend.texData.get(x.dataId);
      var sharedMatMulDim = convInfo.inChannels;
      var outerShapeX = xShape[0] * xShape[1] * xShape[2];
      var outerShapeFilter = convInfo.outChannels;
      var isChannelsLast = convInfo.dataFormat === "channelsLast";
      var transposeA = false;
      var transposeB = false;
      var out;
      var intermediates = [];
      if (preluActivationWeights != null) {
        var targetShape = getShapeForBatchMatMul(preluActivationWeights.shape, isChannelsLast);
        if (targetShape != null) {
          preluActivationWeights = reshape({
            inputs: { x: preluActivationWeights },
            backend,
            attrs: { shape: targetShape }
          });
          intermediates.push(preluActivationWeights);
        }
      }
      if (bias != null) {
        var targetShape = getShapeForBatchMatMul(bias.shape, isChannelsLast);
        if (targetShape != null) {
          bias = reshape({ inputs: { x: bias }, backend, attrs: { shape: targetShape } });
          intermediates.push(bias);
        }
      }
      var batchMatMulWillBeUnpacked = (outerShapeX === 1 || outerShapeFilter === 1) && sharedMatMulDim > MATMUL_SHARED_DIM_THRESHOLD;
      var canOptimize = !batchMatMulWillBeUnpacked && xTexData.isPacked && isChannelsLast && xTexData.texture != null && xShape[2] % 2 !== 0 && tf.util.arraysEqual(xTexData.shape.slice(-3), xShape.slice(-3));
      if (canOptimize) {
        var targetShape = xShape[0] * xShape[1] * (xShape[2] + 1);
        var xReshaped_1 = {
          dataId: x.dataId,
          shape: [1, targetShape, convInfo.inChannels],
          dtype: x.dtype
        };
        var originalXTexDataShape = xTexData.shape;
        xTexData.shape = xTexData.shape.slice();
        xTexData.shape[xTexData.shape.length - 2]++;
        tf.util.assert(isReshapeFree(xTexData.shape, xReshaped_1.shape), function() {
          return "packed reshape ".concat(xTexData.shape, " to ").concat(xReshaped_1.shape, " isn't free");
        });
        var filterReshaped = reshape({
          inputs: { x: filter },
          backend,
          attrs: { shape: [1, convInfo.inChannels, convInfo.outChannels] }
        });
        intermediates.push(filterReshaped);
        var pointwiseConv = batchMatMulImpl({
          a: xReshaped_1,
          b: filterReshaped,
          backend,
          transposeA,
          transposeB,
          bias,
          activation,
          preluActivationWeights,
          leakyreluAlpha
        });
        var pointwiseConvTexData = backend.texData.get(pointwiseConv.dataId);
        tf.util.assert(pointwiseConvTexData.isPacked, function() {
          return "batchMatMul result is expected to be packed";
        });
        xTexData.shape = originalXTexDataShape;
        pointwiseConvTexData.shape = convInfo.outShape;
        out = identity({ inputs: { x: pointwiseConv }, backend });
        out.shape = convInfo.outShape;
        intermediates.push(pointwiseConv);
      } else {
        var numCols = convInfo.outHeight * convInfo.outWidth;
        var xReshaped = reshape({
          inputs: { x },
          backend,
          attrs: {
            shape: isChannelsLast ? [convInfo.batchSize, numCols, convInfo.inChannels] : [convInfo.batchSize, convInfo.inChannels, numCols]
          }
        });
        var filterReshaped = reshape({
          inputs: { x: filter },
          backend,
          attrs: { shape: [1, convInfo.inChannels, convInfo.outChannels] }
        });
        var result = batchMatMulImpl({
          a: isChannelsLast ? xReshaped : filterReshaped,
          b: isChannelsLast ? filterReshaped : xReshaped,
          transposeA: !isChannelsLast,
          transposeB,
          backend,
          bias,
          activation,
          preluActivationWeights,
          leakyreluAlpha
        });
        out = reshape({ inputs: { x: result }, backend, attrs: { shape: convInfo.outShape } });
        intermediates.push(xReshaped);
        intermediates.push(filterReshaped);
        intermediates.push(result);
      }
      try {
        for (var intermediates_1 = __values(intermediates), intermediates_1_1 = intermediates_1.next(); !intermediates_1_1.done; intermediates_1_1 = intermediates_1.next()) {
          var i = intermediates_1_1.value;
          backend.disposeIntermediateTensorInfo(i);
        }
      } catch (e_1_1) {
        e_12 = { error: e_1_1 };
      } finally {
        try {
          if (intermediates_1_1 && !intermediates_1_1.done && (_b = intermediates_1.return)) _b.call(intermediates_1);
        } finally {
          if (e_12) throw e_12.error;
        }
      }
      return out;
    }
    function conv2dWithIm2Row(_a2) {
      var e_2, _b;
      var x = _a2.x, filter = _a2.filter, convInfo = _a2.convInfo, backend = _a2.backend, _c = _a2.bias, bias = _c === void 0 ? null : _c, _d = _a2.preluActivationWeights, preluActivationWeights = _d === void 0 ? null : _d, _e = _a2.leakyreluAlpha, leakyreluAlpha = _e === void 0 ? 0 : _e, _f = _a2.activation, activation = _f === void 0 ? null : _f;
      var filterWidth = convInfo.filterWidth, filterHeight = convInfo.filterHeight, inChannels = convInfo.inChannels, outWidth = convInfo.outWidth, outHeight = convInfo.outHeight, dataFormat = convInfo.dataFormat;
      var isChannelsLast = dataFormat === "channelsLast";
      var sharedDim = filterWidth * filterHeight * inChannels;
      var numCols = outHeight * outWidth;
      var x2ColShape = [convInfo.batchSize, sharedDim, numCols];
      var transposeA = true;
      var transposeB = false;
      var intermediates = [];
      if (preluActivationWeights != null) {
        var targetShape = getShapeForBatchMatMul(preluActivationWeights.shape, isChannelsLast);
        if (targetShape != null) {
          preluActivationWeights = reshape({
            inputs: { x: preluActivationWeights },
            backend,
            attrs: { shape: targetShape }
          });
          intermediates.push(preluActivationWeights);
        }
      }
      if (bias != null) {
        var targetShape = getShapeForBatchMatMul(bias.shape, isChannelsLast);
        if (targetShape != null) {
          bias = reshape({ inputs: { x: bias }, backend, attrs: { shape: targetShape } });
          intermediates.push(bias);
        }
      }
      var w2Row = reshape({
        inputs: { x: filter },
        backend,
        attrs: { shape: [1, sharedDim, tf.util.sizeFromShape(filter.shape) / sharedDim] }
      });
      intermediates.push(w2Row);
      var im2ColProgram = new Im2ColPackedProgram(x2ColShape, convInfo);
      var customValues = [
        x.shape,
        [convInfo.padInfo.top, convInfo.padInfo.left],
        [convInfo.strideHeight, convInfo.strideWidth],
        [convInfo.dilationHeight, convInfo.dilationWidth],
        [convInfo.inChannels],
        [convInfo.filterWidth * convInfo.inChannels],
        [convInfo.outWidth]
      ];
      var im2Col = backend.runWebGLProgram(im2ColProgram, [x], "float32", customValues);
      var im2ColReshaped = reshape({ inputs: { x: im2Col }, backend, attrs: { shape: x2ColShape } });
      intermediates.push(im2Col);
      intermediates.push(im2ColReshaped);
      var hasBias = bias != null;
      var hasPreluActivationWeights = preluActivationWeights != null;
      var hasLeakyreluAlpha = activation === "leakyrelu";
      var fusedActivation = activation ? mapActivationToShaderProgram(activation, true) : null;
      var matmulProgram = new MatMulPackedProgram(isChannelsLast ? im2ColReshaped.shape : w2Row.shape, isChannelsLast ? w2Row.shape : im2ColReshaped.shape, isChannelsLast ? [convInfo.batchSize, numCols, convInfo.outChannels] : [convInfo.batchSize, convInfo.outChannels, numCols], transposeA, transposeB, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
      var inputs = isChannelsLast ? [im2ColReshaped, w2Row] : [w2Row, im2ColReshaped];
      if (bias) {
        inputs.push(bias);
      }
      if (hasPreluActivationWeights) {
        inputs.push(preluActivationWeights);
      }
      if (hasLeakyreluAlpha) {
        var $leakyreluAlpha = backend.makeTensorInfo([], "float32", tf.util.createScalarValue(leakyreluAlpha, "float32"));
        inputs.push($leakyreluAlpha);
        intermediates.push($leakyreluAlpha);
      }
      var product = backend.runWebGLProgram(matmulProgram, inputs, "float32");
      var out = reshape({ inputs: { x: product }, backend, attrs: { shape: convInfo.outShape } });
      intermediates.push(product);
      try {
        for (var intermediates_2 = __values(intermediates), intermediates_2_1 = intermediates_2.next(); !intermediates_2_1.done; intermediates_2_1 = intermediates_2.next()) {
          var i = intermediates_2_1.value;
          backend.disposeIntermediateTensorInfo(i);
        }
      } catch (e_2_1) {
        e_2 = { error: e_2_1 };
      } finally {
        try {
          if (intermediates_2_1 && !intermediates_2_1.done && (_b = intermediates_2.return)) _b.call(intermediates_2);
        } finally {
          if (e_2) throw e_2.error;
        }
      }
      return out;
    }
    function conv2d(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, filter = inputs.filter;
      var strides = attrs.strides, pad = attrs.pad, dataFormat = attrs.dataFormat, dilations = attrs.dilations, dimRoundingMode = attrs.dimRoundingMode;
      var $dataFormat = tf.backend_util.convertConv2DDataFormat(dataFormat);
      var convInfo = tf.backend_util.computeConv2DInfo(x.shape, filter.shape, strides, dilations, pad, dimRoundingMode, false, $dataFormat);
      var out;
      if (convInfo.filterHeight === 1 && convInfo.filterWidth === 1 && convInfo.dilationHeight === 1 && convInfo.dilationWidth === 1 && convInfo.strideHeight === 1 && convInfo.strideWidth === 1 && (convInfo.padInfo.type === "SAME" || convInfo.padInfo.type === "VALID")) {
        out = conv2dByMatMul({ x, filter, convInfo, backend });
      } else if (convInfo.strideWidth <= 2 && $dataFormat === "channelsLast" && tf.env().getBool("WEBGL_EXP_CONV")) {
        var program = new Conv2DPackedProgram(convInfo);
        var customValues = [
          [convInfo.padInfo.top, convInfo.padInfo.left],
          [convInfo.strideHeight, convInfo.strideWidth],
          [convInfo.dilationHeight, convInfo.dilationWidth],
          [convInfo.inHeight, convInfo.inWidth]
        ];
        out = backend.runWebGLProgram(program, [x, filter], "float32", customValues);
      } else if (tf.env().getBool("WEBGL_CONV_IM2COL")) {
        out = conv2dWithIm2Row({ x, filter, convInfo, backend });
      } else {
        var program = new Conv2DProgram(convInfo);
        out = backend.runWebGLProgram(program, [x, filter], "float32");
      }
      var outReshaped = reshape({ inputs: { x: out }, backend, attrs: { shape: convInfo.outShape } });
      backend.disposeIntermediateTensorInfo(out);
      return outReshaped;
    }
    var conv2DConfig = {
      kernelName: tf.Conv2D,
      backendName: "webgl",
      kernelFunc: conv2d
    };
    var Conv2DDerFilterProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function Conv2DDerFilterProgram2(convInfo) {
          this.variableNames = ["x", "dy"];
          this.outputShape = convInfo.filterShape;
          var strideHeight = convInfo.strideHeight;
          var strideWidth = convInfo.strideWidth;
          var padTop = convInfo.padInfo.top;
          var padLeft = convInfo.padInfo.left;
          var isChannelsLast = convInfo.dataFormat === "channelsLast";
          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 < ".concat(convInfo.batchSize, "; b++) {\n          for (int yR = 0; yR < ").concat(convInfo.outHeight, "; yR++) {\n            int xR = wR + yR * ").concat(strideHeight, " - ").concat(padTop, ";\n\n            if (xR < 0 || xR >= ").concat(convInfo.inHeight, ") {\n              continue;\n            }\n\n            for (int yC = 0; yC < ").concat(convInfo.outWidth, "; yC++) {\n              int xC = wC + yC * ").concat(strideWidth, " - ").concat(padLeft, ";\n\n              if (xC < 0 || xC >= ").concat(convInfo.inWidth, ") {\n                continue;\n              }\n\n              ").concat(isChannelsLast ? "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    ");
        }
        return Conv2DDerFilterProgram2;
      }()
    );
    var Conv2DDerInputProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function Conv2DDerInputProgram2(convInfo) {
          this.variableNames = ["dy", "W"];
          this.outputShape = convInfo.inShape;
          var filterHeight = convInfo.filterHeight;
          var filterWidth = convInfo.filterWidth;
          var strideHeight = convInfo.strideHeight;
          var strideWidth = convInfo.strideWidth;
          var isChannelsLast = convInfo.dataFormat === "channelsLast";
          var padTop = filterHeight - 1 - convInfo.padInfo.top;
          var padLeft = filterWidth - 1 - convInfo.padInfo.left;
          var rowDim = isChannelsLast ? 1 : 2;
          var colDim = isChannelsLast ? 2 : 3;
          var channelDim = isChannelsLast ? 3 : 1;
          this.userCode = "\n      const ivec2 pads = ivec2(".concat(padTop, ", ").concat(padLeft, ");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords[").concat(channelDim, "];\n\n        ivec2 dyCorner = ivec2(coords[").concat(rowDim, "], coords[").concat(colDim, "]) - 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 < ").concat(filterHeight, "; wR++) {\n          float dyR = float(dyRCorner + wR) / ").concat(strideHeight, ".0;\n\n          if (dyR < 0.0 || dyR >= ").concat(convInfo.outHeight, ".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          int wRPerm = ").concat(filterHeight, " - 1 - wR;\n\n          for (int wC = 0; wC < ").concat(filterWidth, "; wC++) {\n            float dyC = float(dyCCorner + wC) / ").concat(strideWidth, ".0;\n\n            if (dyC < 0.0 || dyC >= ").concat(convInfo.outWidth, ".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            int wCPerm = ").concat(filterWidth, " - 1 - wC;\n\n            for (int d2 = 0; d2 < ").concat(convInfo.outChannels, "; d2++) {\n\n              if (").concat(isChannelsLast, ") {\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    ");
        }
        return Conv2DDerInputProgram2;
      }()
    );
    var Conv3DDerFilterProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function Conv3DDerFilterProgram2(convInfo) {
          this.variableNames = ["x", "dy"];
          this.outputShape = convInfo.filterShape;
          var strideDepth = convInfo.strideDepth;
          var strideHeight = convInfo.strideHeight;
          var strideWidth = convInfo.strideWidth;
          var padFront = convInfo.padInfo.front;
          var padTop = convInfo.padInfo.top;
          var padLeft = convInfo.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 < ".concat(convInfo.batchSize, "; b++) {\n          for (int yF = 0; yF < ").concat(convInfo.outDepth, "; yF++) {\n            int xF = wF + yF * ").concat(strideDepth, " - ").concat(padFront, ";\n\n            if (xF < 0 || xF >= ").concat(convInfo.inDepth, ") {\n              continue;\n            }\n\n            for (int yR = 0; yR < ").concat(convInfo.outHeight, "; yR++) {\n              int xR = wR + yR * ").concat(strideHeight, " - ").concat(padTop, ";\n\n              if (xR < 0 || xR >= ").concat(convInfo.inHeight, ") {\n                continue;\n              }\n\n              for (int yC = 0; yC < ").concat(convInfo.outWidth, "; yC++) {\n                int xC = wC + yC * ").concat(strideWidth, " - ").concat(padLeft, ";\n\n                if (xC < 0 || xC >= ").concat(convInfo.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    ");
        }
        return Conv3DDerFilterProgram2;
      }()
    );
    var Conv3DDerInputProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function Conv3DDerInputProgram2(convInfo) {
          this.variableNames = ["dy", "W"];
          this.outputShape = convInfo.inShape;
          var filterDepth = convInfo.filterDepth;
          var filterHeight = convInfo.filterHeight;
          var filterWidth = convInfo.filterWidth;
          var strideDepth = convInfo.strideDepth;
          var strideHeight = convInfo.strideHeight;
          var strideWidth = convInfo.strideWidth;
          var padFront = filterDepth - 1 - convInfo.padInfo.front;
          var padTop = filterHeight - 1 - convInfo.padInfo.top;
          var padLeft = filterWidth - 1 - convInfo.padInfo.left;
          this.userCode = "\n      const ivec3 pads = ivec3(".concat(padFront, ", ").concat(padTop, ", ").concat(padLeft, ");\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 < ").concat(filterDepth, "; wF++) {\n          float dyF = float(dyFCorner + wF) / ").concat(strideDepth, ".0;\n\n          if (dyF < 0.0 || dyF >= ").concat(convInfo.outDepth, ".0 || fract(dyF) > 0.0) {\n            continue;\n          }\n          int idyF = int(dyF);\n\n          int wFPerm = ").concat(filterDepth, " - 1 - wF;\n\n          for (int wR = 0; wR < ").concat(filterHeight, "; wR++) {\n            float dyR = float(dyRCorner + wR) / ").concat(strideHeight, ".0;\n\n            if (dyR < 0.0 || dyR >= ").concat(convInfo.outHeight, ".0 ||\n              fract(dyR) > 0.0) {\n              continue;\n            }\n            int idyR = int(dyR);\n\n            int wRPerm = ").concat(filterHeight, " - 1 - wR;\n\n            for (int wC = 0; wC < ").concat(filterWidth, "; wC++) {\n              float dyC = float(dyCCorner + wC) / ").concat(strideWidth, ".0;\n\n              if (dyC < 0.0 || dyC >= ").concat(convInfo.outWidth, ".0 ||\n                  fract(dyC) > 0.0) {\n                continue;\n              }\n              int idyC = int(dyC);\n\n              int wCPerm = ").concat(filterWidth, " - 1 - wC;\n\n              for (int d2 = 0; d2 < ").concat(convInfo.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    ");
        }
        return Conv3DDerInputProgram2;
      }()
    );
    function conv2DBackpropFilter(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, dy = inputs.dy;
      var strides = attrs.strides, pad = attrs.pad, dataFormat = attrs.dataFormat, dimRoundingMode = attrs.dimRoundingMode, filterShape = attrs.filterShape;
      var $dataFormat = tf.backend_util.convertConv2DDataFormat(dataFormat);
      var convInfo = tf.backend_util.computeConv2DInfo(x.shape, filterShape, strides, 1, pad, dimRoundingMode, false, $dataFormat);
      var program = new Conv2DDerFilterProgram(convInfo);
      return backend.runWebGLProgram(program, [x, dy], "float32");
    }
    var conv2DBackpropFilterConfig = {
      kernelName: tf.Conv2DBackpropFilter,
      backendName: "webgl",
      kernelFunc: conv2DBackpropFilter
    };
    var Conv2DDerInputPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function Conv2DDerInputPackedProgram2(convInfo) {
          this.variableNames = ["dy", "W"];
          this.packedInputs = true;
          this.packedOutput = true;
          this.customUniforms = [
            { name: "strides", type: "vec2" }
          ];
          this.outputShape = convInfo.inShape;
          this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);
          var filterHeight = convInfo.filterHeight;
          var filterWidth = convInfo.filterWidth;
          var padTop = filterHeight - 1 - convInfo.padInfo.top;
          var padLeft = filterWidth - 1 - convInfo.padInfo.left;
          this.userCode = "\n      const ivec2 pads = ivec2(".concat(padTop, ", ").concat(padLeft, ");\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 < ").concat(filterHeight, "; wR++) {\n          float dyR = float(dyRCorner + wR) / strides[0];\n          if (dyR < 0.0 || dyR >= ").concat(convInfo.outHeight, ".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n          int wRPerm = ").concat(filterHeight, " - 1 - wR;\n\n          for (int wC = 0; wC < ").concat(filterWidth, "; wC++) {\n            int wCPerm = ").concat(filterWidth, " - 1 - wC;\n\n            float dyC = float(dyCCorner + wC) / strides[1];\n            bool idyCVal = (dyC >= 0.0) && (dyC < ").concat(convInfo.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 < ").concat(convInfo.outWidth, ".0)\n              && (fract(dyC2) == 0.0);\n            int idyC2 = int(dyC2);\n\n            if (idyCVal && idyCVal2) {\n              for (int d2 = 0; d2 < ").concat(convInfo.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 < ").concat(convInfo.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 < ").concat(convInfo.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    ");
        }
        return Conv2DDerInputPackedProgram2;
      }()
    );
    function conv2DBackpropInput(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var dy = inputs.dy, filter = inputs.filter;
      var inputShape = attrs.inputShape, strides = attrs.strides, pad = attrs.pad, dataFormat = attrs.dataFormat, dimRoundingMode = attrs.dimRoundingMode;
      var $dataFormat = tf.backend_util.convertConv2DDataFormat(dataFormat);
      var convInfo = tf.backend_util.computeConv2DInfo(inputShape, filter.shape, strides, 1, pad, dimRoundingMode, false, $dataFormat);
      if (tf.env().getBool("WEBGL_PACK_CONV2DTRANSPOSE") && $dataFormat === "channelsLast") {
        var customValues = [
          [convInfo.strideHeight, convInfo.strideWidth]
        ];
        var program = new Conv2DDerInputPackedProgram(convInfo);
        return backend.runWebGLProgram(program, [dy, filter], "float32", customValues);
      } else {
        var program = new Conv2DDerInputProgram(convInfo);
        return backend.runWebGLProgram(program, [dy, filter], "float32");
      }
    }
    var conv2DBackpropInputConfig = {
      kernelName: tf.Conv2DBackpropInput,
      backendName: "webgl",
      kernelFunc: conv2DBackpropInput
    };
    function conv3D(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, filter = inputs.filter;
      var strides = attrs.strides, pad = attrs.pad, dilations = attrs.dilations;
      var convInfo = tf.backend_util.computeConv3DInfo(x.shape, filter.shape, strides, dilations, pad);
      var program = new Conv3DProgram(convInfo);
      return backend.runWebGLProgram(program, [x, filter], "float32");
    }
    var conv3DConfig = {
      kernelName: tf.Conv3D,
      backendName: "webgl",
      kernelFunc: conv3D
    };
    function conv3DBackpropFilterV2(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, dy = inputs.dy;
      var strides = attrs.strides, pad = attrs.pad, filterShape = attrs.filterShape;
      var convInfo = tf.backend_util.computeConv3DInfo(x.shape, filterShape, strides, 1, pad);
      var program = new Conv3DDerFilterProgram(convInfo);
      return backend.runWebGLProgram(program, [x, dy], "float32");
    }
    var conv3DBackpropFilterV2Config = {
      kernelName: tf.Conv3DBackpropFilterV2,
      backendName: "webgl",
      kernelFunc: conv3DBackpropFilterV2
    };
    function conv3DBackpropInput(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var dy = inputs.dy, filter = inputs.filter;
      var pad = attrs.pad, strides = attrs.strides, inputShape = attrs.inputShape;
      var convInfo = tf.backend_util.computeConv3DInfo(inputShape, filter.shape, strides, 1, pad);
      var program = new Conv3DDerInputProgram(convInfo);
      return backend.runWebGLProgram(program, [dy, filter], "float32");
    }
    var conv3DBackpropInputConfig = {
      kernelName: tf.Conv3DBackpropInputV2,
      backendName: "webgl",
      kernelFunc: conv3DBackpropInput
    };
    var COS = CHECK_NAN_SNIPPET_UNARY + "\n  return cos(x);\n";
    var COS_PACKED = "\n  vec4 result = cos(x);\n  bvec4 isNaN = isnan(x);\n  ".concat(CHECK_NAN_SNIPPET_PACKED, "\n  return result;\n");
    var cos = unaryKernelFunc({ opSnippet: COS, packedOpSnippet: COS_PACKED });
    var cosConfig = {
      kernelName: tf.Cos,
      backendName: "webgl",
      kernelFunc: cos
    };
    var COSH = "\n  float e2x = exp(-x);\n  return (e2x + 1.0 / e2x) / 2.0;\n";
    var cosh = unaryKernelFunc({ opSnippet: COSH });
    var coshConfig = {
      kernelName: tf.Cosh,
      backendName: "webgl",
      kernelFunc: cosh
    };
    var CropAndResizeProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function CropAndResizeProgram2(imageShape, boxShape, cropSize, method, extrapolationValue) {
          this.variableNames = ["Image", "Boxes", "BoxInd"];
          this.outputShape = [];
          var _a2 = __read(imageShape, 4), batch = _a2[0], imageHeight = _a2[1], imageWidth = _a2[2], depth = _a2[3];
          var _b = __read(boxShape, 1), numBoxes = _b[0];
          var _c = __read(cropSize, 2), cropHeight = _c[0], cropWidth = _c[1];
          this.outputShape = [numBoxes, cropHeight, cropWidth, depth];
          var methodId = method === "bilinear" ? 1 : 0;
          var _d = __read(["".concat(imageHeight - 1, ".0"), "".concat(imageWidth - 1, ".0")], 2), inputHeightFloat = _d[0], inputWidthFloat = _d[1];
          var _e = __read(cropHeight > 1 ? [
            "".concat((imageHeight - 1) / (cropHeight - 1)),
            "(y2-y1) * height_ratio",
            "y1*".concat(inputHeightFloat, " + float(y)*(height_scale)")
          ] : [
            "0.0",
            "0.0",
            "0.5 * (y1+y2) * ".concat(inputHeightFloat)
          ], 3), heightRatio = _e[0], heightScale = _e[1], inY = _e[2];
          var _f = __read(cropWidth > 1 ? [
            "".concat((imageWidth - 1) / (cropWidth - 1)),
            "(x2-x1) * width_ratio",
            "x1*".concat(inputWidthFloat, " + float(x)*(width_scale)")
          ] : [
            "0.0",
            "0.0",
            "0.5 * (x1+x2) * ".concat(inputWidthFloat)
          ], 3), widthRatio = _f[0], widthScale = _f[1], inX = _f[2];
          this.userCode = "\n      const float height_ratio = float(".concat(heightRatio, ");\n      const float width_ratio = float(").concat(widthRatio, ");\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 >= ").concat(batch, ") {\n          return;\n        }\n\n        float height_scale = ").concat(heightScale, ";\n        float width_scale = ").concat(widthScale, ";\n\n        float in_y = ").concat(inY, ";\n        if( in_y < 0.0 || in_y > ").concat(inputHeightFloat, " ) {\n          setOutput(float(").concat(extrapolationValue, "));\n          return;\n        }\n        float in_x = ").concat(inX, ";\n        if( in_x < 0.0 || in_x > ").concat(inputWidthFloat, " ) {\n          setOutput(float(").concat(extrapolationValue, "));\n          return;\n        }\n\n        vec2 sourceFracIndexCR = vec2(in_x,in_y);\n        if(").concat(methodId, " == 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    ");
        }
        return CropAndResizeProgram2;
      }()
    );
    var cropAndResize = function(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var image = inputs.image, boxes = inputs.boxes, boxInd = inputs.boxInd;
      var cropSize = attrs.cropSize, method = attrs.method, extrapolationValue = attrs.extrapolationValue;
      var program = new CropAndResizeProgram(image.shape, boxes.shape, cropSize, method, extrapolationValue);
      return backend.runWebGLProgram(program, [image, boxes, boxInd], "float32");
    };
    var cropAndResizeConfig = {
      kernelName: tf.CropAndResize,
      backendName: "webgl",
      kernelFunc: cropAndResize
    };
    var CumOpType;
    (function(CumOpType2) {
      CumOpType2["Prod"] = "*";
      CumOpType2["Sum"] = "+";
    })(CumOpType || (CumOpType = {}));
    var CumProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function CumProgram2(op, outputShape, exclusive, reverse2) {
          this.op = op;
          this.outputShape = outputShape;
          this.variableNames = ["x"];
          this.customUniforms = [{ name: "index", type: "float" }];
          var rank = this.outputShape.length;
          var initVal = this.op === CumOpType.Prod ? "1.0" : "0.0";
          var val = exclusive ? initVal : "getX(".concat(getCoords(rank, "coords", this.op), ")");
          var length = this.outputShape[this.outputShape.length - 1];
          var condition = "";
          var idxString = "";
          if (exclusive) {
            condition = reverse2 ? "end != ".concat(length - 1) : "end != 0";
            idxString = reverse2 ? "end + 1" : "end - 1";
          } else {
            condition = reverse2 ? "end + pow2 < ".concat(length) : "end >= pow2";
            idxString = reverse2 ? "end + pow2" : "end - pow2";
          }
          this.userCode = "\n      void main() {\n        ".concat(getCoordsDataType(rank), " coords = getOutputCoords();\n        int end = ").concat(getFinalCoord(rank, "coords", this.op), ";\n        float val = ").concat(val, ";\n        int pow2 = int(pow(2.0, index));\n        if (").concat(condition, ") {\n          int idx = ").concat(idxString, ";\n          ").concat(getFinalCoord(rank, "coords", this.op), " = idx;\n          val ").concat(this.op, "= getX(").concat(getCoords(rank, "coords", this.op), ");\n        }\n        setOutput(val);\n      }\n    ");
        }
        return CumProgram2;
      }()
    );
    function getCoords(rank, name, op) {
      if (rank === 1) {
        return "".concat(name);
      } else if (rank === 2) {
        return "".concat(name, ".x, ").concat(name, ".y");
      } else if (rank === 3) {
        return "".concat(name, ".x, ").concat(name, ".y, ").concat(name, ".z");
      } else if (rank === 4) {
        return "".concat(name, ".x, ").concat(name, ".y, ").concat(name, ".z, ").concat(name, ".w");
      } else {
        throw new Error("Cumulative ".concat(op, " for rank ").concat(rank, " is not yet supported"));
      }
    }
    function getFinalCoord(rank, name, op) {
      if (rank === 1) {
        return "".concat(name);
      } else if (rank === 2) {
        return "".concat(name, ".y");
      } else if (rank === 3) {
        return "".concat(name, ".z");
      } else if (rank === 4) {
        return "".concat(name, ".w");
      } else {
        throw new Error("Cumulative ".concat(op, " for rank ").concat(rank, " is not yet supported"));
      }
    }
    function cumImpl(op, x, backend, axis, exclusive, reverse2) {
      var xRank = x.shape.length;
      var permutation = tf.backend_util.getAxesPermutation([axis], xRank);
      var permutedX = x;
      if (permutation != null) {
        permutedX = transpose({ inputs: { x }, backend, attrs: { perm: permutation } });
      }
      var permutedAxis = tf.backend_util.getInnerMostAxes(1, xRank)[0];
      if (permutedAxis !== xRank - 1) {
        throw new Error("WebGL cumprod shader expects an inner-most axis=".concat(x.shape.length - 1, " ") + "but got axis=".concat(axis));
      }
      var size = permutedX.shape[permutedAxis];
      var result = identity({ inputs: { x: permutedX }, backend });
      for (var i = 0; i <= Math.ceil(Math.log2(size)) - 1; i++) {
        var program = new CumProgram(op, permutedX.shape, false, reverse2);
        var customValues = [[i]];
        var prevResult = result;
        result = backend.runWebGLProgram(program, [result], result.dtype, customValues);
        backend.disposeIntermediateTensorInfo(prevResult);
      }
      if (exclusive) {
        var program = new CumProgram(op, permutedX.shape, exclusive, reverse2);
        var prevResult = result;
        result = backend.runWebGLProgram(program, [result], result.dtype);
        backend.disposeIntermediateTensorInfo(prevResult);
      }
      if (permutation != null) {
        var reversePermutation = tf.backend_util.getUndoAxesPermutation(permutation);
        var reverseTransposedResult = transpose({ inputs: { x: result }, backend, attrs: { perm: reversePermutation } });
        backend.disposeIntermediateTensorInfo(result);
        backend.disposeIntermediateTensorInfo(permutedX);
        return reverseTransposedResult;
      }
      return result;
    }
    function cumprod(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis, exclusive = attrs.exclusive, reverse2 = attrs.reverse;
      return cumImpl(CumOpType.Prod, x, backend, axis, exclusive, reverse2);
    }
    var cumprodConfig = {
      kernelName: tf.Cumprod,
      backendName: "webgl",
      kernelFunc: cumprod
    };
    function cumsum(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis, exclusive = attrs.exclusive, reverse2 = attrs.reverse;
      return cumImpl(CumOpType.Sum, x, backend, axis, exclusive, reverse2);
    }
    var cumsumConfig = {
      kernelName: tf.Cumsum,
      backendName: "webgl",
      kernelFunc: cumsum
    };
    function denseBincount(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, weights = inputs.weights;
      var size = attrs.size, binaryOutput = attrs.binaryOutput;
      if (x.shape.length === 1) {
        var xVals = backend.readSync(x.dataId);
        var weightsVals = backend.readSync(weights.dataId);
        var outVals = bincountImplCPU(xVals, weightsVals, weights.dtype, weights.shape, size);
        return backend.makeTensorInfo([size], weights.dtype, outVals);
      } else if (x.shape.length === 2) {
        var xBuf = backend.bufferSync(x);
        var weightsBuf = backend.bufferSync(weights);
        var outBuf = bincountReduceImplCPU(xBuf, weightsBuf, size, binaryOutput);
        return backend.makeTensorInfo(outBuf.shape, weights.dtype, outBuf.values);
      }
      throw new Error("Error in denseBincount: input must be at most rank 2, but got rank" + "".concat(x.shape.length, "."));
    }
    var denseBincountConfig = {
      kernelName: tf.DenseBincount,
      backendName: "webgl",
      kernelFunc: denseBincount
    };
    var DepthToSpaceProgram = (
      /** @class */
      function() {
        function DepthToSpaceProgram2(outputShape, blockSize, dataFormat) {
          this.variableNames = ["x"];
          this.outputShape = [];
          this.outputShape = outputShape;
          this.blockSize = blockSize;
          this.dataFormat = dataFormat;
          this.userCode = "\n    void main() {\n      ivec4 coords = getOutputCoords();\n      int b = coords[0];\n      int h = ".concat(this.getHeightCoordString(), ";\n      int w = ").concat(this.getWidthCoordString(), ";\n      int d = ").concat(this.getDepthCoordString(), ";\n\n      int in_h = h / ").concat(blockSize, ";\n      int offset_h = imod(h, ").concat(blockSize, ");\n      int in_w = w / ").concat(blockSize, ";\n      int offset_w = imod(w, ").concat(blockSize, ");\n      int offset_d = (offset_h * ").concat(blockSize, " + offset_w) *\n        ").concat(this.getOutputDepthSize(), ";\n      int in_d = d + offset_d;\n\n      float result = ").concat(this.getInputSamplingString(), ";\n      setOutput(result);\n    }\n  ");
        }
        DepthToSpaceProgram2.prototype.getHeightCoordString = function() {
          if (this.dataFormat === "NHWC") {
            return "coords[1]";
          } else {
            return "coords[2]";
          }
        };
        DepthToSpaceProgram2.prototype.getWidthCoordString = function() {
          if (this.dataFormat === "NHWC") {
            return "coords[2]";
          } else {
            return "coords[3]";
          }
        };
        DepthToSpaceProgram2.prototype.getDepthCoordString = function() {
          if (this.dataFormat === "NHWC") {
            return "coords[3]";
          } else {
            return "coords[1]";
          }
        };
        DepthToSpaceProgram2.prototype.getOutputDepthSize = function() {
          if (this.dataFormat === "NHWC") {
            return this.outputShape[3];
          } else {
            return this.outputShape[1];
          }
        };
        DepthToSpaceProgram2.prototype.getInputSamplingString = function() {
          if (this.dataFormat === "NHWC") {
            return "getX(b, in_h, in_w, in_d)";
          } else {
            return "getX(b, in_d, in_h, in_w)";
          }
        };
        return DepthToSpaceProgram2;
      }()
    );
    function depthToSpace(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var blockSize = attrs.blockSize, dataFormat = attrs.dataFormat;
      var batchSize = x.shape[0];
      var inputHeight = dataFormat === "NHWC" ? x.shape[1] : x.shape[2];
      var inputWidth = dataFormat === "NHWC" ? x.shape[2] : x.shape[3];
      var inputDepth = dataFormat === "NHWC" ? x.shape[3] : x.shape[1];
      var outputHeight = inputHeight * blockSize;
      var outputWidth = inputWidth * blockSize;
      var outputDepth = inputDepth / (blockSize * blockSize);
      var outputShape = dataFormat === "NHWC" ? [batchSize, outputHeight, outputWidth, outputDepth] : [batchSize, outputDepth, outputHeight, outputWidth];
      var program = new DepthToSpaceProgram(outputShape, blockSize, dataFormat);
      return backend.runWebGLProgram(program, [x], x.dtype);
    }
    var depthToSpaceConfig = {
      kernelName: tf.DepthToSpace,
      backendName: "webgl",
      kernelFunc: depthToSpace
    };
    var DepthwiseConv2DProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function DepthwiseConv2DProgram2(convInfo, addBias, activation, hasPreluActivation, hasLeakyReluAlpha) {
          if (addBias === void 0) {
            addBias = false;
          }
          if (activation === void 0) {
            activation = null;
          }
          if (hasPreluActivation === void 0) {
            hasPreluActivation = false;
          }
          if (hasLeakyReluAlpha === void 0) {
            hasLeakyReluAlpha = false;
          }
          this.variableNames = ["x", "W"];
          this.customUniforms = [
            { name: "pads", type: "ivec2" },
            { name: "strides", type: "ivec2" },
            { name: "dilations", type: "ivec2" },
            { name: "inDims", type: "ivec2" }
          ];
          this.outputShape = convInfo.outShape;
          this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);
          var filterHeight = convInfo.filterHeight;
          var filterWidth = convInfo.filterWidth;
          var channelMul = convInfo.outChannels / convInfo.inChannels;
          var activationSnippet = "", applyActivationSnippet = "";
          if (activation) {
            if (hasPreluActivation) {
              activationSnippet = "float activation(float a) {\n          float b = getPreluActivationWeightsAtOutCoords();\n          ".concat(activation, "\n        }");
            } else if (hasLeakyReluAlpha) {
              activationSnippet = "float activation(float a) {\n          float b = getLeakyreluAlphaAtOutCoords();\n          ".concat(activation, "\n        }");
            } else {
              activationSnippet = "\n          float activation(float x) {\n            ".concat(activation, "\n          }\n        ");
            }
            applyActivationSnippet = "result = activation(result);";
          }
          var addBiasSnippet = addBias ? "result += getBiasAtOutCoords();" : "";
          if (addBias) {
            this.variableNames.push("bias");
          }
          if (hasPreluActivation) {
            this.variableNames.push("preluActivationWeights");
          }
          if (hasLeakyReluAlpha) {
            this.variableNames.push("leakyreluAlpha");
          }
          this.userCode = "\n      ".concat(activationSnippet, "\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 / ").concat(channelMul, ";\n        int q = d2 - d1 * ").concat(channelMul, ";\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 < ").concat(filterHeight, "; 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 < ").concat(filterWidth, "; 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        ").concat(addBiasSnippet, "\n        ").concat(applyActivationSnippet, "\n        setOutput(result);\n      }\n    ");
        }
        return DepthwiseConv2DProgram2;
      }()
    );
    var DepthwiseConvPacked2DProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function DepthwiseConvPacked2DProgram2(convInfo, addBias, activation, hasPreluActivation, hasLeakyReluAlpha) {
          if (addBias === void 0) {
            addBias = false;
          }
          if (activation === void 0) {
            activation = null;
          }
          if (hasPreluActivation === void 0) {
            hasPreluActivation = false;
          }
          if (hasLeakyReluAlpha === void 0) {
            hasLeakyReluAlpha = false;
          }
          this.variableNames = ["x", "W"];
          this.packedInputs = true;
          this.packedOutput = true;
          this.customUniforms = [
            { name: "pads", type: "ivec2" },
            { name: "strides", type: "ivec2" },
            { name: "dilations", type: "ivec2" },
            { name: "inDims", type: "ivec2" }
          ];
          this.outputShape = convInfo.outShape;
          this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);
          var channelMul = convInfo.outChannels / convInfo.inChannels;
          var padLeft = convInfo.padInfo.left;
          var strideWidth = convInfo.strideWidth;
          var dilationWidth = convInfo.dilationWidth;
          var filterHeight = convInfo.filterHeight;
          var filterWidth = convInfo.filterWidth;
          var texelsAcross = filterWidth;
          var mainLoop = "\n      int xR; int xC; int xCOffset;\n      vec4 wTexel; vec4 previous; vec4 final;";
          for (var c = 0; c < filterWidth; c++) {
            mainLoop += "\n          vec4 xTexelC".concat(c * 2, ";\n          int xTexelC").concat(c * 2, "Ready;\n          vec4 xTexelC").concat(c * 2 + 1, ";\n          int xTexelC").concat(c * 2 + 1, "Ready;\n          vec4 xC").concat(c, ";");
          }
          mainLoop += "\n    for (int r = 0; r < ".concat(filterHeight, "; r++) {\n      ");
          for (var c = 0; c < filterWidth; c++) {
            mainLoop += "\n          xTexelC".concat(c * 2, " = vec4(0.0);\n          xTexelC").concat(c * 2, "Ready = 0;\n          xTexelC").concat(c * 2 + 1, " = vec4(0.0);\n          xTexelC").concat(c * 2 + 1, "Ready = 0;\n          xC").concat(c, " = vec4(0.0);");
          }
          mainLoop += "\n        xR = xRCorner + r * dilations[0];\n        if (xR >=0 && xR < inDims[0]) {\n      ";
          for (var texelC = 0; texelC < (texelsAcross + 1) / 2; texelC++) {
            var colIndex = texelC * 2;
            mainLoop += "\n          xC = xCCorner + ".concat(colIndex * dilationWidth, ";\n          ");
            if (strideWidth === 1) {
              if (colIndex < filterWidth) {
                if (padLeft % 2 === 1) {
                  mainLoop += "\n                xCOffset = xC + 1;\n                if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC".concat(colIndex, "Ready == 0) {\n                  xTexelC").concat(colIndex, " = 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").concat(colIndex, ".zw = vec2(0.0);\n                  }\n                  xTexelC").concat(colIndex, "Ready = 1;\n                }\n              ");
                  if (dilationWidth === 1 && colIndex > 0) {
                    mainLoop += "\n                xC".concat(colIndex, " = vec4(xTexelC").concat(colIndex - 2, ".zw, xTexelC").concat(colIndex, ".xy);\n                ");
                  } else {
                    mainLoop += "\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".concat(colIndex, " = vec4(previous.zw, xTexelC").concat(colIndex, ".xy);\n                  } else {\n                    xC").concat(colIndex, " = vec4(0.0, 0.0, xTexelC").concat(colIndex, ".xy);\n                  }\n                  ");
                  }
                } else {
                  mainLoop += "\n                if (xC >= 0 && xC < inDims[1] && xTexelC".concat(colIndex, "Ready == 0) {\n                  xTexelC").concat(colIndex, " = getX(batch, xR, xC, d1);\n                  if (xC + 1 >= inDims[1]) {\n                    xTexelC").concat(colIndex, ".zw = vec2(0.0);\n                  }\n                  xTexelC").concat(colIndex, "Ready = 1;\n                }\n\n                xC").concat(colIndex, " = xTexelC").concat(colIndex, ";\n                ");
                }
                if (colIndex + 1 < filterWidth) {
                  var nextTexelOffset = padLeft % 2 === 0 ? tf.util.nearestLargerEven(dilationWidth) : dilationWidth;
                  if (dilationWidth % 2 === 0 && padLeft % 2 === 1 || dilationWidth % 2 !== 0 && padLeft % 2 !== 1) {
                    mainLoop += "\n                  xCOffset = xC + imod(pads[1], 2) + ".concat(nextTexelOffset, ";\n\n                  if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC").concat(colIndex + 1, "Ready == 0) {\n                    xTexelC").concat(colIndex + 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").concat(colIndex + 1, ".zw = vec2(0.0);\n                    }\n                    xTexelC").concat(colIndex + 1, "Ready = 1;\n                  }\n                  ");
                    if (dilationWidth > 1) {
                      mainLoop += "\n                    xCOffset -= 2;\n                    if (xCOffset >= 0 && xCOffset < inDims[1]) {\n                     previous = getX(batch, xR, xCOffset, d1);\n                     xC".concat(colIndex + 1, " = vec4(previous.zw, xTexelC").concat(colIndex + 1, ".xy);\n                    } else {\n                     xC").concat(colIndex + 1, " = vec4(0.0, 0.0, xTexelC").concat(colIndex + 1, ".xy);\n                    }\n                    ");
                    } else {
                      mainLoop += "\n                    xC".concat(colIndex + 1, " = vec4(xTexelC").concat(colIndex, ".zw, xTexelC").concat(colIndex + 1, ".xy);\n                    ");
                    }
                  } else {
                    if (nextTexelOffset === 1) {
                      mainLoop += "\n                    xC".concat(colIndex + 1, " = xTexelC").concat(colIndex, ";\n                    ");
                    } else {
                      mainLoop += "\n                    xCOffset = xC + ".concat(nextTexelOffset, ";\n\n                    if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC").concat(colIndex + 1, "Ready == 0) {\n                      xTexelC").concat(colIndex + 1, " = getX(batch, xR, xCOffset, d1);\n                      if (xCOffset + 1 >= inDims[1]) {\n                        xTexelC").concat(colIndex + 1, ".zw = vec2(0.0);\n                      }\n                      xTexelC").concat(colIndex + 1, "Ready = 1;\n                    }\n\n                    xC").concat(colIndex + 1, " = xTexelC").concat(colIndex + 1, ";\n                    ");
                    }
                  }
                }
              }
            } else {
              if (colIndex < filterWidth) {
                if (padLeft % 2 === 1) {
                  mainLoop += "\n                xCOffset = xC + 1 - strides[1];\n                if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC".concat(colIndex, "Ready == 0) {\n                  xTexelC").concat(colIndex, " = 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").concat(colIndex, ".zw = vec2(0.0);\n                  }\n                  xTexelC").concat(colIndex, "Ready = 1;\n                }\n\n                if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC").concat(colIndex + 1, "Ready == 0) {\n                  xTexelC").concat(colIndex + 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").concat(colIndex + 1, ".zw = vec2(0.0);\n                  }\n                  xTexelC").concat(colIndex + 1, "Ready = 1;\n                }\n\n                xC").concat(colIndex, " = vec4(xTexelC").concat(colIndex, ".zw, xTexelC").concat(colIndex + 1, ".zw);\n              ");
                  if (colIndex + 1 < filterWidth) {
                    mainLoop += "\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".concat(colIndex + 1, " = vec4(xTexelC").concat(colIndex + 1, ".xy, final.xy);\n                ");
                  }
                } else {
                  mainLoop += "\n                if(xC >= 0 && xC < inDims[1] && xTexelC".concat(colIndex, "Ready == 0) {\n                  xTexelC").concat(colIndex, " = getX(batch, xR, xC, d1);\n                  if (xC + 1 >= inDims[1]) {\n                    xTexelC").concat(colIndex, ".zw = vec2(0.0);\n                  }\n                  xTexelC").concat(colIndex, "Ready = 1;\n                }\n\n                xCOffset = xC + strides[1];\n                if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC").concat(colIndex + 1, "Ready == 0) {\n                  xTexelC").concat(colIndex + 1, " = getX(batch, xR, xCOffset, d1);\n                  if (xCOffset + 1 >= inDims[1]) {\n                    xTexelC").concat(colIndex + 1, ".zw = vec2(0.);\n                  }\n                  xTexelC").concat(colIndex + 1, "Ready = 1;\n                }\n\n                xC").concat(colIndex, " = vec4(\n                  xTexelC").concat(colIndex, ".xy, xTexelC").concat(colIndex + 1, ".xy);\n              ");
                  if (colIndex + 1 < filterWidth) {
                    mainLoop += "\n                  xC".concat(colIndex + 1, " = vec4(xTexelC").concat(colIndex, ".zw, xTexelC").concat(colIndex + 1, ".zw);\n                ");
                  }
                }
              }
            }
            if (colIndex < filterWidth) {
              mainLoop += "\n            wTexel = getW(r, ".concat(colIndex, ", d1, q);\n            dotProd += xC").concat(colIndex, " * vec4(wTexel.xz, wTexel.xz);\n          ");
              if (colIndex + 1 < filterWidth) {
                mainLoop += "\n              wTexel = getW(r, ".concat(colIndex + 1, ", d1, q);\n              dotProd += xC").concat(colIndex + 1, " * vec4(wTexel.xz, wTexel.xz);\n            ");
              }
            }
          }
          mainLoop += "\n    }\n  ";
          mainLoop += "\n      }\n    ";
          var activationSnippet = "", applyActivationSnippet = "";
          if (activation) {
            if (hasPreluActivation) {
              activationSnippet = "vec4 activation(vec4 a) {\n          vec4 b = getPreluActivationWeightsAtOutCoords();\n          ".concat(activation, "\n        }");
            } else if (hasLeakyReluAlpha) {
              activationSnippet = "vec4 activation(vec4 a) {\n          vec4 b = getLeakyreluAlphaAtOutCoords();\n          ".concat(activation, "\n        }");
            } else {
              activationSnippet = "vec4 activation(vec4 x) {\n          ".concat(activation, "\n        }");
            }
            applyActivationSnippet = "result = activation(result);";
          }
          var addBiasSnippet = addBias ? "result += getBiasAtOutCoords();" : "";
          if (addBias) {
            this.variableNames.push("bias");
          }
          if (hasPreluActivation) {
            this.variableNames.push("preluActivationWeights");
          }
          if (hasLeakyReluAlpha) {
            this.variableNames.push("leakyreluAlpha");
          }
          this.userCode = "\n      ".concat(activationSnippet, "\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 / ").concat(channelMul, ";\n        int q = d2 - d1 * ").concat(channelMul, ";\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        ").concat(mainLoop, "\n\n        vec4 result = dotProd - vec4(0.000000000000001);\n        ").concat(addBiasSnippet, "\n        ").concat(applyActivationSnippet, "\n        setOutput(result);\n      }\n    ");
        }
        return DepthwiseConvPacked2DProgram2;
      }()
    );
    function depthwiseConv2dNative(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, filter = inputs.filter;
      var strides = attrs.strides, pad = attrs.pad, dilations = attrs.dilations, dimRoundingMode = attrs.dimRoundingMode;
      var $dilations = dilations;
      if ($dilations == null) {
        $dilations = [1, 1];
      }
      tf.util.assert(tf.backend_util.eitherStridesOrDilationsAreOne(strides, $dilations), function() {
        return "Error in depthwiseConv2d: Either strides or dilations must be " + "1. Got strides ".concat(strides, " and dilations '").concat($dilations, "'");
      });
      var convInfo = tf.backend_util.computeConv2DInfo(
        x.shape,
        filter.shape,
        strides,
        $dilations,
        pad,
        dimRoundingMode,
        true
        /* depthwise */
      );
      var program;
      if (tf.env().getBool("WEBGL_PACK_DEPTHWISECONV") && convInfo.strideWidth <= 2 && convInfo.outChannels / convInfo.inChannels === 1) {
        program = new DepthwiseConvPacked2DProgram(convInfo);
      } else {
        program = new DepthwiseConv2DProgram(convInfo);
      }
      var customValues = [
        [convInfo.padInfo.top, convInfo.padInfo.left],
        [convInfo.strideHeight, convInfo.strideWidth],
        [convInfo.dilationHeight, convInfo.dilationWidth],
        [convInfo.inHeight, convInfo.inWidth]
      ];
      return backend.runWebGLProgram(program, [x, filter], "float32", customValues);
    }
    var depthwiseConv2dNativeConfig = {
      kernelName: tf.DepthwiseConv2dNative,
      backendName: "webgl",
      kernelFunc: depthwiseConv2dNative
    };
    var DepthwiseConv2DDerFilterProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function DepthwiseConv2DDerFilterProgram2(convInfo) {
          this.variableNames = ["x", "dy"];
          this.outputShape = convInfo.filterShape;
          var strideHeight = convInfo.strideHeight;
          var strideWidth = convInfo.strideWidth;
          var padTop = convInfo.padInfo.top;
          var padLeft = convInfo.padInfo.left;
          var channelMul = convInfo.outChannels / convInfo.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 * ".concat(channelMul, " + dm;\n\n        float dotProd = 0.0;\n\n        // TO DO: Vec4 over the batch size\n        for (int b = 0; b < ").concat(convInfo.batchSize, "; b++) {\n          for (int yR = 0; yR < ").concat(convInfo.outHeight, "; yR++) {\n            int xR = wR + yR * ").concat(strideHeight, " - ").concat(padTop, ";\n\n            if (xR < 0 || xR >= ").concat(convInfo.inHeight, ") {\n              continue;\n            }\n\n            for (int yC = 0; yC < ").concat(convInfo.outWidth, "; yC++) {\n              int xC = wC + yC * ").concat(strideWidth, " - ").concat(padLeft, ";\n\n              if (xC < 0 || xC >= ").concat(convInfo.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    ");
        }
        return DepthwiseConv2DDerFilterProgram2;
      }()
    );
    var DepthwiseConv2DDerInputProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function DepthwiseConv2DDerInputProgram2(convInfo) {
          this.variableNames = ["dy", "W"];
          this.outputShape = convInfo.inShape;
          var filterHeight = convInfo.filterHeight;
          var filterWidth = convInfo.filterWidth;
          var strideHeight = convInfo.strideHeight;
          var strideWidth = convInfo.strideWidth;
          var padTop = filterHeight - 1 - convInfo.padInfo.top;
          var padLeft = filterWidth - 1 - convInfo.padInfo.left;
          var channelMul = convInfo.outChannels / convInfo.inChannels;
          this.userCode = "\n      const ivec2 pads = ivec2(".concat(padTop, ", ").concat(padLeft, ");\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 < ").concat(filterHeight, "; wR++) {\n          float dyR = float(dyRCorner + wR) / ").concat(strideHeight, ".0;\n\n          if (dyR < 0.0 || dyR >= ").concat(convInfo.outHeight, ".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          int wRPerm = ").concat(filterHeight, " - 1 - wR;\n\n          for (int wC = 0; wC < ").concat(filterWidth, "; wC++) {\n            float dyC = float(dyCCorner + wC) / ").concat(strideWidth, ".0;\n\n            if (dyC < 0.0 || dyC >= ").concat(convInfo.outWidth, ".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            int wCPerm = ").concat(filterWidth, " - 1 - wC;\n\n            // TO DO: Vec4 over the channelMul\n            for (int dm = 0; dm < ").concat(channelMul, "; dm++) {\n              int d2 = d1 * ").concat(channelMul, " + 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    ");
        }
        return DepthwiseConv2DDerInputProgram2;
      }()
    );
    function depthwiseConv2dNativeBackpropFilter(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, dy = inputs.dy;
      var strides = attrs.strides, dilations = attrs.dilations, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode, filterShape = attrs.filterShape;
      var convInfo = tf.backend_util.computeConv2DInfo(
        x.shape,
        filterShape,
        strides,
        dilations,
        pad,
        dimRoundingMode,
        true
        /* depthwise */
      );
      var program = new DepthwiseConv2DDerFilterProgram(convInfo);
      return backend.runWebGLProgram(program, [x, dy], "float32");
    }
    var depthwiseConv2dNativeBackpropFilterConfig = {
      kernelName: tf.DepthwiseConv2dNativeBackpropFilter,
      backendName: "webgl",
      kernelFunc: depthwiseConv2dNativeBackpropFilter
    };
    function depthwiseConv2dNativeBackpropInput(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var dy = inputs.dy, filter = inputs.filter;
      var strides = attrs.strides, dilations = attrs.dilations, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode, inputShape = attrs.inputShape;
      var convInfo = tf.backend_util.computeConv2DInfo(
        inputShape,
        filter.shape,
        strides,
        dilations,
        pad,
        dimRoundingMode,
        true
        /* depthwise */
      );
      var program = new DepthwiseConv2DDerInputProgram(convInfo);
      return backend.runWebGLProgram(program, [dy, filter], "float32");
    }
    var depthwiseConv2dNativeBackpropInputConfig = {
      kernelName: tf.DepthwiseConv2dNativeBackpropInput,
      backendName: "webgl",
      kernelFunc: depthwiseConv2dNativeBackpropInput
    };
    var DiagProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function DiagProgram2(size) {
          this.variableNames = ["X"];
          this.outputShape = [size, size];
          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    ";
        }
        return DiagProgram2;
      }()
    );
    function diag(args) {
      var inputs = args.inputs, backend = args.backend;
      var x = inputs.x;
      var outShape = __spreadArray(__spreadArray([], __read(x.shape), false), __read(x.shape), false);
      var xSize = tf.util.sizeFromShape(x.shape);
      var flat = reshape({ inputs: { x }, backend, attrs: { shape: [xSize] } });
      var program = new DiagProgram(xSize);
      var res = backend.runWebGLProgram(program, [flat], flat.dtype);
      var out = reshape({ inputs: { x: res }, backend, attrs: { shape: outShape } });
      backend.disposeIntermediateTensorInfo(flat);
      backend.disposeIntermediateTensorInfo(res);
      return out;
    }
    var diagConfig = {
      kernelName: tf.Diag,
      backendName: "webgl",
      kernelFunc: diag
    };
    var Dilation2DProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function Dilation2DProgram2(convInfo) {
          this.variableNames = ["x", "W"];
          this.outputShape = convInfo.outShape;
          var inHeight = convInfo.inHeight, inWidth = convInfo.inWidth, padInfo = convInfo.padInfo, strideHeight = convInfo.strideHeight, strideWidth = convInfo.strideWidth, filterHeight = convInfo.filterHeight, filterWidth = convInfo.filterWidth, dilationHeight = convInfo.dilationHeight, dilationWidth = convInfo.dilationWidth;
          var padTop = padInfo.top, padLeft = padInfo.left;
          this.userCode = "\n      const ivec2 strides = ivec2(".concat(strideHeight, ", ").concat(strideWidth, ");\n      const ivec2 pads = ivec2(").concat(padTop, ", ").concat(padLeft, ");\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 < ").concat(filterHeight, "; h++) {\n          int hIn = hBeg + h * ").concat(dilationHeight, ";\n\n          if (hIn >= 0 && hIn < ").concat(inHeight, ") {\n            for (int w = 0; w < ").concat(filterWidth, "; w++) {\n              int wIn = wBeg + w * ").concat(dilationWidth, ";\n\n              if (wIn >= 0 && wIn < ").concat(inWidth, ") {\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    ");
        }
        return Dilation2DProgram2;
      }()
    );
    function dilation2D(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, filter = inputs.filter;
      var strides = attrs.strides, pad = attrs.pad, dilations = attrs.dilations;
      var convInfo = tf.backend_util.computeDilation2DInfo(x.shape, filter.shape, strides, pad, "NHWC", dilations);
      var out;
      var program = new Dilation2DProgram(convInfo);
      out = backend.runWebGLProgram(program, [x, filter], "float32");
      var outReshaped = reshape({ inputs: { x: out }, backend, attrs: { shape: convInfo.outShape } });
      backend.disposeIntermediateTensorInfo(out);
      return outReshaped;
    }
    var dilation2DConfig = {
      kernelName: tf.Dilation2D,
      backendName: "webgl",
      kernelFunc: dilation2D
    };
    function einsum(args) {
      var e_12, _a2, e_2, _b;
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var equation = attrs.equation;
      var tensors = inputs;
      var _c = tf.backend_util.decodeEinsumEquation(equation, tensors.length), allDims = _c.allDims, summedDims = _c.summedDims, idDims = _c.idDims;
      tf.backend_util.checkEinsumDimSizes(allDims.length, idDims, tensors);
      var _d = tf.backend_util.getEinsumComputePath(summedDims, idDims), path = _d.path, steps = _d.steps;
      var nSteps = steps.length;
      var out = null;
      var numDimsRemaining = allDims.length;
      var tensorsToDispose = [];
      for (var i = 0; i < nSteps; ++i) {
        try {
          for (var _e = (e_12 = void 0, __values(steps[i])), _f = _e.next(); !_f.done; _f = _e.next()) {
            var idTerm = _f.value;
            var _g = tf.backend_util.getEinsumPermutation(numDimsRemaining, idDims[idTerm]), perm = _g.permutationIndices, dimsToExpand = _g.expandDims;
            var x = void 0;
            if (tf.backend_util.isIdentityPermutation(perm)) {
              x = tensors[idTerm];
            } else {
              x = transpose({ inputs: { x: tensors[idTerm] }, backend, attrs: { perm } });
              tensorsToDispose.push(x);
            }
            var targetShape = x.shape.slice();
            for (var k = 0; k < dimsToExpand.length; ++k) {
              targetShape.splice(dimsToExpand[k], 0, 1);
            }
            if (!tf.util.arraysEqual(x.shape, targetShape)) {
              x = reshape({ inputs: { x }, backend, attrs: { shape: targetShape } });
              tensorsToDispose.push(x);
            }
            if (out === null) {
              out = x;
            } else {
              out = multiply({ inputs: { a: x, b: out }, backend });
              tensorsToDispose.push(out);
            }
          }
        } catch (e_1_1) {
          e_12 = { error: e_1_1 };
        } finally {
          try {
            if (_f && !_f.done && (_a2 = _e.return)) _a2.call(_e);
          } finally {
            if (e_12) throw e_12.error;
          }
        }
        if (i < nSteps - 1) {
          if (path[i] >= 0) {
            out = sum({
              inputs: { x: out },
              backend,
              attrs: {
                axis: path[i] - (allDims.length - numDimsRemaining),
                keepDims: false
              }
            });
            tensorsToDispose.push(out);
          }
          numDimsRemaining--;
        }
      }
      try {
        for (var tensorsToDispose_1 = __values(tensorsToDispose), tensorsToDispose_1_1 = tensorsToDispose_1.next(); !tensorsToDispose_1_1.done; tensorsToDispose_1_1 = tensorsToDispose_1.next()) {
          var tensorInfo = tensorsToDispose_1_1.value;
          if (tensorInfo === out) {
            continue;
          }
          backend.disposeIntermediateTensorInfo(tensorInfo);
        }
      } catch (e_2_1) {
        e_2 = { error: e_2_1 };
      } finally {
        try {
          if (tensorsToDispose_1_1 && !tensorsToDispose_1_1.done && (_b = tensorsToDispose_1.return)) _b.call(tensorsToDispose_1);
        } finally {
          if (e_2) throw e_2.error;
        }
      }
      return out;
    }
    var einsumConfig = {
      kernelName: tf.Einsum,
      backendName: "webgl",
      kernelFunc: einsum
    };
    var ELU = "return (x >= 0.0) ? x : (exp(x) - 1.0);";
    var ELU_PACKED = "\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";
    var elu = unaryKernelFunc({ opSnippet: ELU, packedOpSnippet: ELU_PACKED });
    var eluConfig = {
      kernelName: tf.Elu,
      backendName: "webgl",
      kernelFunc: elu
    };
    var ELU_DER = "return (b >= 0.0) ? a : a * (b + 1.0);";
    var ELU_DER_PACKED = "\n  vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n  return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n";
    var eluGrad = function(args) {
      var inputs = args.inputs, backend = args.backend;
      var dy = inputs.dy, y = inputs.y;
      var program = tf.env().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new BinaryOpPackedProgram(ELU_DER_PACKED, dy.shape, y.shape) : new BinaryOpProgram(ELU_DER, dy.shape, y.shape);
      return backend.runWebGLProgram(program, [dy, y], dy.dtype);
    };
    var eluGradConfig = {
      kernelName: tf.EluGrad,
      backendName: "webgl",
      kernelFunc: eluGrad
    };
    var PACKED_EQUAL = "\n  return vec4(equal(a, b));\n";
    var EQUAL = "return float(a == b);";
    var equal = binaryKernelFunc({
      opSnippet: EQUAL,
      packedOpSnippet: PACKED_EQUAL,
      dtype: "bool",
      cpuKernelImpl: equalImplCPU
    });
    var equalConfig = {
      kernelName: tf.Equal,
      backendName: "webgl",
      kernelFunc: equal
    };
    var ERF = '\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 = '.concat(tf.backend_util.ERF_P, ";\n  float a1 = ").concat(tf.backend_util.ERF_A1, ";\n  float a2 = ").concat(tf.backend_util.ERF_A2, ";\n  float a3 = ").concat(tf.backend_util.ERF_A3, ";\n  float a4 = ").concat(tf.backend_util.ERF_A4, ";\n  float a5 = ").concat(tf.backend_util.ERF_A5, ";\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");
    var erf = unaryKernelFunc({ opSnippet: ERF });
    var erfConfig = {
      kernelName: tf.Erf,
      backendName: "webgl",
      kernelFunc: erf
    };
    var EXP = CHECK_NAN_SNIPPET_UNARY + "\n  return exp(x);\n";
    var EXP_PACKED = "\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";
    var exp = unaryKernelFunc({
      opSnippet: EXP,
      packedOpSnippet: EXP_PACKED,
      cpuKernelImpl: expImplCPU,
      dtype: "float32"
    });
    var expConfig = {
      kernelName: tf.Exp,
      backendName: "webgl",
      kernelFunc: exp
    };
    function expandDims(args) {
      var inputs = args.inputs, attrs = args.attrs, backend = args.backend;
      var dim = attrs.dim;
      var input = inputs.input;
      var inputRank = input.shape.length;
      var newShape = input.shape.slice();
      var $dim = dim;
      if (dim < 0) {
        tf.util.assert(-(inputRank + 1) <= dim, function() {
          return "Axis must be in the interval [".concat(-(inputRank + 1), ", ").concat(inputRank, "]");
        });
        $dim = inputRank + dim + 1;
      }
      newShape.splice($dim, 0, 1);
      return reshape({ inputs: { x: input }, backend, attrs: { shape: newShape } });
    }
    var expandDimsConfig = {
      kernelName: tf.ExpandDims,
      backendName: "webgl",
      kernelFunc: expandDims
    };
    var EXPM1 = "return exp(x) - 1.0;";
    var expm1 = unaryKernelFunc({ opSnippet: EXPM1, packedOpSnippet: EXPM1, cpuKernelImpl: expm1ImplCPU });
    var expm1Config = {
      kernelName: tf.Expm1,
      backendName: "webgl",
      kernelFunc: expm1
    };
    var FFTProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function FFTProgram2(component, inputShape, inverse) {
          this.variableNames = ["real", "imag"];
          var innerDim = inputShape[1];
          this.outputShape = inputShape;
          var exponentMultiplierSnippet = inverse ? "2.0 * ".concat(Math.PI) : "-2.0 * ".concat(Math.PI);
          var resultDenominator = inverse ? "".concat(innerDim, ".0") : "1.0";
          var opString;
          if (component === "real") {
            opString = "return real * expR - imag * expI;";
          } else if (component === "imag") {
            opString = "return real * expI + imag * expR;";
          } else {
            throw new Error('FFT component must be either "real" or "imag", got '.concat(component, "."));
          }
          this.userCode = "\n      const float exponentMultiplier = ".concat(exponentMultiplierSnippet, ";\n\n      float unaryOpComplex(float real, float expR, float imag, float expI) {\n        ").concat(opString, "\n      }\n\n      float mulMatDFT(int batch, int index) {\n        float indexRatio = float(index) / float(").concat(innerDim, ");\n        float exponentMultiplierTimesIndexRatio =\n            exponentMultiplier * indexRatio;\n\n        float result = 0.0;\n\n        for (int i = 0; i < ").concat(innerDim, "; 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) / ").concat(resultDenominator, ";\n        }\n\n        return result;\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        setOutput(mulMatDFT(coords[0], coords[1]));\n      }\n    ");
        }
        return FFTProgram2;
      }()
    );
    function fftImpl(x, inverse, backend) {
      var xData = backend.texData.get(x.dataId);
      var inputSize = tf.util.sizeFromShape(x.shape);
      var innerDimensionSize = x.shape[x.shape.length - 1];
      var batch = inputSize / innerDimensionSize;
      var input2D = reshape({ inputs: { x }, backend, attrs: { shape: [batch, innerDimensionSize] } });
      var xShape = input2D.shape;
      var realProgram = new FFTProgram("real", xShape, inverse);
      var imagProgram = new FFTProgram("imag", xShape, inverse);
      var inputs = [
        {
          dataId: xData.complexTensorInfos.real.dataId,
          dtype: xData.complexTensorInfos.real.dtype,
          shape: xShape
        },
        {
          dataId: xData.complexTensorInfos.imag.dataId,
          dtype: xData.complexTensorInfos.imag.dtype,
          shape: xShape
        }
      ];
      var realPart = backend.runWebGLProgram(realProgram, inputs, "float32");
      var imagPart = backend.runWebGLProgram(imagProgram, inputs, "float32");
      var complexOutput = complex({ inputs: { real: realPart, imag: imagPart }, backend });
      backend.disposeIntermediateTensorInfo(realPart);
      backend.disposeIntermediateTensorInfo(imagPart);
      var complexOutputReshaped = reshape({ inputs: { x: complexOutput }, backend, attrs: { shape: x.shape } });
      backend.disposeIntermediateTensorInfo(input2D);
      backend.disposeIntermediateTensorInfo(complexOutput);
      return complexOutputReshaped;
    }
    function fft(args) {
      var inputs = args.inputs, backend = args.backend;
      var input = inputs.input;
      return fftImpl(input, false, backend);
    }
    var fftConfig = {
      kernelName: tf.FFT,
      backendName: "webgl",
      kernelFunc: fft
    };
    var FillProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function FillProgram2(shape, value) {
          this.outputShape = [];
          this.customUniforms = [{ name: "value", type: "float" }];
          this.variableNames = ["x"];
          this.outputShape = shape;
          this.userCode = "\n      void main() {\n        // Input can be obtained from uniform value.\n        setOutput(value);\n      }\n    ";
        }
        return FillProgram2;
      }()
    );
    function fill(args) {
      var backend = args.backend, attrs = args.attrs;
      var shape = attrs.shape, value = attrs.value;
      var dtype = attrs.dtype;
      dtype = dtype || tf.util.inferDtype(value);
      if (dtype === "string") {
        var values = tf.util.getArrayFromDType(dtype, tf.util.sizeFromShape(shape));
        values.fill(value);
        return backend.makeTensorInfo(shape, dtype, values);
      } else {
        var program = new FillProgram(shape, value);
        var customValues = [[value]];
        return backend.runWebGLProgram(program, [], dtype, customValues);
      }
    }
    var fillConfig = {
      kernelName: tf.Fill,
      backendName: "webgl",
      kernelFunc: fill
    };
    var FlipLeftRightProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function FlipLeftRightProgram2(imageShape) {
          this.variableNames = ["Image"];
          this.outputShape = [];
          var imageWidth = imageShape[2];
          this.outputShape = imageShape;
          this.userCode = "\n        void main() {\n          ivec4 coords = getOutputCoords();\n          int x = coords[2];\n\n          int coordX = ".concat(imageWidth, " - x - 1;\n          float outputValue;\n          if(coordX >= 0 && coordX < ").concat(imageWidth, ") {\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    ");
        }
        return FlipLeftRightProgram2;
      }()
    );
    var flipLeftRightConfig = {
      kernelName: tf.FlipLeftRight,
      backendName: "webgl",
      kernelFunc: function(_a2) {
        var inputs = _a2.inputs, backend = _a2.backend;
        var image = inputs.image;
        var webglBackend = backend;
        var program = new FlipLeftRightProgram(image.shape);
        var output = webglBackend.runWebGLProgram(program, [image], image.dtype);
        return output;
      }
    };
    var FLOOR = "return floor(x);";
    var floor = unaryKernelFunc({ opSnippet: FLOOR, packedOpSnippet: FLOOR, cpuKernelImpl: floorImplCPU });
    var floorConfig = {
      kernelName: tf.Floor,
      backendName: "webgl",
      kernelFunc: floor
    };
    var INT_DIV = "\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";
    var INT_DIV_PACKED = "\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";
    var floorDiv = binaryKernelFunc({ opSnippet: INT_DIV, packedOpSnippet: INT_DIV_PACKED, dtype: "int32" });
    var floorDivConfig = {
      kernelName: tf.FloorDiv,
      backendName: "webgl",
      kernelFunc: floorDiv
    };
    var FromPixelsProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function FromPixelsProgram2(outputShape) {
          this.variableNames = ["A"];
          var glsl = getGlslDifferences();
          var _a2 = __read(outputShape, 2), height = _a2[0], width = _a2[1];
          this.outputShape = outputShape;
          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(".concat(width, ".0, ").concat(height, ".0);\n\n        vec4 values = ").concat(glsl.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    ");
        }
        return FromPixelsProgram2;
      }()
    );
    var FromPixelsPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function FromPixelsPackedProgram2(outputShape) {
          this.variableNames = ["A"];
          this.packedInputs = false;
          this.packedOutput = true;
          var glsl = getGlslDifferences();
          var _a2 = __read(outputShape, 2), height = _a2[0], width = _a2[1];
          this.outputShape = outputShape;
          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(".concat(width, ".0, ").concat(height, ".0);\n            vec4 values = ").concat(glsl.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        ").concat(glsl.output, " = result;\n      }\n    ");
        }
        return FromPixelsPackedProgram2;
      }()
    );
    var fromPixelsConfig = {
      kernelName: tf.FromPixels,
      backendName: "webgl",
      kernelFunc: fromPixels
    };
    var fromPixels2DContext;
    var willReadFrequently = tf.env().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");
    function fromPixels(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var pixels = inputs.pixels;
      var numChannels = attrs.numChannels;
      var isVideo = typeof HTMLVideoElement !== "undefined" && pixels instanceof HTMLVideoElement;
      var isImage = typeof HTMLImageElement !== "undefined" && pixels instanceof HTMLImageElement;
      var _a2 = __read(isVideo ? [
        pixels.videoWidth,
        pixels.videoHeight
      ] : [pixels.width, pixels.height], 2), width = _a2[0], height = _a2[1];
      var texShape = [height, width];
      var outShape = [height, width, numChannels];
      if (isImage || isVideo) {
        var newWillReadFrequently = tf.env().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");
        if (fromPixels2DContext == null || newWillReadFrequently !== willReadFrequently) {
          willReadFrequently = newWillReadFrequently;
          fromPixels2DContext = document.createElement("canvas").getContext("2d", { willReadFrequently });
        }
        fromPixels2DContext.canvas.width = width;
        fromPixels2DContext.canvas.height = height;
        fromPixels2DContext.drawImage(pixels, 0, 0, width, height);
        pixels = fromPixels2DContext.canvas;
      }
      var tempPixelHandle = backend.makeTensorInfo(texShape, "int32");
      backend.texData.get(tempPixelHandle.dataId).usage = TextureUsage.PIXELS;
      backend.gpgpu.uploadPixelDataToTexture(backend.getTexture(tempPixelHandle.dataId), pixels);
      var program = tf.env().getBool("WEBGL_PACK") ? new FromPixelsPackedProgram(outShape) : new FromPixelsProgram(outShape);
      var res = backend.runWebGLProgram(program, [tempPixelHandle], "int32");
      backend.disposeData(tempPixelHandle.dataId);
      return res;
    }
    function fusedConv2d(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, filter = inputs.filter, bias = inputs.bias, preluActivationWeights = inputs.preluActivationWeights;
      var strides = attrs.strides, pad = attrs.pad, dataFormat = attrs.dataFormat, dilations = attrs.dilations, dimRoundingMode = attrs.dimRoundingMode, activation = attrs.activation, leakyreluAlpha = attrs.leakyreluAlpha;
      var $dataFormat = tf.backend_util.convertConv2DDataFormat(dataFormat);
      var convInfo = tf.backend_util.computeConv2DInfo(x.shape, filter.shape, strides, dilations, pad, dimRoundingMode, false, $dataFormat);
      var out;
      var intermediates = [];
      var hasBias = bias != null;
      var hasPreluActivationWeights = preluActivationWeights != null;
      var hasLeakyreluAlpha = activation === "leakyrelu";
      var prepareInputs = function() {
        var inputs2 = [x, filter];
        var alignInputWithDataFormat = function(input, dataFormat2) {
          if (dataFormat2 === "NCHW" && input.shape.length === 1 && input.shape[0] !== 1) {
            var alignedInput = reshape({
              inputs: { x: input },
              backend,
              attrs: { shape: [input.shape[0], 1, 1] }
            });
            intermediates.push(alignedInput);
            return alignedInput;
          }
          return input;
        };
        if (hasBias) {
          inputs2.push(alignInputWithDataFormat(bias, dataFormat));
        }
        if (hasPreluActivationWeights) {
          inputs2.push(alignInputWithDataFormat(preluActivationWeights, dataFormat));
        }
        if (hasLeakyreluAlpha) {
          var $leakyreluAlpha = backend.makeTensorInfo([], "float32", tf.util.createScalarValue(leakyreluAlpha, "float32"));
          inputs2.push($leakyreluAlpha);
          intermediates.push($leakyreluAlpha);
        }
        return inputs2;
      };
      if (convInfo.filterHeight === 1 && convInfo.filterWidth === 1 && convInfo.dilationHeight === 1 && convInfo.dilationWidth === 1 && convInfo.strideHeight === 1 && convInfo.strideWidth === 1 && (convInfo.padInfo.type === "SAME" || convInfo.padInfo.type === "VALID")) {
        out = conv2dByMatMul({
          x,
          filter,
          convInfo,
          backend,
          bias,
          activation,
          preluActivationWeights,
          leakyreluAlpha
        });
      } else if (convInfo.strideWidth <= 2 && $dataFormat === "channelsLast" && tf.env().getBool("WEBGL_EXP_CONV")) {
        var fusedActivation = activation ? mapActivationToShaderProgram(activation, true) : null;
        var program = new Conv2DPackedProgram(convInfo, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
        var customValues = [
          [convInfo.padInfo.top, convInfo.padInfo.left],
          [convInfo.strideHeight, convInfo.strideWidth],
          [convInfo.dilationHeight, convInfo.dilationWidth],
          [convInfo.inHeight, convInfo.inWidth]
        ];
        var inputs_1 = prepareInputs();
        out = backend.runWebGLProgram(program, inputs_1, "float32", customValues);
      } else if (tf.env().getBool("WEBGL_CONV_IM2COL")) {
        out = conv2dWithIm2Row({
          x,
          filter,
          convInfo,
          backend,
          bias,
          activation,
          preluActivationWeights,
          leakyreluAlpha
        });
      } else {
        var fusedActivation = activation ? mapActivationToShaderProgram(activation, false) : null;
        var program = new Conv2DProgram(convInfo, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
        var inputs_2 = prepareInputs();
        out = backend.runWebGLProgram(program, inputs_2, "float32");
      }
      var outReshaped = reshape({ inputs: { x: out }, backend, attrs: { shape: convInfo.outShape } });
      intermediates.push(out);
      intermediates.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return outReshaped;
    }
    var fusedConv2DConfig = {
      kernelName: tf.FusedConv2D,
      backendName: "webgl",
      kernelFunc: fusedConv2d
    };
    function fusedDepthwiseConv2D(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, filter = inputs.filter, bias = inputs.bias, preluActivationWeights = inputs.preluActivationWeights;
      var strides = attrs.strides, pad = attrs.pad, dilations = attrs.dilations, dimRoundingMode = attrs.dimRoundingMode, activation = attrs.activation, leakyreluAlpha = attrs.leakyreluAlpha;
      var intermediates = [];
      var $dilations = dilations;
      if ($dilations == null) {
        $dilations = [1, 1];
      }
      tf.util.assert(tf.backend_util.eitherStridesOrDilationsAreOne(strides, $dilations), function() {
        return "Error in depthwiseConv2d: Either strides or dilations must be " + "1. Got strides ".concat(strides, " and dilations '").concat($dilations, "'");
      });
      var convInfo = tf.backend_util.computeConv2DInfo(
        x.shape,
        filter.shape,
        strides,
        $dilations,
        pad,
        dimRoundingMode,
        true
        /* depthwise */
      );
      var shouldPackDepthwiseConv = tf.env().getBool("WEBGL_PACK_DEPTHWISECONV") && convInfo.strideWidth <= 2 && convInfo.outChannels / convInfo.inChannels === 1;
      var fusedActivation = activation ? mapActivationToShaderProgram(activation, shouldPackDepthwiseConv) : null;
      var programInputs = [x, filter];
      var hasBias = bias != null;
      var hasPreluActivationWeights = preluActivationWeights != null;
      var hasLeakyreluAlpha = activation === "leakyrelu";
      if (hasBias) {
        programInputs.push(bias);
      }
      if (hasPreluActivationWeights) {
        programInputs.push(preluActivationWeights);
      }
      if (hasLeakyreluAlpha) {
        var $leakyreluAlpha = backend.makeTensorInfo([], "float32", tf.util.createScalarValue(leakyreluAlpha, "float32"));
        programInputs.push($leakyreluAlpha);
        intermediates.push($leakyreluAlpha);
      }
      var program;
      if (shouldPackDepthwiseConv) {
        program = new DepthwiseConvPacked2DProgram(convInfo, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
      } else {
        program = new DepthwiseConv2DProgram(convInfo, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
      }
      var customValues = [
        [convInfo.padInfo.top, convInfo.padInfo.left],
        [convInfo.strideHeight, convInfo.strideWidth],
        [convInfo.dilationHeight, convInfo.dilationWidth],
        [convInfo.inHeight, convInfo.inWidth]
      ];
      var result = backend.runWebGLProgram(program, programInputs, "float32", customValues);
      intermediates.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return result;
    }
    var fusedDepthwiseConv2DConfig = {
      kernelName: tf.FusedDepthwiseConv2D,
      backendName: "webgl",
      kernelFunc: fusedDepthwiseConv2D
    };
    var GatherNDProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function GatherNDProgram2(sliceDim, strides, shape, paramsShape) {
          this.sliceDim = sliceDim;
          this.strides = strides;
          this.paramsShape = paramsShape;
          this.variableNames = ["x", "indices"];
          this.outputShape = shape;
          var dtype = getCoordsDataType(shape.length);
          var mainLoop = "\n    int index;";
          for (var j = 0; j < this.sliceDim; j++) {
            mainLoop += "\n          index = round(getIndices(coords[0], ".concat(j, "));\n          out_of_bounds = out_of_bounds || index < 0;\n          out_of_bounds = out_of_bounds || index >= ").concat(this.paramsShape[j], ";\n          flattenIndex += index * ").concat(this.strides[j], ";");
          }
          this.userCode = "\n         void main() {\n          ".concat(dtype, " coords = getOutputCoords();\n          int flattenIndex = 0;\n          bool out_of_bounds = false;\n\n          ").concat(mainLoop, "\n\n          setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));\n        }\n      ");
        }
        return GatherNDProgram2;
      }()
    );
    function gatherNd(args) {
      var inputs = args.inputs, backend = args.backend;
      var params = inputs.params, indices = inputs.indices;
      var indicesShape = indices.shape;
      var sliceRank = indicesShape[indicesShape.length - 1];
      var paramsSize = tf.util.sizeFromShape(params.shape);
      var _a2 = __read(tf.backend_util.prepareAndValidate(params, indices), 4), resultShape = _a2[0], numSlices = _a2[1], sliceSize = _a2[2], strides = _a2[3];
      var flattenIndices = reshape({ inputs: { x: indices }, backend, attrs: { shape: [numSlices, sliceRank] } });
      var flattenX = reshape({
        inputs: { x: params },
        backend,
        attrs: { shape: [tf.util.sizeFromShape(params.shape) / sliceSize, sliceSize] }
      });
      if (backend.shouldExecuteOnCPU([params, indices]) || params.dtype === "string") {
        var indicesData = backend.readSync(indices.dataId);
        var paramsBuf = backend.bufferSync(params);
        var outValue = gatherNdImplCPU(indicesData, paramsBuf, params.dtype, numSlices, sliceRank, sliceSize, strides, params.shape, paramsSize);
        return backend.makeTensorInfo(resultShape, params.dtype, outValue.values);
      }
      var program = new GatherNDProgram(sliceRank, strides, [numSlices, sliceSize], params.shape);
      var res = backend.runWebGLProgram(program, [flattenX, flattenIndices], flattenX.dtype);
      var reshaped = reshape({ inputs: { x: res }, backend, attrs: { shape: resultShape } });
      backend.disposeIntermediateTensorInfo(flattenIndices);
      backend.disposeIntermediateTensorInfo(flattenX);
      backend.disposeIntermediateTensorInfo(res);
      return reshaped;
    }
    var gatherNdConfig = {
      kernelName: tf.GatherNd,
      backendName: "webgl",
      kernelFunc: gatherNd
    };
    var GatherProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function GatherProgram2(aShape, outputShape) {
          this.variableNames = ["A", "indices"];
          this.outputShape = outputShape;
          this.rank = outputShape.length;
          var dtype = getCoordsDataType(this.rank);
          var sourceCoords = getSourceCoords$1(aShape);
          this.userCode = "\n      void main() {\n        ".concat(dtype, " resRC = getOutputCoords();\n        int index = int(getIndices(resRC.x, resRC.z));\n        float inBounds = (index >= 0) && (index < ").concat(aShape[2], ") ? 1.0 : 0.0;\n        setOutput(inBounds * getA(").concat(sourceCoords, "));\n      }\n    ");
        }
        return GatherProgram2;
      }()
    );
    function getSourceCoords$1(aShape, axis) {
      var currentCoords = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"];
      var sourceCoords = [];
      for (var i = 0; i < aShape.length; i++) {
        if (i === 2) {
          sourceCoords.push("index");
        } else {
          sourceCoords.push("".concat(currentCoords[i]));
        }
      }
      return sourceCoords.join();
    }
    function gatherV2(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, indices = inputs.indices;
      var axis = attrs.axis, batchDims = attrs.batchDims;
      var parsedAxis = tf.util.parseAxisParam(axis, x.shape)[0];
      if (tf.env().get("DEBUG")) {
        var indicesVals = backend.readSync(indices.dataId);
        var axisDim_1 = x.shape[parsedAxis];
        var _loop_1 = function(i2) {
          var index = indicesVals[i2];
          tf.util.assert(index <= axisDim_1 - 1 && index >= 0, function() {
            return "GatherV2: the index value ".concat(index, " is not in [0, ").concat(axisDim_1 - 1, "]");
          });
        };
        for (var i = 0; i < indicesVals.length; ++i) {
          _loop_1(i);
        }
      }
      var shapeInfo = tf.backend_util.segment_util.collectGatherOpShapeInfo(x, indices, parsedAxis, batchDims);
      var indicesSize = tf.util.sizeFromShape(indices.shape);
      var toDispose = [];
      var flattenX = reshape({
        inputs: { x },
        backend,
        attrs: {
          shape: [
            shapeInfo.batchSize,
            shapeInfo.outerSize,
            shapeInfo.dimSize,
            shapeInfo.sliceSize
          ]
        }
      });
      var flattenIndex = reshape({
        inputs: { x: indices },
        backend,
        attrs: { shape: [shapeInfo.batchSize, indicesSize / shapeInfo.batchSize] }
      });
      toDispose.push(flattenX);
      toDispose.push(flattenIndex);
      var flattenOutputShape = [
        shapeInfo.batchSize,
        shapeInfo.outerSize,
        indicesSize / shapeInfo.batchSize,
        shapeInfo.sliceSize
      ];
      if (backend.shouldExecuteOnCPU([x, indices]) || x.dtype === "string") {
        var indicesBuf = backend.bufferSync(flattenIndex);
        var xBuf = backend.bufferSync(flattenX);
        var outBuf = gatherV2ImplCPU(xBuf, indicesBuf, flattenOutputShape);
        toDispose.forEach(function(t) {
          return backend.disposeIntermediateTensorInfo(t);
        });
        return backend.makeTensorInfo(shapeInfo.outputShape, outBuf.dtype, outBuf.values);
      }
      var program = new GatherProgram(flattenX.shape, flattenOutputShape);
      var res = backend.runWebGLProgram(program, [flattenX, flattenIndex], flattenX.dtype);
      toDispose.push(res);
      var reshaped = reshape({ inputs: { x: res }, backend, attrs: { shape: shapeInfo.outputShape } });
      toDispose.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return reshaped;
    }
    var gatherV2Config = {
      kernelName: tf.GatherV2,
      backendName: "webgl",
      kernelFunc: gatherV2
    };
    var GREATER = "return float(a > b);";
    var GREATER_PACKED = "\n  return vec4(greaterThan(a, b));\n";
    var greater = binaryKernelFunc({
      opSnippet: GREATER,
      packedOpSnippet: GREATER_PACKED,
      cpuKernelImpl: greaterImplCPU,
      dtype: "bool"
    });
    var greaterConfig = {
      kernelName: tf.Greater,
      backendName: "webgl",
      kernelFunc: greater
    };
    var GREATER_EQUAL = "return float(a >= b);";
    var GREATER_EQUAL_PACKED = "\n  return vec4(greaterThanEqual(a, b));\n";
    var greaterEqual = binaryKernelFunc({
      opSnippet: GREATER_EQUAL,
      packedOpSnippet: GREATER_EQUAL_PACKED,
      dtype: "bool",
      cpuKernelImpl: greaterEqualImplCPU
    });
    var greaterEqualConfig = {
      kernelName: tf.GreaterEqual,
      backendName: "webgl",
      kernelFunc: greaterEqual
    };
    function ifft(args) {
      var inputs = args.inputs, backend = args.backend;
      var input = inputs.input;
      return fftImpl(input, true, backend);
    }
    var ifftConfig = {
      kernelName: tf.IFFT,
      backendName: "webgl",
      kernelFunc: ifft
    };
    var IS_FINITE = "return float(!isnan(x) && !isinf(x));";
    var isFinite2 = unaryKernelFunc({ opSnippet: IS_FINITE, dtype: "bool" });
    var isFiniteConfig = {
      kernelName: tf.IsFinite,
      backendName: "webgl",
      kernelFunc: isFinite2
    };
    var IS_INF = "return float(isinf(x));";
    var isInf = unaryKernelFunc({ opSnippet: IS_INF, dtype: "bool" });
    var isInfConfig = {
      kernelName: tf.IsInf,
      backendName: "webgl",
      kernelFunc: isInf
    };
    var IS_NAN = "return float(isnan(x));";
    var isNaN2 = unaryKernelFunc({ opSnippet: IS_NAN, dtype: "bool" });
    var isNaNConfig = {
      kernelName: tf.IsNan,
      backendName: "webgl",
      kernelFunc: isNaN2
    };
    var LESS = "return float(a < b);";
    var LESS_PACKED = "\n  return vec4(lessThan(a, b));\n";
    var less = binaryKernelFunc({
      opSnippet: LESS,
      packedOpSnippet: LESS_PACKED,
      cpuKernelImpl: lessImplCPU,
      dtype: "bool"
    });
    var lessConfig = {
      kernelName: tf.Less,
      backendName: "webgl",
      kernelFunc: less
    };
    var LESS_EQUAL = "return float(a <= b);";
    var LESS_EQUAL_PACKED = "\n  return vec4(lessThanEqual(a, b));\n";
    var lessEqual = binaryKernelFunc({
      opSnippet: LESS_EQUAL,
      packedOpSnippet: LESS_EQUAL_PACKED,
      cpuKernelImpl: lessEqualImplCPU,
      dtype: "bool"
    });
    var lessEqualConfig = {
      kernelName: tf.LessEqual,
      backendName: "webgl",
      kernelFunc: lessEqual
    };
    function linSpace(args) {
      var backend = args.backend, attrs = args.attrs;
      var start = attrs.start, stop = attrs.stop, num = attrs.num;
      var outVals = linSpaceImplCPU(start, stop, num);
      return backend.makeTensorInfo([outVals.length], "float32", outVals);
    }
    var linSpaceConfig = {
      kernelName: tf.LinSpace,
      backendName: "webgl",
      kernelFunc: linSpace
    };
    var LOG = CHECK_NAN_SNIPPET_UNARY + "\n  return x < 0.0 ? 0./0. : log(x);\n";
    var LOG_PACKED = "\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";
    var log = unaryKernelFunc({ opSnippet: LOG, packedOpSnippet: LOG_PACKED, cpuKernelImpl: logImplCPU });
    var logConfig = {
      kernelName: tf.Log,
      backendName: "webgl",
      kernelFunc: log
    };
    var LOG1P = CHECK_NAN_SNIPPET_UNARY + "\n  return log(1.0 + x);\n";
    var log1p = unaryKernelFunc({ opSnippet: LOG1P });
    var log1pConfig = {
      kernelName: tf.Log1p,
      backendName: "webgl",
      kernelFunc: log1p
    };
    var LOGICAL_AND = "return float(a >= 1.0 && b >= 1.0);";
    var LOGICAL_AND_PACKED = "\n  return vec4(\n    vec4(greaterThanEqual(a, vec4(1.0))) *\n    vec4(greaterThanEqual(b, vec4(1.0))));\n";
    var logicalAnd = binaryKernelFunc({
      opSnippet: LOGICAL_AND,
      packedOpSnippet: LOGICAL_AND_PACKED,
      dtype: "bool"
    });
    var logicalAndConfig = {
      kernelName: tf.LogicalAnd,
      backendName: "webgl",
      kernelFunc: logicalAnd
    };
    var LOGICAL_NOT = "return float(!(x >= 1.0));";
    var logicalNot = unaryKernelFunc({ opSnippet: LOGICAL_NOT });
    var logicalNotConfig = {
      kernelName: tf.LogicalNot,
      backendName: "webgl",
      kernelFunc: logicalNot
    };
    var LOGICAL_OR = "return float(a >= 1.0 || b >= 1.0);";
    var LOGICAL_OR_PACKED = "\n  return min(\n    vec4(greaterThanEqual(a, vec4(1.0))) +\n    vec4(greaterThanEqual(b, vec4(1.0))),\n    vec4(1.0));\n";
    var logicalOr = binaryKernelFunc({ opSnippet: LOGICAL_OR, packedOpSnippet: LOGICAL_OR_PACKED, dtype: "bool" });
    var logicalOrConfig = {
      kernelName: tf.LogicalOr,
      backendName: "webgl",
      kernelFunc: logicalOr
    };
    var LRNProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function LRNProgram2(xShape, radius, bias, alpha, beta) {
          this.variableNames = ["x"];
          this.outputShape = [];
          var rad = radius;
          var maxD = xShape[3] - 1;
          this.outputShape = xShape;
          var powOperator;
          var basis = "float(".concat(bias, ") + float(").concat(alpha, ") * sum");
          if (beta === 0.5) {
            powOperator = "inversesqrt(".concat(basis, ")");
          } else if (beta === 1) {
            powOperator = "1.0/(".concat(basis, ")");
          } else {
            powOperator = "exp(log(".concat(basis, ") * float(-").concat(beta, "));");
          }
          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 = -".concat(rad, "; j <= ").concat(rad, "; j++) {\n          int idx = d + j;\n          if (idx >= 0 && idx <=  ").concat(maxD, ") {\n            float z = getX(b, r, c, idx);\n            sum += z * z;\n          }\n        }\n        float val = x * ").concat(powOperator, ";\n        setOutput(val);\n      }\n    ");
        }
        return LRNProgram2;
      }()
    );
    var LRNPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function LRNPackedProgram2(xShape, radius, bias, alpha, beta) {
          this.variableNames = ["x"];
          this.outputShape = [];
          this.packedInputs = true;
          this.packedOutput = true;
          var rad = radius;
          var maxD = xShape[3] - 1;
          this.outputShape = xShape;
          var powOperator;
          var basis = "float(".concat(bias, ") + float(").concat(alpha, ") * sum");
          if (beta === 0.5) {
            powOperator = "inversesqrt(".concat(basis, ")");
          } else if (beta === 1) {
            powOperator = "1.0/(".concat(basis, ")");
          } else {
            powOperator = "exp(log(".concat(basis, ") * float(-").concat(beta, "));");
          }
          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 < ".concat(this.outputShape[3], ";\n        bool hasNextRow = c < ").concat(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 - ").concat(rad, ";\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 = - ").concat(rad, "; j <= ").concat(rad, "; j++) {\n          ivec2 idx = depth + j;\n          bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n          bvec2 belowUpperBound = lessThanEqual(idx, ivec2(").concat(maxD, "));\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 * ").concat(powOperator, ";\n        setOutput(result);\n      }\n    ");
        }
        return LRNPackedProgram2;
      }()
    );
    var lrn = function(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var depthRadius = attrs.depthRadius, bias = attrs.bias, alpha = attrs.alpha, beta = attrs.beta;
      var program = tf.env().getBool("WEBGL_PACK_NORMALIZATION") ? new LRNPackedProgram(x.shape, depthRadius, bias, alpha, beta) : new LRNProgram(x.shape, depthRadius, bias, alpha, beta);
      return backend.runWebGLProgram(program, [x], x.dtype);
    };
    var LRNConfig = {
      kernelName: tf.LRN,
      backendName: "webgl",
      kernelFunc: lrn
    };
    var LRNGradProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function LRNGradProgram2(inputShape, depthRadius, bias, alpha, beta) {
          this.variableNames = ["inputImage", "outputImage", "dy"];
          this.outputShape = [];
          this.outputShape = inputShape;
          this.depth = inputShape[3];
          this.depthRadius = depthRadius;
          this.bias = bias;
          this.alpha = alpha;
          this.beta = beta;
          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 < ".concat(this.depth, "; ++d) {\n          int depthBegin = int(max(0.0, float(d - ").concat(depthRadius, ")));\n          int depthEnd = int(min(float(").concat(this.depth, "),\n              float(d + ").concat(depthRadius, " + 1)));\n\n          const int MIN_DEPTH_BEGIN = 0;\n          const int MAX_DEPTH_END = ").concat(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(").concat(alpha, ") * norm + float(").concat(bias, ");\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(").concat(alpha, ")\n                * float(").concat(beta, ")\n                * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d)\n                / norm;\n              if (k == d) {\n                dyi += pow(norm, -1.0 * ").concat(beta, ");\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    ");
        }
        return LRNGradProgram2;
      }()
    );
    var lrnGrad = function(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, y = inputs.y, dy = inputs.dy;
      var depthRadius = attrs.depthRadius, bias = attrs.bias, alpha = attrs.alpha, beta = attrs.beta;
      var program = new LRNGradProgram(x.shape, depthRadius, bias, alpha, beta);
      return backend.runWebGLProgram(program, [x, y, dy], x.dtype);
    };
    var LRNGradConfig = {
      kernelName: tf.LRNGrad,
      backendName: "webgl",
      kernelFunc: lrnGrad
    };
    function maxImpl(x, reduceShape, outShape, backend) {
      var inSize = tf.util.sizeFromShape(reduceShape);
      var xSize = tf.util.sizeFromShape(x.shape);
      var batchSize = xSize / inSize;
      var reshapedInput = reshape({ inputs: { x }, attrs: { shape: [batchSize, inSize] }, backend });
      var reduced = reduce(reshapedInput, x.dtype, "max", backend);
      var reshapedOutput = reshape({ inputs: { x: reduced }, attrs: { shape: outShape }, backend });
      backend.disposeIntermediateTensorInfo(reshapedInput);
      backend.disposeIntermediateTensorInfo(reduced);
      return reshapedOutput;
    }
    function max(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var reductionIndices = attrs.reductionIndices, keepDims = attrs.keepDims;
      var xRank = x.shape.length;
      var origAxes = tf.util.parseAxisParam(reductionIndices, x.shape);
      var axes = origAxes;
      var permutedAxes = tf.backend_util.getAxesPermutation(axes, xRank);
      var maxInputIsTransposed = permutedAxes != null;
      var shouldExecuteOnCPU = backend.shouldExecuteOnCPU([x]);
      var maxInput = x;
      if (maxInputIsTransposed) {
        if (shouldExecuteOnCPU) {
          var xTexData = backend.texData.get(maxInput.dataId);
          var values = xTexData.values;
          var newShape = new Array(xRank);
          for (var i = 0; i < newShape.length; i++) {
            newShape[i] = x.shape[permutedAxes[i]];
          }
          var maxInputValues = transposeImplCPU(values, x.shape, x.dtype, permutedAxes, newShape);
          maxInput = backend.makeTensorInfo(newShape, x.dtype);
          var maxInputData = backend.texData.get(maxInput.dataId);
          maxInputData.values = maxInputValues;
        } else {
          maxInput = transposeImpl(x, permutedAxes, backend);
        }
        axes = tf.backend_util.getInnerMostAxes(axes.length, xRank);
      }
      tf.backend_util.assertAxesAreInnerMostDims("max", axes, xRank);
      var _a2 = __read(tf.backend_util.computeOutAndReduceShapes(maxInput.shape, axes), 2), maxOutShape = _a2[0], reduceShape = _a2[1];
      var outShape = maxOutShape;
      if (keepDims) {
        outShape = tf.backend_util.expandShapeToKeepDim(maxOutShape, origAxes);
      }
      var out;
      if (shouldExecuteOnCPU) {
        var xTexData = backend.texData.get(maxInput.dataId);
        var values = xTexData.values;
        var outValues = maxImplCPU(values, tf.util.sizeFromShape(reduceShape), outShape, x.dtype);
        out = backend.makeTensorInfo(outShape, x.dtype);
        var outData = backend.texData.get(out.dataId);
        outData.values = outValues;
      } else {
        out = maxImpl(maxInput, reduceShape, outShape, backend);
      }
      if (maxInputIsTransposed) {
        backend.disposeIntermediateTensorInfo(maxInput);
      }
      return out;
    }
    var maxConfig = {
      kernelName: tf.Max,
      backendName: "webgl",
      kernelFunc: max
    };
    var MAXIMUM = CHECK_NAN_SNIPPET + "\n  return max(a, b);\n";
    var MAXIMUM_PACKED = "\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  " + CHECK_NAN_SNIPPET_PACKED + "\n  return result;\n";
    var maximum = binaryKernelFunc({
      opSnippet: MAXIMUM,
      packedOpSnippet: MAXIMUM_PACKED,
      cpuKernelImpl: maximumImplCPU
    });
    var maximumConfig = {
      kernelName: tf.Maximum,
      backendName: "webgl",
      kernelFunc: maximum
    };
    function maxPool(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      assertNotComplex(x, "maxPool");
      var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
      var dilations = 1;
      tf.util.assert(tf.backend_util.eitherStridesOrDilationsAreOne(strides, dilations), function() {
        return "Error in maxPool: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
      });
      var convInfo = tf.backend_util.computePool2DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode);
      if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 && tf.util.arraysEqual(convInfo.inShape, convInfo.outShape)) {
        return identity({ inputs: { x }, backend });
      }
      var maxPoolProgram = new Pool2DProgram(convInfo, "max", false);
      return backend.runWebGLProgram(maxPoolProgram, [x], x.dtype);
    }
    var maxPoolConfig = {
      kernelName: tf.MaxPool,
      backendName: "webgl",
      kernelFunc: maxPool
    };
    function maxPool3d(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dataFormat = attrs.dataFormat, dimRoundingMode = attrs.dimRoundingMode;
      var dilations = [1, 1, 1];
      var convInfo = tf.backend_util.computePool3DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode, dataFormat);
      var maxPoolProgram = new Pool3DProgram(convInfo, "max", false);
      return backend.runWebGLProgram(maxPoolProgram, [x], x.dtype);
    }
    var maxPool3DConfig = {
      kernelName: tf.MaxPool3D,
      backendName: "webgl",
      kernelFunc: maxPool3d
    };
    var MaxPool2DBackpropProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function MaxPool2DBackpropProgram2(convInfo) {
          this.variableNames = ["dy", "maxPos"];
          this.outputShape = convInfo.inShape;
          var strideHeight = convInfo.strideHeight;
          var strideWidth = convInfo.strideWidth;
          var dilationHeight = convInfo.dilationHeight;
          var effectiveFilterHeight = convInfo.effectiveFilterHeight;
          var effectiveFilterWidth = convInfo.effectiveFilterWidth;
          var padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
          var padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
          var lastIndex = effectiveFilterHeight * effectiveFilterWidth - 1;
          this.userCode = "\n      const ivec2 pads = ivec2(".concat(padTop, ", ").concat(padLeft, ");\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 < ").concat(effectiveFilterHeight, ";\n          wR += ").concat(dilationHeight, ") {\n          float dyR = float(dyRCorner + wR) / ").concat(strideHeight, ".0;\n\n          if (dyR < 0.0 || dyR >= ").concat(convInfo.outHeight, ".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          for (int wC = 0; wC < ").concat(effectiveFilterWidth, "; wC++) {\n            float dyC = float(dyCCorner + wC) / ").concat(strideWidth, ".0;\n\n            if (dyC < 0.0 || dyC >= ").concat(convInfo.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 = ").concat(lastIndex, " - 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 * ").concat(effectiveFilterWidth, " + wC;\n            float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n            dotProd += dyValue * mask;\n          }\n        }\n        setOutput(dotProd);\n      }\n    ");
        }
        return MaxPool2DBackpropProgram2;
      }()
    );
    var MaxPool3DBackpropProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function MaxPool3DBackpropProgram2(convInfo) {
          this.variableNames = ["dy", "maxPos"];
          this.outputShape = convInfo.inShape;
          var strideDepth = convInfo.strideDepth;
          var strideHeight = convInfo.strideHeight;
          var strideWidth = convInfo.strideWidth;
          var dilationDepth = convInfo.dilationDepth;
          var dilationHeight = convInfo.dilationHeight;
          var dilationWidth = convInfo.dilationWidth;
          var effectiveFilterDepth = convInfo.effectiveFilterDepth;
          var effectiveFilterHeight = convInfo.effectiveFilterHeight;
          var effectiveFilterWidth = convInfo.effectiveFilterWidth;
          var padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;
          var padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
          var padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
          var lastIndex = effectiveFilterDepth * effectiveFilterHeight * effectiveFilterWidth - 1;
          this.userCode = "\n      const ivec3 pads = ivec3(".concat(padFront, ", ").concat(padTop, ", ").concat(padLeft, ");\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 < ").concat(effectiveFilterDepth, ";\n           wD += ").concat(dilationDepth, ") {\n          float dyD = float(dyDCorner + wD) / ").concat(strideDepth, ".0;\n\n          if (dyD < 0.0 || dyD >= ").concat(convInfo.outDepth, ".0 || fract(dyD) > 0.0) {\n            continue;\n          }\n          int idyD = int(dyD);\n\n          for (int wR = 0; wR < ").concat(effectiveFilterHeight, ";\n              wR += ").concat(dilationHeight, ") {\n            float dyR = float(dyRCorner + wR) / ").concat(strideHeight, ".0;\n\n            if (dyR < 0.0 || dyR >= ").concat(convInfo.outHeight, ".0 ||\n                fract(dyR) > 0.0) {\n              continue;\n            }\n            int idyR = int(dyR);\n\n            for (int wC = 0; wC < ").concat(effectiveFilterWidth, ";\n                wC += ").concat(dilationWidth, ") {\n              float dyC = float(dyCCorner + wC) / ").concat(strideWidth, ".0;\n\n              if (dyC < 0.0 || dyC >= ").concat(convInfo.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 = ").concat(lastIndex, " -\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 * ").concat(effectiveFilterHeight, " * ").concat(effectiveFilterWidth, " +\n                  wR * ").concat(effectiveFilterWidth, " + wC;\n              float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n              dotProd += dyValue * mask;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    ");
        }
        return MaxPool3DBackpropProgram2;
      }()
    );
    function maxPool3DGrad(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var dy = inputs.dy, input = inputs.input;
      var x = input;
      var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
      var dilations = [1, 1, 1];
      var convInfo = tf.backend_util.computePool3DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode);
      var maxPool3dPositionsProgram = new Pool3DProgram(
        convInfo,
        "max",
        true
        /* get positions */
      );
      var maxPool3dPositions = backend.runWebGLProgram(maxPool3dPositionsProgram, [x], x.dtype);
      var maxPoolBackpropProgram = new MaxPool3DBackpropProgram(convInfo);
      var result = backend.runWebGLProgram(maxPoolBackpropProgram, [dy, maxPool3dPositions], x.dtype);
      backend.disposeIntermediateTensorInfo(maxPool3dPositions);
      return result;
    }
    var maxPool3DGradConfig = {
      kernelName: tf.MaxPool3DGrad,
      backendName: "webgl",
      kernelFunc: maxPool3DGrad
    };
    function maxPoolGrad(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var dy = inputs.dy, input = inputs.input, output = inputs.output;
      var x = input;
      assertNotComplex([input, output], "maxPoolGrad");
      var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
      var convInfo = tf.backend_util.computePool2DInfo(x.shape, filterSize, strides, 1, pad, dimRoundingMode);
      var getPositions = true;
      var maxPoolPositionsProgram = new Pool2DProgram(convInfo, "max", getPositions);
      var maxPoolPositions = backend.runWebGLProgram(maxPoolPositionsProgram, [x], x.dtype);
      var maxPoolBackPropProgram = new MaxPool2DBackpropProgram(convInfo);
      var result = backend.runWebGLProgram(maxPoolBackPropProgram, [dy, maxPoolPositions], x.dtype);
      backend.disposeIntermediateTensorInfo(maxPoolPositions);
      return result;
    }
    var maxPoolGradConfig = {
      kernelName: tf.MaxPoolGrad,
      backendName: "webgl",
      kernelFunc: maxPoolGrad
    };
    function maxPoolWithArgmaxImpl(x, includeBatchInIndex, convInfo, backend) {
      var program = new Pool2DProgram(convInfo, "max", false);
      var poolOutput = backend.runWebGLProgram(program, [x], "float32");
      program = new Pool2DProgram(convInfo, "max", true, true, includeBatchInIndex);
      var indexOutput = backend.runWebGLProgram(program, [x], "float32");
      return [poolOutput, indexOutput];
    }
    var maxPoolWithArgmaxConfig = {
      kernelName: tf.MaxPoolWithArgmax,
      backendName: "webgl",
      kernelFunc: function(_a2) {
        var inputs = _a2.inputs, attrs = _a2.attrs, backend = _a2.backend;
        var x = inputs.x;
        var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, includeBatchInIndex = attrs.includeBatchInIndex;
        var webglBackend = backend;
        tf.util.assert(x.shape.length === 4, function() {
          return "Error in maxPool: input must be rank 4 but got rank ".concat(x.shape.length, ".");
        });
        var dilations = [1, 1];
        tf.util.assert(tf.backend_util.eitherStridesOrDilationsAreOne(strides, dilations), function() {
          return "Error in maxPool: Either strides or dilations must be 1. " + "Got strides ".concat(strides, " and dilations '").concat(dilations, "'");
        });
        var convInfo = tf.backend_util.computePool2DInfo(x.shape, filterSize, strides, dilations, pad);
        var _b = __read(maxPoolWithArgmaxImpl(x, includeBatchInIndex, convInfo, webglBackend), 2), result = _b[0], indexes = _b[1];
        return [result, indexes];
      }
    };
    function meanImpl(x, reduceShape, outShape, backend) {
      var inSize = tf.util.sizeFromShape(reduceShape);
      var xSize = tf.util.sizeFromShape(x.shape);
      var batchSize = xSize / inSize;
      var reshapedInput = reshape({ inputs: { x }, attrs: { shape: [batchSize, inSize] }, backend });
      var reduced = reduce(reshapedInput, "float32", "mean", backend);
      var reshapedOutput = reshape({ inputs: { x: reduced }, attrs: { shape: outShape }, backend });
      backend.disposeIntermediateTensorInfo(reshapedInput);
      backend.disposeIntermediateTensorInfo(reduced);
      return reshapedOutput;
    }
    var meanConfig = {
      kernelName: tf.Mean,
      backendName: "webgl",
      kernelFunc: function(_a2) {
        var e_12, _b;
        var inputs = _a2.inputs, attrs = _a2.attrs, backend = _a2.backend;
        var x = inputs.x;
        var keepDims = attrs.keepDims, axis = attrs.axis;
        var webglBackend = backend;
        var xRank = x.shape.length;
        var origAxes = tf.util.parseAxisParam(axis, x.shape);
        var axes = origAxes;
        var permutedAxes = tf.backend_util.getAxesPermutation(axes, xRank);
        var meanInputIsTransposed = permutedAxes != null;
        var shouldExecuteOnCPU = webglBackend.shouldExecuteOnCPU([x]);
        var intermediates = [];
        var meanInput = x;
        if (meanInputIsTransposed) {
          if (shouldExecuteOnCPU) {
            var xTexData = webglBackend.texData.get(meanInput.dataId);
            var values = xTexData.values;
            var newShape = new Array(xRank);
            for (var i = 0; i < newShape.length; i++) {
              newShape[i] = x.shape[permutedAxes[i]];
            }
            var meanInputValues = transposeImplCPU(values, x.shape, x.dtype, permutedAxes, newShape);
            meanInput = webglBackend.makeTensorInfo(newShape, x.dtype);
            var meanInputData = webglBackend.texData.get(meanInput.dataId);
            meanInputData.values = meanInputValues;
          } else {
            meanInput = transposeImpl(x, permutedAxes, webglBackend);
          }
          intermediates.push(meanInput);
          axes = tf.backend_util.getInnerMostAxes(axes.length, xRank);
        }
        tf.backend_util.assertAxesAreInnerMostDims("sum", axes, xRank);
        var _c = __read(tf.backend_util.computeOutAndReduceShapes(meanInput.shape, axes), 2), meanOutShape = _c[0], reduceShape = _c[1];
        var outShape = meanOutShape;
        if (keepDims) {
          outShape = tf.backend_util.expandShapeToKeepDim(meanOutShape, origAxes);
        }
        var out = meanImpl(meanInput, reduceShape, outShape, webglBackend);
        try {
          for (var intermediates_1 = __values(intermediates), intermediates_1_1 = intermediates_1.next(); !intermediates_1_1.done; intermediates_1_1 = intermediates_1.next()) {
            var i = intermediates_1_1.value;
            webglBackend.disposeIntermediateTensorInfo(i);
          }
        } catch (e_1_1) {
          e_12 = { error: e_1_1 };
        } finally {
          try {
            if (intermediates_1_1 && !intermediates_1_1.done && (_b = intermediates_1.return)) _b.call(intermediates_1);
          } finally {
            if (e_12) throw e_12.error;
          }
        }
        return out;
      }
    };
    function min(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis, keepDims = attrs.keepDims;
      var xRank = x.shape.length;
      var origAxes = tf.util.parseAxisParam(axis, x.shape);
      var axes = origAxes;
      var permutedAxes = tf.backend_util.getAxesPermutation(axes, xRank);
      var permutedX = x;
      if (permutedAxes != null) {
        permutedX = transpose({ inputs: { x }, backend, attrs: { perm: permutedAxes } });
        axes = tf.backend_util.getInnerMostAxes(axes.length, x.shape.length);
      }
      tf.backend_util.assertAxesAreInnerMostDims("min", axes, xRank);
      var _a2 = __read(tf.backend_util.computeOutAndReduceShapes(permutedX.shape, axes), 2), outShape = _a2[0], reduceShape = _a2[1];
      var inSize = tf.util.sizeFromShape(reduceShape);
      var a2D = reshape({ inputs: { x: permutedX }, backend, attrs: { shape: [-1, inSize] } });
      var reduced = reduce(a2D, a2D.dtype, "min", backend);
      var res;
      if (keepDims) {
        var newShape = tf.backend_util.expandShapeToKeepDim(outShape, origAxes);
        res = reshape({ inputs: { x: reduced }, backend, attrs: { shape: newShape } });
      } else {
        res = reshape({ inputs: { x: reduced }, backend, attrs: { shape: outShape } });
      }
      backend.disposeIntermediateTensorInfo(a2D);
      backend.disposeIntermediateTensorInfo(reduced);
      if (permutedAxes != null) {
        backend.disposeIntermediateTensorInfo(permutedX);
      }
      return res;
    }
    var minConfig = {
      kernelName: tf.Min,
      backendName: "webgl",
      kernelFunc: min
    };
    var MINIMUM = CHECK_NAN_SNIPPET + "\n  return min(a, b);\n";
    var MINIMUM_PACKED = "\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  " + CHECK_NAN_SNIPPET_PACKED + "\n  return result;\n";
    var minimum = binaryKernelFunc({
      opSnippet: MINIMUM,
      packedOpSnippet: MINIMUM_PACKED,
      cpuKernelImpl: minimumImplCPU
    });
    var minimumConfig = {
      kernelName: tf.Minimum,
      backendName: "webgl",
      kernelFunc: minimum
    };
    var MirrorPadProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function MirrorPadProgram2(xShape, paddings, mode) {
          this.variableNames = ["x"];
          this.outputShape = paddings.map(
            function(p, i) {
              return p[0] + xShape[i] + p[1];
            }
            /* afterPad */
          );
          var rank = xShape.length;
          var dtype = getCoordsDataType(rank);
          var start = paddings.map(function(p) {
            return p[0];
          }).join(",");
          var end = paddings.map(function(p, i) {
            return p[0] + xShape[i];
          }).join(",");
          var unpackedCoords = ["coords[0]", "coords[1]", "coords[2]", "coords[3]"].slice(0, rank);
          var offset = mode === "reflect" ? 0 : 1;
          if (rank === 1) {
            this.userCode = "\n        int start = ".concat(start, ";\n        int end = ").concat(end, ";\n\n        void main() {\n          int outC = getOutputCoords();\n          if (outC < start) {\n            outC = start * 2 - outC - ").concat(offset, ";\n          } else if(outC >= end) {\n            outC = (end - 1) * 2 - outC + ").concat(offset, ";\n          }\n          setOutput(getX(outC - start));\n        }\n      ");
            return;
          }
          this.userCode = "\n      ".concat(dtype, " start = ").concat(dtype, "(").concat(start, ");\n      ").concat(dtype, " end = ").concat(dtype, "(").concat(end, ");\n\n      void main() {\n        ").concat(dtype, " outC = getOutputCoords();\n        for (int i = 0; i < ").concat(rank, "; i++) {\n          if (outC[i] < start[i]) {\n            outC[i] = start[i] * 2 - outC[i] - ").concat(offset, ";\n          } else if(outC[i] >= end[i]) {\n            outC[i] = (end[i] - 1) * 2 - outC[i] + ").concat(offset, ";\n          }\n        }\n        ").concat(dtype, " coords = outC - start;\n        setOutput(getX(").concat(unpackedCoords, "));\n      }\n    ");
        }
        return MirrorPadProgram2;
      }()
    );
    var MirrorPadPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function MirrorPadPackedProgram2(xShape, paddings, mode) {
          this.variableNames = ["x"];
          this.packedInputs = true;
          this.packedOutput = true;
          this.outputShape = paddings.map(
            function(p, i) {
              return p[0] + xShape[i] + p[1];
            }
            /* afterPad */
          );
          var rank = xShape.length;
          var dtype = getCoordsDataType(rank);
          var start = paddings.map(function(p) {
            return p[0];
          }).join(",");
          var end = paddings.map(function(p, i) {
            return p[0] + xShape[i];
          }).join(",");
          var coords2 = getChannels("rc", rank);
          var source = getChannels("source", rank);
          var cLimit = "".concat(coords2[rank - 1], " < ").concat(this.outputShape[rank - 1]);
          var innerDims = rank === 1 ? "source" : "vec2(".concat(source.slice(-2).join(), ")");
          var offset = mode === "reflect" ? 0 : 1;
          var mainLoop = "";
          if (rank === 1) {
            var padSetup = "\n        ".concat(dtype, " source = rc;\n        if (source < start) {\n          source = start * 2 - source - ").concat(offset, ";\n        } else if (source >= end) {\n          source = (end - 1) * 2 - source + ").concat(offset, ";\n        }\n        source -= start;\n      ");
            mainLoop = "\n        ".concat(dtype, " rc = outputLoc;\n        ").concat(padSetup, "\n        result[0] = getChannel(getX(").concat(source.join(), "), ").concat(innerDims, ");\n        ").concat(coords2[rank - 1], " += 1;\n        if(").concat(cLimit, ") {\n          ").concat(padSetup, "\n          result[1] = getChannel(getX(").concat(source.join(), "), ").concat(innerDims, ");\n        }\n      ");
          } else {
            var padSetup = "\n        ".concat(dtype, " source = rc;\n        ").concat(dtype, " lt = ").concat(dtype, "(lessThan(source, start));\n        ").concat(dtype, " gte = ").concat(dtype, "(greaterThanEqual(source, end));\n        ").concat(dtype, " orig = 1 - (lt + gte);\n        source = orig * source +\n                lt * (start * 2 - source - ").concat(offset, ") +\n                gte * ((end - 1) * 2 - source + ").concat(offset, ");\n        source -= start;\n      ");
            mainLoop = "\n        ".concat(dtype, " rc = outputLoc;\n        ").concat(padSetup, "\n        result[0] = getChannel(getX(").concat(source.join(), "), ").concat(innerDims, ");\n        ").concat(coords2[rank - 1], " += 1;\n        if(").concat(cLimit, ") {\n          ").concat(padSetup, "\n          result[1] = getChannel(getX(").concat(source.join(), "), ").concat(innerDims, ");\n        }\n        rc = outputLoc;\n        ").concat(coords2[rank - 2], " += 1;\n        if(").concat(coords2[rank - 2], " < ").concat(this.outputShape[rank - 2], ") {\n          ").concat(padSetup, "\n          result[2] = getChannel(getX(").concat(source.join(), "), ").concat(innerDims, ");\n          ").concat(coords2[rank - 1], " += 1;\n          if(").concat(cLimit, ") {\n            ").concat(padSetup, "\n            result[3] = getChannel(getX(").concat(source.join(), "), ").concat(innerDims, ");\n          }\n        }\n      ");
          }
          this.userCode = "\n      const ".concat(dtype, " start = ").concat(dtype, "(").concat(start, ");\n      const ").concat(dtype, " end = ").concat(dtype, "(").concat(end, ");\n\n      void main() {\n        ").concat(dtype, " outputLoc = getOutputCoords();\n        vec4 result = vec4(0.);\n        ").concat(mainLoop, "\n        setOutput(result);\n      }\n    ");
        }
        return MirrorPadPackedProgram2;
      }()
    );
    var mirrorPadKernelFunc = function(_a2) {
      var inputs = _a2.inputs, backend = _a2.backend, attrs = _a2.attrs;
      var x = inputs.x;
      var paddings = attrs.paddings, mode = attrs.mode;
      var program = tf.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new MirrorPadPackedProgram(x.shape, paddings, mode) : new MirrorPadProgram(x.shape, paddings, mode);
      var output = backend.runWebGLProgram(program, [x], x.dtype);
      return output;
    };
    var mirrorPadConfig = {
      kernelName: tf.MirrorPad,
      backendName: "webgl",
      kernelFunc: mirrorPadKernelFunc
    };
    var MOD = "if (b == 0.0) return NAN;\n  return mod(a, b);";
    var MOD_PACKED = "\n  vec4 result = mod(a, b);\n  bvec4 isNaN = equal(b, vec4(0.0));\n  " + CHECK_NAN_SNIPPET_PACKED + "\n  return result;\n";
    var mod = binaryKernelFunc({
      opSnippet: MOD,
      packedOpSnippet: MOD_PACKED
    });
    var modConfig = {
      kernelName: tf.Mod,
      backendName: "webgl",
      kernelFunc: mod
    };
    var MultinomialProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function MultinomialProgram2(batchSize, numOutcomes, numSamples) {
          this.variableNames = ["probs"];
          this.customUniforms = [{ name: "seed", type: "float" }];
          this.outputShape = [batchSize, numSamples];
          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 < ".concat(numOutcomes - 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(").concat(numOutcomes - 1, "));\n      }\n    ");
        }
        return MultinomialProgram2;
      }()
    );
    var DIV = "\nif (a == b) {\n  return 1.0;\n};\nreturn a / b;";
    var DIV_PACKED = "\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";
    var realDiv = binaryKernelFunc({ opSnippet: DIV, packedOpSnippet: DIV_PACKED, checkOutOfBounds: true });
    var realDivConfig = {
      kernelName: tf.RealDiv,
      backendName: "webgl",
      kernelFunc: realDiv
    };
    var SUB = "return a - b;";
    var sub = binaryKernelFunc({
      opSnippet: SUB,
      packedOpSnippet: SUB,
      supportsComplex: true,
      cpuKernelImpl: subImplCPU
    });
    var subConfig = {
      kernelName: tf.Sub,
      backendName: "webgl",
      kernelFunc: sub
    };
    function softmax(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var logits = inputs.logits;
      var dim = attrs.dim;
      var axes = tf.util.parseAxisParam([dim], logits.shape);
      var maxLogit = max({
        inputs: { x: logits },
        backend,
        attrs: { reductionIndices: axes, keepDims: false }
      });
      var expandedShape = tf.backend_util.expandShapeToKeepDim(maxLogit.shape, axes);
      var maxLogitsReshaped = reshape({ inputs: { x: maxLogit }, backend, attrs: { shape: expandedShape } });
      var a = sub({ inputs: { a: logits, b: maxLogitsReshaped }, backend });
      var b = exp({ inputs: { x: a }, backend });
      var sumExp = sum({ inputs: { x: b }, backend, attrs: { axis: axes, keepDims: false } });
      var sumExpReshaped = reshape({ inputs: { x: sumExp }, backend, attrs: { shape: expandedShape } });
      var res = realDiv({ inputs: { a: b, b: sumExpReshaped }, backend });
      backend.disposeIntermediateTensorInfo(maxLogit);
      backend.disposeIntermediateTensorInfo(maxLogitsReshaped);
      backend.disposeIntermediateTensorInfo(a);
      backend.disposeIntermediateTensorInfo(b);
      backend.disposeIntermediateTensorInfo(sumExp);
      backend.disposeIntermediateTensorInfo(sumExpReshaped);
      return res;
    }
    var softmaxConfig = {
      kernelName: tf.Softmax,
      backendName: "webgl",
      kernelFunc: softmax
    };
    function multinomial(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var logits = inputs.logits;
      var numSamples = attrs.numSamples, seed = attrs.seed, normalized = attrs.normalized;
      var probs = normalized ? logits : softmax({ inputs: { logits }, backend, attrs: { dim: logits.shape.length - 1 } });
      var batchSize = probs.shape[0];
      var numOutcomes = probs.shape[1];
      var program = new MultinomialProgram(batchSize, numOutcomes, numSamples);
      var customValues = [[seed]];
      var res = backend.runWebGLProgram(program, [probs], "int32", customValues);
      if (!normalized) {
        backend.disposeIntermediateTensorInfo(probs);
      }
      return res;
    }
    var multinomialConfig = {
      kernelName: tf.Multinomial,
      backendName: "webgl",
      kernelFunc: multinomial
    };
    var NEG = CHECK_NAN_SNIPPET$1 + "\n  return -x;\n";
    var NEG_PACKED = "\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";
    function neg(args) {
      var inputs = args.inputs, backend = args.backend;
      var x = inputs.x;
      if (backend.shouldExecuteOnCPU([x])) {
        var xData = backend.texData.get(x.dataId);
        var _a2 = __read(negImplCPU(xData.values, x.shape, x.dtype), 2), outValues = _a2[0], newShape = _a2[1];
        return backend.makeTensorInfo(newShape, x.dtype, outValues);
      }
      var program;
      if (tf.env().getBool("WEBGL_PACK_UNARY_OPERATIONS")) {
        program = new UnaryOpPackedProgram(x.shape, NEG_PACKED);
      } else {
        program = new UnaryOpProgram(x.shape, NEG);
      }
      return backend.runWebGLProgram(program, [x], x.dtype);
    }
    var negConfig = {
      kernelName: tf.Neg,
      backendName: "webgl",
      kernelFunc: neg
    };
    var nonMaxSuppressionV3Impl = tf.kernel_impls.nonMaxSuppressionV3Impl;
    function nonMaxSuppressionV3(args) {
      tf.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var boxes = inputs.boxes, scores = inputs.scores;
      var maxOutputSize = attrs.maxOutputSize, iouThreshold = attrs.iouThreshold, scoreThreshold = attrs.scoreThreshold;
      var boxesVals = backend.readSync(boxes.dataId);
      var scoresVals = backend.readSync(scores.dataId);
      var selectedIndices = nonMaxSuppressionV3Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold).selectedIndices;
      return backend.makeTensorInfo([selectedIndices.length], "int32", new Int32Array(selectedIndices));
    }
    var nonMaxSuppressionV3Config = {
      kernelName: tf.NonMaxSuppressionV3,
      backendName: "webgl",
      kernelFunc: nonMaxSuppressionV3
    };
    var nonMaxSuppressionV4Impl = tf.kernel_impls.nonMaxSuppressionV4Impl;
    function nonMaxSuppressionV4(args) {
      tf.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var boxes = inputs.boxes, scores = inputs.scores;
      var maxOutputSize = attrs.maxOutputSize, iouThreshold = attrs.iouThreshold, scoreThreshold = attrs.scoreThreshold, padToMaxOutputSize = attrs.padToMaxOutputSize;
      var boxesVals = backend.readSync(boxes.dataId);
      var scoresVals = backend.readSync(scores.dataId);
      var _a2 = nonMaxSuppressionV4Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize), selectedIndices = _a2.selectedIndices, validOutputs = _a2.validOutputs;
      return [
        backend.makeTensorInfo([selectedIndices.length], "int32", new Int32Array(selectedIndices)),
        backend.makeTensorInfo([], "int32", new Int32Array([validOutputs]))
      ];
    }
    var nonMaxSuppressionV4Config = {
      kernelName: tf.NonMaxSuppressionV4,
      backendName: "webgl",
      kernelFunc: nonMaxSuppressionV4
    };
    var nonMaxSuppressionV5Impl = tf.kernel_impls.nonMaxSuppressionV5Impl;
    function nonMaxSuppressionV5(args) {
      tf.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var boxes = inputs.boxes, scores = inputs.scores;
      var maxOutputSize = attrs.maxOutputSize, iouThreshold = attrs.iouThreshold, scoreThreshold = attrs.scoreThreshold, softNmsSigma = attrs.softNmsSigma;
      var boxesVals = backend.readSync(boxes.dataId);
      var scoresVals = backend.readSync(scores.dataId);
      var maxOutputSizeVal = maxOutputSize;
      var iouThresholdVal = iouThreshold;
      var scoreThresholdVal = scoreThreshold;
      var softNmsSigmaVal = softNmsSigma;
      var _a2 = nonMaxSuppressionV5Impl(boxesVals, scoresVals, maxOutputSizeVal, iouThresholdVal, scoreThresholdVal, softNmsSigmaVal), selectedIndices = _a2.selectedIndices, selectedScores = _a2.selectedScores;
      return [
        backend.makeTensorInfo([selectedIndices.length], "int32", new Int32Array(selectedIndices)),
        backend.makeTensorInfo([selectedScores.length], "float32", new Float32Array(selectedScores))
      ];
    }
    var nonMaxSuppressionV5Config = {
      kernelName: tf.NonMaxSuppressionV5,
      backendName: "webgl",
      kernelFunc: nonMaxSuppressionV5
    };
    var OneHotProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function OneHotProgram2(numIndices, depth, onValue, offValue) {
          this.variableNames = ["indices"];
          this.outputShape = [numIndices, depth];
          this.userCode = "\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int index = round(getIndices(coords.x));\n        setOutput(mix(float(".concat(offValue, "), float(").concat(onValue, "),\n                      float(index == coords.y)));\n      }\n    ");
        }
        return OneHotProgram2;
      }()
    );
    var oneHot = function(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var indices = inputs.indices;
      var dtype = attrs.dtype, depth = attrs.depth, onValue = attrs.onValue, offValue = attrs.offValue;
      var indicesSize = tf.util.sizeFromShape(indices.shape);
      var program = new OneHotProgram(indicesSize, depth, onValue, offValue);
      var reshaped = reshape({ inputs: { x: indices }, backend, attrs: { shape: [indicesSize] } });
      var result = backend.runWebGLProgram(program, [reshaped], dtype);
      backend.disposeIntermediateTensorInfo(reshaped);
      var outShape = __spreadArray(__spreadArray([], __read(indices.shape), false), [depth], false);
      var out = reshape({ inputs: { x: result }, backend, attrs: { shape: outShape } });
      backend.disposeIntermediateTensorInfo(result);
      return out;
    };
    var oneHotConfig = {
      kernelName: tf.OneHot,
      backendName: "webgl",
      kernelFunc: oneHot
    };
    function zerosLike(args) {
      var inputs = args.inputs, backend = args.backend;
      var x = inputs.x;
      if (x.dtype === "complex64") {
        var realPart = real({ inputs: { input: x }, backend });
        var r = zerosLike({ inputs: { x: realPart }, backend });
        var imagPart = imag({ inputs: { input: x }, backend });
        var i = zerosLike({ inputs: { x: imagPart }, backend });
        var result = complex({ inputs: { real: r, imag: i }, backend });
        backend.disposeIntermediateTensorInfo(realPart);
        backend.disposeIntermediateTensorInfo(r);
        backend.disposeIntermediateTensorInfo(imagPart);
        backend.disposeIntermediateTensorInfo(i);
        return result;
      } else {
        return fill({
          attrs: {
            shape: x.shape,
            dtype: x.dtype,
            value: x.dtype === "string" ? "" : 0
          },
          backend
        });
      }
    }
    var zerosLikeConfig = {
      kernelName: tf.ZerosLike,
      backendName: "webgl",
      kernelFunc: zerosLike
    };
    function onesLike(args) {
      var inputs = args.inputs, backend = args.backend;
      var x = inputs.x;
      if (x.dtype === "string") {
        throw new Error("onesLike is not supported under string dtype");
      } else if (x.dtype === "complex64") {
        var realPart = real({ inputs: { input: x }, backend });
        var r = onesLike({ inputs: { x: realPart }, backend });
        var imagPart = imag({ inputs: { input: x }, backend });
        var i = zerosLike({ inputs: { x: imagPart }, backend });
        var result = complex({ inputs: { real: r, imag: i }, backend });
        backend.disposeIntermediateTensorInfo(realPart);
        backend.disposeIntermediateTensorInfo(r);
        backend.disposeIntermediateTensorInfo(imagPart);
        backend.disposeIntermediateTensorInfo(i);
        return result;
      } else {
        return fill({ attrs: { shape: x.shape, dtype: x.dtype, value: 1 }, backend });
      }
    }
    var onesLikeConfig = {
      kernelName: tf.OnesLike,
      backendName: "webgl",
      kernelFunc: onesLike
    };
    function pack(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var axis = attrs.axis;
      if (inputs.length === 1) {
        return expandDims({ inputs: { input: inputs[0] }, backend, attrs: { dim: axis } });
      }
      var shape = inputs[0].shape;
      var dtype = inputs[0].dtype;
      inputs.forEach(function(t) {
        tf.util.assertShapesMatch(shape, t.shape, "All tensors passed to stack must have matching shapes");
        tf.util.assert(dtype === t.dtype, function() {
          return "All tensors passed to stack must have matching dtypes";
        });
      });
      var intermediateTensorInfos = [];
      var expandedTensors = inputs.map(function(t) {
        var expandedT = expandDims({ inputs: { input: t }, backend, attrs: { dim: axis } });
        intermediateTensorInfos.push(expandedT);
        return expandedT;
      });
      var result = concat({ inputs: expandedTensors, backend, attrs: { axis } });
      intermediateTensorInfos.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return result;
    }
    var packConfig = {
      kernelName: tf.Pack,
      backendName: "webgl",
      kernelFunc: pack
    };
    var PadProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function PadProgram2(xShape, paddings, constantValue) {
          this.variableNames = ["x"];
          this.customUniforms = [{ name: "value", type: "float" }];
          this.outputShape = paddings.map(
            function(p, i) {
              return p[0] + xShape[i] + p[1];
            }
            /* afterPad */
          );
          var rank = xShape.length;
          var type = getCoordsDataType(rank);
          var start = paddings.map(function(p) {
            return p[0];
          }).join(",");
          var end = paddings.map(function(p, i) {
            return p[0] + xShape[i];
          }).join(",");
          var unpackedCoords = ["coords[0]", "coords[1]", "coords[2]", "coords[3]"].slice(0, rank);
          if (rank === 1) {
            this.userCode = "\n        int start = ".concat(start, ";\n        int end = ").concat(end, ";\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      ");
            return;
          }
          this.userCode = "\n      ".concat(type, " start = ").concat(type, "(").concat(start, ");\n      ").concat(type, " end = ").concat(type, "(").concat(end, ");\n\n      void main() {\n        ").concat(type, " outC = getOutputCoords();\n        if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n          setOutput(value);\n        } else {\n          ").concat(type, " coords = outC - start;\n          setOutput(getX(").concat(unpackedCoords, "));\n        }\n      }\n    ");
        }
        return PadProgram2;
      }()
    );
    var PadPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function PadPackedProgram2(xShape, paddings, constantValue) {
          this.variableNames = ["x"];
          this.packedInputs = true;
          this.packedOutput = true;
          this.customUniforms = [{ name: "value", type: "float" }];
          this.outputShape = paddings.map(
            function(p, i2) {
              return p[0] + xShape[i2] + p[1];
            }
            /* afterPad */
          );
          var rank = xShape.length;
          var dtype = getCoordsDataType(rank);
          var start = paddings.map(function(p) {
            return p[0];
          }).join(",");
          var end = paddings.map(function(p, i2) {
            return p[0] + xShape[i2];
          }).join(",");
          var coords2 = getChannels("rc", rank);
          var source = getChannels("source", rank);
          var cLimit = "".concat(coords2[rank - 1], " < ").concat(this.outputShape[rank - 1]);
          var innerDims = rank === 1 ? "source" : "vec2(".concat(source.slice(-2).join(), ")");
          var componentSetup = [
            "".concat(dtype, " rc = outputLoc;"),
            "".concat(coords2[rank - 1], " += 1;\n       if(").concat(cLimit, ") {\n      "),
            rank === 1 ? "" : "}\n       rc = outputLoc;\n       ".concat(coords2[rank - 2], " += 1;\n       if(").concat(coords2[rank - 2], " < ").concat(this.outputShape[rank - 2], ") {"),
            rank === 1 ? "" : "  ".concat(coords2[rank - 1], " += 1;\n         if(").concat(cLimit, ") {")
          ];
          var paddingArea = rank === 1 ? "rc < start || rc >= end" : "any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";
          var mainLoop = "";
          for (var i = 0, j = rank === 1 ? 2 : 4; i < j; i++) {
            mainLoop += "\n        ".concat(componentSetup[i], "\n        if (").concat(paddingArea, ") {\n          result[").concat(i, "] = float(value);\n        } else {\n          ").concat(dtype, " source = rc - start;\n          result[").concat(i, "] = getChannel(getX(").concat(source.join(), "), ").concat(innerDims, ");\n        }\n      ");
          }
          mainLoop += rank === 1 ? "} " : "}}";
          this.userCode = "\n      const ".concat(dtype, " start = ").concat(dtype, "(").concat(start, ");\n      const ").concat(dtype, " end = ").concat(dtype, "(").concat(end, ");\n\n      void main() {\n        ").concat(dtype, " outputLoc = getOutputCoords();\n        vec4 result = vec4(0.);\n        ").concat(mainLoop, "\n        setOutput(result);\n      }\n    ");
        }
        return PadPackedProgram2;
      }()
    );
    var padV2 = function(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var paddings = attrs.paddings, constantValue = attrs.constantValue;
      if (tf.util.sizeFromShape(x.shape) === 0) {
        var outputShape = paddings.map(
          function(p, i) {
            return p[0] + x.shape[i] + p[1];
          }
          /* afterPad */
        );
        return fill({
          backend,
          attrs: { shape: outputShape, value: constantValue, dtype: x.dtype }
        });
      }
      var program = tf.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new PadPackedProgram(x.shape, paddings, constantValue) : new PadProgram(x.shape, paddings, constantValue);
      var customValues = [[constantValue]];
      return backend.runWebGLProgram(program, [x], x.dtype, customValues);
    };
    var padV2Config = {
      kernelName: tf.PadV2,
      backendName: "webgl",
      kernelFunc: padV2
    };
    var POW = "\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";
    var POW_PACKED = "\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  " + CHECK_NAN_SNIPPET_PACKED + "\n  return result;\n";
    var pow = binaryKernelFunc({ opSnippet: POW, packedOpSnippet: POW_PACKED });
    var powConfig = {
      kernelName: tf.Pow,
      backendName: "webgl",
      kernelFunc: pow
    };
    function prod(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var axis = attrs.axis, keepDims = attrs.keepDims;
      var xRank = x.shape.length;
      var toDispose = [];
      var origAxes = tf.util.parseAxisParam(axis, x.shape);
      var axes = origAxes;
      var permutedAxes = tf.backend_util.getAxesPermutation(axes, xRank);
      var permutedX = x;
      if (permutedAxes != null) {
        permutedX = transpose({ inputs: { x }, backend, attrs: { perm: permutedAxes } });
        axes = tf.backend_util.getInnerMostAxes(axes.length, xRank);
        toDispose.push(permutedX);
      }
      tf.backend_util.assertAxesAreInnerMostDims("prod", axes, xRank);
      var res;
      if (backend.shouldExecuteOnCPU([permutedX])) {
        var xVals = backend.texData.get(permutedX.dataId).values;
        var _a2 = prodImplCPU(permutedX.shape, permutedX.dtype, xVals, axes), outVals = _a2.outVals, outShape = _a2.outShape, outDtype = _a2.outDtype;
        res = backend.makeTensorInfo(outShape, outDtype, outVals);
      } else {
        var _b = __read(tf.backend_util.computeOutAndReduceShapes(permutedX.shape, axes), 2), outShape = _b[0], reduceShape = _b[1];
        var inSize = tf.util.sizeFromShape(reduceShape);
        var a2D = reshape({ inputs: { x: permutedX }, backend, attrs: { shape: [-1, inSize] } });
        var outputDType = tf.sumOutType(x.dtype);
        var reduced = reduce(a2D, outputDType, "prod", backend);
        res = reshape({ inputs: { x: reduced }, backend, attrs: { shape: outShape } });
        toDispose.push(a2D);
        toDispose.push(reduced);
      }
      if (keepDims) {
        toDispose.push(res);
        var newShape = tf.backend_util.expandShapeToKeepDim(res.shape, origAxes);
        res = reshape({ inputs: { x: res }, backend, attrs: { shape: newShape } });
      }
      toDispose.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return res;
    }
    var prodConfig = {
      kernelName: tf.Prod,
      backendName: "webgl",
      kernelFunc: prod
    };
    function raggedGather(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var paramsNestedSplits = inputs.paramsNestedSplits, paramsDenseValues = inputs.paramsDenseValues, indices = inputs.indices;
      attrs.outputRaggedRank;
      var $paramsNestedSplits = paramsNestedSplits.map(function(t) {
        return backend.readSync(t.dataId);
      });
      var $paramsNestedSplitsShapes = paramsNestedSplits.map(function(t) {
        return t.shape;
      });
      var $paramsDenseValues = backend.readSync(paramsDenseValues.dataId);
      var $indices = backend.readSync(indices.dataId);
      var _a2 = __read(raggedGatherImplCPU($paramsNestedSplits, $paramsNestedSplitsShapes, $paramsDenseValues, paramsDenseValues.shape, paramsDenseValues.dtype, $indices, indices.shape), 3), outputNestedSplits = _a2[0], outputDenseValues = _a2[1], outputDenseValuesShape = _a2[2];
      var outputNestedSplitsTensors = outputNestedSplits.map(function(splits) {
        return backend.makeTensorInfo([splits.length], "int32", splits);
      });
      var outputDenseValuesTensor = backend.makeTensorInfo(outputDenseValuesShape, paramsDenseValues.dtype, outputDenseValues);
      return outputNestedSplitsTensors.concat([outputDenseValuesTensor]);
    }
    var raggedGatherConfig = {
      kernelName: tf.RaggedGather,
      backendName: "webgl",
      kernelFunc: raggedGather
    };
    function raggedRange(args) {
      var inputs = args.inputs, backend = args.backend;
      var starts = inputs.starts, limits = inputs.limits, deltas = inputs.deltas;
      var $starts = backend.readSync(starts.dataId);
      var $limits = backend.readSync(limits.dataId);
      var $deltas = backend.readSync(deltas.dataId);
      var _a2 = __read(raggedRangeImplCPU($starts, starts.shape, starts.dtype, $limits, limits.shape, $deltas, deltas.shape), 2), rtNestedSplitsData = _a2[0], rtDenseValuesData = _a2[1];
      var rtNestedSplits = backend.makeTensorInfo([rtNestedSplitsData.length], "int32", rtNestedSplitsData);
      var rtDenseValues = backend.makeTensorInfo([rtDenseValuesData.length], starts.dtype, rtDenseValuesData);
      return [rtNestedSplits, rtDenseValues];
    }
    var raggedRangeConfig = {
      kernelName: tf.RaggedRange,
      backendName: "webgl",
      kernelFunc: raggedRange
    };
    function raggedTensorToTensor(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var shape = inputs.shape, values = inputs.values, defaultValue = inputs.defaultValue, rowPartitionTensors = inputs.rowPartitionTensors;
      var rowPartitionTypes = attrs.rowPartitionTypes;
      var $shape = backend.readSync(shape.dataId);
      var $values = backend.readSync(values.dataId);
      var $defaultValue = backend.readSync(defaultValue.dataId);
      var $rowPartitionValues = rowPartitionTensors.map(function(t) {
        return backend.readSync(t.dataId);
      });
      var rowPartitionValuesShapes = rowPartitionTensors.map(function(t) {
        return t.shape;
      });
      var _a2 = __read(raggedTensorToTensorImplCPU($shape, shape.shape, $values, values.shape, values.dtype, $defaultValue, defaultValue.shape, $rowPartitionValues, rowPartitionValuesShapes, rowPartitionTypes), 2), outputShape = _a2[0], output = _a2[1];
      return backend.makeTensorInfo(outputShape, values.dtype, output);
    }
    var raggedTensorToTensorConfig = {
      kernelName: tf.RaggedTensorToTensor,
      backendName: "webgl",
      kernelFunc: raggedTensorToTensor
    };
    var range = function(args) {
      var backend = args.backend, attrs = args.attrs;
      var start = attrs.start, stop = attrs.stop, step2 = attrs.step, dtype = attrs.dtype;
      var values = rangeImplCPU(start, stop, step2, dtype);
      return backend.makeTensorInfo([values.length], dtype, values);
    };
    var rangeConfig = {
      kernelName: tf.Range,
      backendName: "webgl",
      kernelFunc: range
    };
    var RECIPROCAL = "return 1.0 / x;";
    var reciprocal = unaryKernelFunc({ opSnippet: RECIPROCAL });
    var reciprocalConfig = {
      kernelName: tf.Reciprocal,
      backendName: "webgl",
      kernelFunc: reciprocal
    };
    var RELU = CHECK_NAN_SNIPPET$1 + "\n  return (x < 0.0) ? 0.0 : x;\n";
    var RELU_PACKED = "\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";
    var relu = unaryKernelFunc({ opSnippet: RELU, packedOpSnippet: RELU_PACKED });
    var reluConfig = {
      kernelName: tf.Relu,
      backendName: "webgl",
      kernelFunc: relu
    };
    var RELU6 = CHECK_NAN_SNIPPET$1 + "\n  return (x < 0.0) ? 0.0 : min(6.0, x);\n";
    var RELU6_PACKED = "\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";
    var relu6 = unaryKernelFunc({ opSnippet: RELU6, packedOpSnippet: RELU6_PACKED });
    var relu6Config = {
      kernelName: tf.Relu6,
      backendName: "webgl",
      kernelFunc: relu6
    };
    var ResizeBilinearProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ResizeBilinearProgram2(inputShape, newHeight, newWidth, alignCorners, halfPixelCenters) {
          this.variableNames = ["A"];
          this.outputShape = [];
          var _a2 = __read(inputShape, 4), batch = _a2[0], oldHeight = _a2[1], oldWidth = _a2[2], depth = _a2[3];
          this.outputShape = [batch, newHeight, newWidth, depth];
          var effectiveInSize = [
            alignCorners && newHeight > 1 ? oldHeight - 1 : oldHeight,
            alignCorners && newWidth > 1 ? oldWidth - 1 : oldWidth
          ];
          var effectiveOutSize = [
            alignCorners && newHeight > 1 ? newHeight - 1 : newHeight,
            alignCorners && newWidth > 1 ? newWidth - 1 : newWidth
          ];
          var sourceFracIndexRC;
          if (halfPixelCenters) {
            sourceFracIndexRC = "(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)";
          } else {
            sourceFracIndexRC = "vec2(yRC) * effectiveInputOverOutputRatioRC";
          }
          this.userCode = "\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          ".concat(effectiveInSize[0] / effectiveOutSize[0], ",\n          ").concat(effectiveInSize[1] / effectiveOutSize[1], ");\n      const vec2 inputShapeRC = vec2(").concat(oldHeight, ".0, ").concat(oldWidth, ".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 = ").concat(sourceFracIndexRC, ";\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    ");
        }
        return ResizeBilinearProgram2;
      }()
    );
    var ResizeBilinearPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ResizeBilinearPackedProgram2(inputShape, newHeight, newWidth, alignCorners, halfPixelCenters) {
          this.variableNames = ["A"];
          this.packedInputs = true;
          this.packedOutput = true;
          this.outputShape = [];
          var _a2 = __read(inputShape, 4), batch = _a2[0], oldHeight = _a2[1], oldWidth = _a2[2], depth = _a2[3];
          this.outputShape = [batch, newHeight, newWidth, depth];
          var effectiveInSize = [
            alignCorners && newHeight > 1 ? oldHeight - 1 : oldHeight,
            alignCorners && newWidth > 1 ? oldWidth - 1 : oldWidth
          ];
          var effectiveOutSize = [
            alignCorners && newHeight > 1 ? newHeight - 1 : newHeight,
            alignCorners && newWidth > 1 ? newWidth - 1 : newWidth
          ];
          var sourceFracIndexRC;
          if (halfPixelCenters) {
            sourceFracIndexRC = "(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)";
          } else {
            sourceFracIndexRC = "vec3(yRC) * effectiveInputOverOutputRatioRC";
          }
          this.userCode = "\n      const vec3 effectiveInputOverOutputRatioRC = vec3(\n          ".concat(effectiveInSize[0] / effectiveOutSize[0], ",\n          ").concat(effectiveInSize[1] / effectiveOutSize[1], ",\n          ").concat(effectiveInSize[1] / effectiveOutSize[1], ");\n      const vec3 inputShapeRC = vec3(").concat(oldHeight, ".0, ").concat(oldWidth, ".0,\n                                     ").concat(oldWidth, ".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 = ").concat(sourceFracIndexRC, ";\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 < ").concat(depth - 1, ";\n        bool hasNextRow = coords.z < ").concat(newWidth - 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    ");
        }
        return ResizeBilinearPackedProgram2;
      }()
    );
    function resizeBilinear(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var images = inputs.images;
      var alignCorners = attrs.alignCorners, halfPixelCenters = attrs.halfPixelCenters, size = attrs.size;
      var _a2 = __read(size, 2), newHeight = _a2[0], newWidth = _a2[1];
      var program = tf.env().getBool("WEBGL_PACK_IMAGE_OPERATIONS") ? new ResizeBilinearPackedProgram(images.shape, newHeight, newWidth, alignCorners, halfPixelCenters) : new ResizeBilinearProgram(images.shape, newHeight, newWidth, alignCorners, halfPixelCenters);
      return backend.runWebGLProgram(program, [images], "float32");
    }
    var resizeBilinearConfig = {
      kernelName: tf.ResizeBilinear,
      backendName: "webgl",
      kernelFunc: resizeBilinear
    };
    var ResizeBilinearBackpropProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ResizeBilinearBackpropProgram2(dyShape, inputShape, alignCorners) {
          this.variableNames = ["dy"];
          this.outputShape = [];
          this.outputShape = inputShape;
          var _a2 = __read(inputShape, 3), xHeight = _a2[1], xWidth = _a2[2];
          var _b = __read(dyShape, 3), yHeight = _b[1], yWidth = _b[2];
          var effectiveXSize = [
            alignCorners && yHeight > 1 ? xHeight - 1 : xHeight,
            alignCorners && yWidth > 1 ? xWidth - 1 : xWidth
          ];
          var effectiveYSize = [
            alignCorners && yHeight > 1 ? yHeight - 1 : yHeight,
            alignCorners && yWidth > 1 ? yWidth - 1 : yWidth
          ];
          var heightScale = effectiveXSize[0] / effectiveYSize[0];
          var widthScale = effectiveXSize[1] / effectiveYSize[1];
          var invHeightScale = 1 / heightScale;
          var invWidthScale = 1 / widthScale;
          var winHeight = Math.ceil(invHeightScale) * 2 + 2;
          var winWidth = Math.ceil(invWidthScale) * 2 + 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(".concat(heightScale, ");\n        const float widthScale = float(").concat(widthScale, ");\n\n        const float invHeightScale = float(").concat(invHeightScale, ");\n        const float invWidthScale = float(").concat(invWidthScale, ");\n\n        const int winHeight = int(").concat(winHeight, ");\n        const int winWidth = int(").concat(winWidth, ");\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 >= ").concat(yHeight, ") {\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 >= ").concat(yWidth, ") {\n              continue;\n            }\n\n            float dxR = float(dyR) * heightScale;\n            int topDxRIndex = int(floor(dxR));\n            int bottomDxRIndex = int(min(ceil(dxR), ").concat(xHeight - 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), ").concat(xWidth - 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    ");
        }
        return ResizeBilinearBackpropProgram2;
      }()
    );
    function resizeBilinearGrad(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var images = inputs.images, dy = inputs.dy;
      var alignCorners = attrs.alignCorners;
      var program = new ResizeBilinearBackpropProgram(dy.shape, images.shape, alignCorners);
      return backend.runWebGLProgram(program, [dy], dy.dtype);
    }
    var resizeBilinearGradConfig = {
      kernelName: tf.ResizeBilinearGrad,
      backendName: "webgl",
      kernelFunc: resizeBilinearGrad
    };
    var ResizeNearestNeighborProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ResizeNearestNeighborProgram2(inputShape, newHeight, newWidth, alignCorners, halfPixelCenters) {
          this.variableNames = ["A"];
          this.outputShape = [];
          var _a2 = __read(inputShape, 4), batch = _a2[0], oldHeight = _a2[1], oldWidth = _a2[2], depth = _a2[3];
          this.outputShape = [batch, newHeight, newWidth, depth];
          var effectiveInSize = [
            alignCorners && newHeight > 1 ? oldHeight - 1 : oldHeight,
            alignCorners && newWidth > 1 ? oldWidth - 1 : oldWidth
          ];
          var effectiveOutSize = [
            alignCorners && newHeight > 1 ? newHeight - 1 : newHeight,
            alignCorners && newWidth > 1 ? newWidth - 1 : newWidth
          ];
          var roundBase = alignCorners ? "0.5" : "0.0";
          var sourceFracIndexRC;
          if (halfPixelCenters) {
            sourceFracIndexRC = "max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))";
          } else {
            sourceFracIndexRC = "vec2(yRC) * effectiveInputOverOutputRatioRC";
          }
          this.userCode = "\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          ".concat(effectiveInSize[0] / effectiveOutSize[0], ",\n          ").concat(effectiveInSize[1] / effectiveOutSize[1], ");\n      const vec2 inputShapeRC = vec2(").concat(oldHeight, ".0, ").concat(oldWidth, ".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 = ").concat(sourceFracIndexRC, ";\n\n        // Compute the coordinators of nearest neighbor point.\n        ivec2 sourceNearestRC = ivec2(\n          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ").concat(roundBase, ")));\n        float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n        setOutput(newValue);\n      }\n    ");
        }
        return ResizeNearestNeighborProgram2;
      }()
    );
    var ResizeNearestNeighborPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ResizeNearestNeighborPackedProgram2(inputShape, newHeight, newWidth, alignCorners, halfPixelCenters) {
          this.variableNames = ["A"];
          this.packedInputs = true;
          this.packedOutput = true;
          this.outputShape = [];
          var _a2 = __read(inputShape, 4), batch = _a2[0], oldHeight = _a2[1], oldWidth = _a2[2], depth = _a2[3];
          this.outputShape = [batch, newHeight, newWidth, depth];
          var effectiveInSize = [
            alignCorners && newHeight > 1 ? oldHeight - 1 : oldHeight,
            alignCorners && newWidth > 1 ? oldWidth - 1 : oldWidth
          ];
          var effectiveOutSize = [
            alignCorners && newHeight > 1 ? newHeight - 1 : newHeight,
            alignCorners && newWidth > 1 ? newWidth - 1 : newWidth
          ];
          var roundBase = alignCorners ? "0.5" : "0.0";
          var sourceFracIndexRC;
          if (halfPixelCenters) {
            sourceFracIndexRC = "max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))";
          } else {
            sourceFracIndexRC = "vec3(yRC) * effectiveInputOverOutputRatioRC";
          }
          this.userCode = "\n      const vec3 effectiveInputOverOutputRatioRC = vec3(\n          ".concat(effectiveInSize[0] / effectiveOutSize[0], ",\n          ").concat(effectiveInSize[1] / effectiveOutSize[1], ",\n          ").concat(effectiveInSize[1] / effectiveOutSize[1], ");\n      const vec3 inputShapeRC = vec3(").concat(oldHeight, ".0, ").concat(oldWidth, ".0,\n                                     ").concat(oldWidth, ".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 = ").concat(sourceFracIndexRC, ";\n\n        // Compute the coordinators of nearest neighbor point.\n        ivec3 sourceNearestRC = ivec3(\n          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ").concat(roundBase, ")));\n\n        // Should we calculate next column and row elements in 2x2 packed cell.\n        bool hasNextCol = d < ").concat(depth - 1, ";\n        bool hasNextRow = coords.z < ").concat(newWidth - 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    ");
        }
        return ResizeNearestNeighborPackedProgram2;
      }()
    );
    function resizeNearestNeighbor(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var images = inputs.images;
      var alignCorners = attrs.alignCorners, halfPixelCenters = attrs.halfPixelCenters, size = attrs.size;
      var _a2 = __read(size, 2), newHeight = _a2[0], newWidth = _a2[1];
      var program = tf.env().getBool("WEBGL_PACK_IMAGE_OPERATIONS") ? new ResizeNearestNeighborPackedProgram(images.shape, newHeight, newWidth, alignCorners, halfPixelCenters) : new ResizeNearestNeighborProgram(images.shape, newHeight, newWidth, alignCorners, halfPixelCenters);
      return backend.runWebGLProgram(program, [images], images.dtype);
    }
    var resizeNearestNeighborConfig = {
      kernelName: tf.ResizeNearestNeighbor,
      backendName: "webgl",
      kernelFunc: resizeNearestNeighbor
    };
    var ResizeNearestNeigborBackpropProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ResizeNearestNeigborBackpropProgram2(dyShape, inputShape, alignCorners) {
          this.variableNames = ["dy"];
          this.outputShape = [];
          this.outputShape = inputShape;
          var _a2 = __read(inputShape, 3), xHeight = _a2[1], xWidth = _a2[2];
          var _b = __read(dyShape, 3), yHeight = _b[1], yWidth = _b[2];
          var effectiveXSize = [
            alignCorners && yHeight > 1 ? xHeight - 1 : xHeight,
            alignCorners && yWidth > 1 ? xWidth - 1 : xWidth
          ];
          var effectiveYSize = [
            alignCorners && yHeight > 1 ? yHeight - 1 : yHeight,
            alignCorners && yWidth > 1 ? yWidth - 1 : yWidth
          ];
          var heightScale = effectiveXSize[0] / effectiveYSize[0];
          var widthScale = effectiveXSize[1] / effectiveYSize[1];
          var invHeightScale = 1 / heightScale;
          var invWidthScale = 1 / widthScale;
          var winHeight = Math.ceil(invHeightScale) * 2 + 2;
          var winWidth = Math.ceil(invWidthScale) * 2 + 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(".concat(heightScale, ");\n        const float widthScale = float(").concat(widthScale, ");\n\n        const float invHeightScale = float(").concat(invHeightScale, ");\n        const float invWidthScale = float(").concat(invWidthScale, ");\n\n        const int winHeight = int(").concat(winHeight, ");\n        const int winWidth = int(").concat(winWidth, ");\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 >= ").concat(yHeight, ") {\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 >= ").concat(yWidth, ") {\n              continue;\n            }\n\n            float sourceFracRow =\n              float(").concat(effectiveXSize[0], ") *\n                (float(dyR) / float(").concat(effectiveYSize[0], "));\n\n            float sourceFracCol =\n                float(").concat(effectiveXSize[1], ") *\n                  (float(dyC) / float(").concat(effectiveYSize[1], "));\n\n            int sourceNearestRow = int(min(\n                float(int(").concat(xHeight, ") - 1),\n                ").concat(alignCorners, " ? float(round(sourceFracRow)) :\n                                  float(floor(sourceFracRow))));\n\n            int sourceNearestCol = int(min(\n                float(int(").concat(xWidth, ") - 1),\n                ").concat(alignCorners, " ? 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    ");
        }
        return ResizeNearestNeigborBackpropProgram2;
      }()
    );
    function resizeNearestNeighborGrad(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var images = inputs.images, dy = inputs.dy;
      var alignCorners = attrs.alignCorners;
      var program = new ResizeNearestNeigborBackpropProgram(dy.shape, images.shape, alignCorners);
      return backend.runWebGLProgram(program, [dy], dy.dtype);
    }
    var resizeNearestNeighborGradConfig = {
      kernelName: tf.ResizeNearestNeighborGrad,
      backendName: "webgl",
      kernelFunc: resizeNearestNeighborGrad
    };
    var ReverseProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ReverseProgram2(xShape, axis) {
          this.variableNames = ["x"];
          var rank = xShape.length;
          if (rank > 4) {
            throw new Error("WebGL backend: Reverse of rank-".concat(rank, " tensor is not yet supported"));
          }
          this.outputShape = xShape;
          if (rank === 1) {
            this.userCode = "\n        void main() {\n          int coord = getOutputCoords();\n          setOutput(getX(".concat(xShape[0], " - coord - 1));\n        }\n      ");
            return;
          }
          var getInCoord = function(i) {
            if (axis.indexOf(i) !== -1 && xShape[i] !== 1) {
              return "".concat(xShape[i], " - coords[").concat(i, "] - 1");
            }
            return "coords[".concat(i, "]");
          };
          var inCoords = xShape.map(function(_, i) {
            return getInCoord(i);
          }).join(",");
          var type = getCoordsDataType(rank);
          this.userCode = "\n      void main() {\n        ".concat(type, " coords = getOutputCoords();\n        setOutput(getX(").concat(inCoords, "));\n      }\n    ");
        }
        return ReverseProgram2;
      }()
    );
    var ReversePackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ReversePackedProgram2(xShape, axis) {
          this.variableNames = ["x"];
          this.packedInputs = true;
          this.packedOutput = true;
          var rank = xShape.length;
          if (rank > 4) {
            throw new Error("WebGL backend: Reverse of rank-".concat(rank, " tensor is not yet supported"));
          }
          this.outputShape = xShape;
          var channels = getChannels("rc", rank);
          var nextColumn = "".concat(channels[rank - 1], " + 1 < ").concat(this.outputShape[rank - 1]);
          var nextRow = "".concat(channels[rank - 2], " + 1 < ").concat(this.outputShape[rank - 2]);
          var type = getCoordsDataType(rank);
          if (rank === 1) {
            this.userCode = "\n        void main(){\n          int rc = getOutputCoords();\n          vec4 result = vec4(0.);\n          result.r = getChannel(getX(".concat(xShape[0], " - rc - 1),\n            ").concat(xShape[0], " - rc - 1);\n          if(").concat(nextColumn, "){\n              result.g = getChannel(getX(").concat(xShape[0], " - (rc  + 1) - 1),\n                ").concat(xShape[0], " - (rc  + 1) - 1);\n          }\n          setOutput(result);\n        }\n      ");
          } else {
            this.userCode = "\n        void main() {\n          ".concat(type, " rc = getOutputCoords();\n          vec4 result = vec4(0.);\n          result.r = ").concat(getR(channels.slice()), ";\n          if(").concat(nextColumn, "){\n            result.g = ").concat(getG(channels.slice()), ";\n          }\n          if(").concat(nextRow, ") {\n            result.b = ").concat(getB(channels.slice()), ";\n            if(").concat(nextColumn, ") {\n              result.a = ").concat(getA(channels.slice()), ";\n            }\n          }\n          setOutput(result);\n        }\n    ");
          }
          function getR(channels2) {
            return getChannel(channels2);
          }
          function getG(channels2) {
            channels2[rank - 1] = "(" + channels2[rank - 1] + " + 1)";
            return getChannel(channels2);
          }
          function getB(channels2) {
            channels2[rank - 2] = "(" + channels2[rank - 2] + " + 1)";
            return getChannel(channels2);
          }
          function getA(channels2) {
            channels2[rank - 1] = "(" + channels2[rank - 1] + " + 1)";
            channels2[rank - 2] = "(" + channels2[rank - 2] + " + 1)";
            return getChannel(channels2);
          }
          function getChannel(channels2) {
            var inCoordsArray = xShape.map(function(_, i) {
              return getInCoord(i, channels2);
            });
            var inCoords = inCoordsArray.join(",");
            var innerDims = inCoordsArray.slice(-2).join(",");
            return "getChannel(getX(".concat(inCoords, "), vec2(").concat(innerDims, "))");
          }
          function getInCoord(i, channels1) {
            if (axis.indexOf(i) !== -1 && xShape[i] !== 1) {
              return "".concat(xShape[i], " - ").concat(channels1[i], " - 1");
            } else {
              return "".concat(channels1[i]);
            }
          }
        }
        return ReversePackedProgram2;
      }()
    );
    function reverse(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var dims = attrs.dims;
      var xRank = x.shape.length;
      var $dims = tf.util.parseAxisParam(dims, x.shape);
      if (xRank === 0) {
        return identity({ inputs: { x }, backend });
      }
      var program = tf.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new ReversePackedProgram(x.shape, $dims) : new ReverseProgram(x.shape, $dims);
      return backend.runWebGLProgram(program, [x], x.dtype);
    }
    var reverseConfig = {
      kernelName: tf.Reverse,
      backendName: "webgl",
      kernelFunc: reverse
    };
    var RotateProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function RotateProgram2(imageShape, fillValue) {
          this.variableNames = ["Image"];
          this.outputShape = [];
          this.customUniforms = [{ name: "params", type: "vec4" }];
          var imageHeight = imageShape[1];
          var imageWidth = imageShape[2];
          this.outputShape = imageShape;
          var fillSnippet = "";
          if (typeof fillValue === "number") {
            fillSnippet = "float outputValue = ".concat(fillValue.toFixed(2), ";");
          } else {
            fillSnippet = "\n        vec3 fill = vec3(".concat(fillValue.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          ".concat(fillSnippet, "\n          if(coordX >= 0 && coordX < ").concat(imageWidth, " && coordY >= 0 && coordY < ").concat(imageHeight, ") {\n            outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n          }\n          setOutput(outputValue);\n        }\n    ");
        }
        return RotateProgram2;
      }()
    );
    var rotateWithOffsetConfig = {
      kernelName: tf.RotateWithOffset,
      backendName: "webgl",
      kernelFunc: function(_a2) {
        var inputs = _a2.inputs, attrs = _a2.attrs, backend = _a2.backend;
        var image = inputs.image;
        var radians = attrs.radians, fillValue = attrs.fillValue, center = attrs.center;
        var webglBackend = backend;
        var program = new RotateProgram(image.shape, fillValue);
        var _b = __read(tf.backend_util.getImageCenter(center, image.shape[1], image.shape[2]), 2), centerX = _b[0], centerY = _b[1];
        var customValues = [[centerX, centerY, Math.sin(radians), Math.cos(radians)]];
        var output = webglBackend.runWebGLProgram(program, [image], image.dtype, customValues);
        return output;
      }
    };
    var ROUND = "\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";
    var round = unaryKernelFunc({ opSnippet: ROUND });
    var roundConfig = {
      kernelName: tf.Round,
      backendName: "webgl",
      kernelFunc: round
    };
    var RSQRT = "return inversesqrt(x);";
    var rsqrt = unaryKernelFunc({ opSnippet: RSQRT, cpuKernelImpl: rsqrtImplCPU });
    var rsqrtConfig = {
      kernelName: tf.Rsqrt,
      backendName: "webgl",
      kernelFunc: rsqrt
    };
    var ScatterProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ScatterProgram2(updateSize, sliceDim, indicesRank, updatesRank, strides, shape, summingDupeIndex, defaultIsTensor) {
          if (defaultIsTensor === void 0) {
            defaultIsTensor = false;
          }
          this.variableNames = ["updates", "indices", "defaultValue"];
          this.outputShape = shape;
          var stridesType = getCoordsDataType(strides.length);
          var dtype = getCoordsDataType(shape.length);
          var indicesString = "";
          if (indicesRank === 1) {
            indicesString = "i";
          } else if (indicesRank === 2) {
            indicesString = "i, j";
          }
          var indicesSnippet = "getIndices(".concat(indicesString, ")");
          var updatesString = "";
          if (updatesRank === 1) {
            updatesString = "i";
          } else if (updatesRank === 2) {
            updatesString = "i, coords[1]";
          }
          var updatesSnippet = "getUpdates(".concat(updatesString, ")");
          var defaultValuesString = "";
          if (defaultIsTensor) {
            defaultValuesString = "coords[0], coords[1]";
          }
          var defaultValueSnippet = "getDefaultValue(".concat(defaultValuesString, ")");
          var strideString = sliceDim > 1 ? "strides[j]" : "strides";
          this.userCode = "\n        ".concat(stridesType, " strides = ").concat(stridesType, "(").concat(strides, ");\n\n        void main() {\n          ").concat(dtype, " coords = getOutputCoords();\n          float sum = 0.0;\n          bool found = false;\n          for (int i = 0; i < ").concat(updateSize, "; i++) {\n            int flattenedIndex = 0;\n            for (int j = 0; j < ").concat(sliceDim, "; j++) {\n              int index = round(").concat(indicesSnippet, ");\n              flattenedIndex += index * ").concat(strideString, ";\n            }\n            if (flattenedIndex == coords[0]) {\n              sum += ").concat(updatesSnippet, ";\n              found = true;\n            }\n          }\n          setOutput(mix(").concat(defaultValueSnippet, ", sum, float(found)));\n        }\n      ");
        }
        return ScatterProgram2;
      }()
    );
    var ScatterPackedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function ScatterPackedProgram2(updateSize, sliceDim, indicesRank, updatesRank, strides, shape, summingDupeIndex, defaultIsTensor) {
          if (defaultIsTensor === void 0) {
            defaultIsTensor = false;
          }
          this.variableNames = ["updates", "indices", "defaultValue"];
          this.packedInputs = true;
          this.packedOutput = true;
          this.outputShape = shape;
          var stridesType = getCoordsDataType(strides.length);
          var dtype = getCoordsDataType(shape.length);
          var indicesString = "";
          if (indicesRank === 1) {
            indicesString = "i";
          } else if (indicesRank === 2) {
            indicesString = "i, j";
          }
          var indicesSnippet = "getIndices(".concat(indicesString, ")");
          var updatesString = "";
          if (updatesRank === 1) {
            updatesString = "i";
          } else if (updatesRank === 2) {
            updatesString = "i, coords[1]";
          }
          var updatesSnippet = "getUpdates(".concat(updatesString, ")");
          var defaultValuesString = "";
          if (defaultIsTensor) {
            defaultValuesString = "coords[0], coords[1]";
          }
          var defaultValueSnippet = "getDefaultValue(".concat(defaultValuesString, ")");
          var strideString = sliceDim > 1 ? "strides[j]" : "strides";
          var strideString2 = sliceDim > 1 ? "strides[j + 1]" : "strides";
          this.userCode = "\n        ".concat(stridesType, " strides = ").concat(stridesType, "(").concat(strides, ");\n\n        void main() {\n          ").concat(dtype, " coords = getOutputCoords();\n          vec4 sum = vec4(0.);\n          vec4 found = vec4(0.);\n          for (int i = 0; i < ").concat(updateSize, "; i+=2) {\n            ivec2 flattenedIndex = ivec2(0);\n            for (int j = 0; j < ").concat(sliceDim, "; j+=2) {\n              ivec4 index = round(").concat(indicesSnippet, ");\n              flattenedIndex += index.xz * ").concat(strideString, ";\n              if (j + 1 < ").concat(sliceDim, ") {\n                flattenedIndex += index.yw * ").concat(strideString2, ";\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 = ").concat(updatesSnippet, ";\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(").concat(defaultValueSnippet, ", sum, found));\n        }\n      ");
        }
        return ScatterPackedProgram2;
      }()
    );
    function scatterNd(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var indices = inputs.indices, updates = inputs.updates;
      var shape = attrs.shape;
      var _a2 = tf.backend_util.calculateShapes(updates, indices, shape), sliceRank = _a2.sliceRank, numUpdates = _a2.numUpdates, sliceSize = _a2.sliceSize, strides = _a2.strides, outputSize = _a2.outputSize;
      var flattenShape = [outputSize / sliceSize, sliceSize];
      if (outputSize === 0) {
        return backend.makeTensorInfo(shape, indices.dtype);
      }
      var flattenIndices = reshape({ inputs: { x: indices }, backend, attrs: { shape: [numUpdates, sliceRank] } });
      var flattenX = reshape({ inputs: { x: updates }, backend, attrs: { shape: [numUpdates, sliceSize] } });
      var defaultValue = backend.makeTensorInfo([], "float32", new Float32Array([0]));
      var program;
      if (tf.env().getBool("WEBGL_PACK")) {
        program = new ScatterPackedProgram(numUpdates, sliceRank, flattenIndices.shape.length, flattenX.shape.length, strides, flattenShape);
      } else {
        program = new ScatterProgram(numUpdates, sliceRank, flattenIndices.shape.length, flattenX.shape.length, strides, flattenShape);
      }
      var res = backend.runWebGLProgram(program, [flattenX, flattenIndices, defaultValue], flattenX.dtype);
      var reshaped = reshape({ inputs: { x: res }, backend, attrs: { shape } });
      backend.disposeIntermediateTensorInfo(flattenIndices);
      backend.disposeIntermediateTensorInfo(flattenX);
      backend.disposeIntermediateTensorInfo(res);
      backend.disposeIntermediateTensorInfo(defaultValue);
      return reshaped;
    }
    var scatterNdConfig = {
      kernelName: tf.ScatterNd,
      backendName: "webgl",
      kernelFunc: scatterNd
    };
    var SearchSortedProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function SearchSortedProgram2(batchSize, numInputs, numValues, side) {
          this.variableNames = ["sortedSequence", "values"];
          this.customUniforms = [{ name: "numInputs", type: "int" }];
          this.outputShape = [batchSize, numValues];
          var webGL2LoopHead = "while (left < right) {";
          var webGL1LoopHead = "for (int i = 0; i < ".concat(Math.ceil(Math.log2(numInputs + 1)), "; ++i) { if (left >= right) break;");
          var loopHead = tf.env().getNumber("WEBGL_VERSION") === 2 ? webGL2LoopHead : webGL1LoopHead;
          var boundComparator = side === "left" ? "<" : "<=";
          this.userCode = "\n       int findBound(int batch, float value) {\n         int left = 0;\n         int right = numInputs;\n         int mid;\n         ".concat(loopHead, "\n           mid = (left + right) / 2;\n           if (getSortedSequence(batch, mid) ").concat(boundComparator, " 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     ");
        }
        return SearchSortedProgram2;
      }()
    );
    function searchSorted(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var sortedSequence = inputs.sortedSequence, values = inputs.values;
      var side = attrs.side;
      var program = new SearchSortedProgram(sortedSequence.shape[0], sortedSequence.shape[1], values.shape[1], side);
      var customValues = [[sortedSequence.shape[1]]];
      return backend.runWebGLProgram(program, [sortedSequence, values], "int32", customValues);
    }
    var searchSortedConfig = {
      kernelName: tf.SearchSorted,
      backendName: "webgl",
      kernelFunc: searchSorted
    };
    var SelectProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function SelectProgram2(cRank, shape, rank) {
          this.variableNames = ["c", "a", "b"];
          this.outputShape = shape;
          var cCoords;
          var abCoords;
          if (rank > 4) {
            throw Error("Where for rank ".concat(rank, " is not yet supported"));
          }
          if (rank === 1) {
            abCoords = "resRC";
            cCoords = "resRC";
          } else {
            var currentCoords = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"];
            var cCoordVars = [];
            var abCoordVars = [];
            for (var i = 0; i < shape.length; i++) {
              abCoordVars.push("".concat(currentCoords[i]));
              if (i < cRank) {
                cCoordVars.push("".concat(currentCoords[i]));
              }
            }
            cCoords = cCoordVars.join();
            abCoords = abCoordVars.join();
          }
          var dtype = getCoordsDataType(rank);
          this.userCode = "\n      void main() {\n        ".concat(dtype, " resRC = getOutputCoords();\n        float cVal = getC(").concat(cCoords, ");\n        if (cVal >= 1.0) {\n          setOutput(getA(").concat(abCoords, "));\n        } else {\n          setOutput(getB(").concat(abCoords, "));\n        }\n      }\n    ");
        }
        return SelectProgram2;
      }()
    );
    function select(args) {
      var inputs = args.inputs, backend = args.backend;
      var condition = inputs.condition, t = inputs.t, e = inputs.e;
      var program = new SelectProgram(condition.shape.length, t.shape, t.shape.length);
      return backend.runWebGLProgram(program, [condition, t, e], tf.upcastType(t.dtype, e.dtype));
    }
    var selectConfig = {
      kernelName: tf.Select,
      backendName: "webgl",
      kernelFunc: select
    };
    var SELU = "\n  // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n  // see: https://arxiv.org/abs/1706.02515\n  float scaleAlpha = ".concat(tf.backend_util.SELU_SCALEALPHA, ";\n  float scale = ").concat(tf.backend_util.SELU_SCALE, ";\n  return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n");
    var selu = unaryKernelFunc({ opSnippet: SELU });
    var seluConfig = {
      kernelName: tf.Selu,
      backendName: "webgl",
      kernelFunc: selu
    };
    var SIGMOID = CHECK_NAN_SNIPPET_UNARY + "\n  return 1.0 / (1.0 + exp(-1.0 * x));\n";
    var SIGMOID_PACKED = "\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";
    var sigmoid = unaryKernelFunc({
      opSnippet: SIGMOID,
      packedOpSnippet: SIGMOID_PACKED,
      cpuKernelImpl: sigmoidImplCPU
    });
    var sigmoidConfig = {
      kernelName: tf.Sigmoid,
      backendName: "webgl",
      kernelFunc: sigmoid
    };
    var SIGN = "\n  if (isnan(x)) { return 0.0; }\n  return sign(x);\n";
    var sign = unaryKernelFunc({ opSnippet: SIGN });
    var signConfig = {
      kernelName: tf.Sign,
      backendName: "webgl",
      kernelFunc: sign
    };
    var SIN = CHECK_NAN_SNIPPET_UNARY + "\n  return sin(x);\n";
    var SIN_PACKED = "\n  vec4 result = sin(x);\n  bvec4 isNaN = isnan(x);\n  ".concat(CHECK_NAN_SNIPPET_PACKED, "\n  return result;\n");
    var sin = unaryKernelFunc({ opSnippet: SIN, packedOpSnippet: SIN_PACKED });
    var sinConfig = {
      kernelName: tf.Sin,
      backendName: "webgl",
      kernelFunc: sin
    };
    var SINH = "\n  float e2x = exp(x);\n  return (e2x - 1.0 / e2x) / 2.0;\n";
    var sinh = unaryKernelFunc({ opSnippet: SINH });
    var sinhConfig = {
      kernelName: tf.Sinh,
      backendName: "webgl",
      kernelFunc: sinh
    };
    var SOFTPLUS = "\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";
    var softplus = unaryKernelFunc({ opSnippet: SOFTPLUS });
    var softplusConfig = {
      kernelName: tf.Softplus,
      backendName: "webgl",
      kernelFunc: softplus
    };
    var spaceToBatchND = function(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var blockShape = attrs.blockShape, paddings = attrs.paddings;
      tf.util.assert(x.shape.length <= 4, function() {
        return "spaceToBatchND for rank > 4 with a WebGL backend not implemented yet";
      });
      var prod2 = blockShape.reduce(function(a, b) {
        return a * b;
      });
      var completePaddings = [[0, 0]];
      completePaddings.push.apply(completePaddings, __spreadArray([], __read(paddings), false));
      for (var i = 1 + blockShape.length; i < x.shape.length; ++i) {
        completePaddings.push([0, 0]);
      }
      var toDispose = [];
      var paddedX = padV2({
        inputs: { x },
        backend,
        attrs: { paddings: completePaddings, constantValue: 0 }
      });
      var reshapedPaddedShape = tf.backend_util.getReshaped(paddedX.shape, blockShape, prod2, false);
      var permutedReshapedPaddedPermutation = tf.backend_util.getPermuted(reshapedPaddedShape.length, blockShape.length, false);
      var flattenShape = tf.backend_util.getReshapedPermuted(paddedX.shape, blockShape, prod2, false);
      var reshapedPaddedX = reshape({ inputs: { x: paddedX }, backend, attrs: { shape: reshapedPaddedShape } });
      var paddedXT = transpose({
        inputs: { x: reshapedPaddedX },
        backend,
        attrs: { perm: permutedReshapedPaddedPermutation }
      });
      var result = reshape({ inputs: { x: paddedXT }, backend, attrs: { shape: flattenShape } });
      toDispose.push(paddedX);
      toDispose.push(reshapedPaddedX);
      toDispose.push(paddedXT);
      toDispose.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return result;
    };
    var spaceToBatchNDConfig = {
      kernelName: tf.SpaceToBatchND,
      backendName: "webgl",
      kernelFunc: spaceToBatchND
    };
    function sparseFillEmptyRows(args) {
      var inputs = args.inputs, backend = args.backend;
      var indices = inputs.indices, values = inputs.values, denseShape = inputs.denseShape, defaultValue = inputs.defaultValue;
      if (denseShape.shape.length !== 1) {
        throw new Error("Dense shape must be a vector, saw:\n         ".concat(denseShape.shape));
      }
      if (indices.shape.length !== 2) {
        throw new Error("Indices must be a matrix, saw:\n         ".concat(indices.shape));
      }
      if (values.shape.length !== 1) {
        throw new Error("Values must be a vector, saw:\n         ".concat(values.shape));
      }
      if (defaultValue.shape.length !== 0) {
        throw new Error("Default value must be a scalar, saw:\n        ".concat(defaultValue.shape));
      }
      var $indices = backend.readSync(indices.dataId);
      var $values = backend.readSync(values.dataId);
      var $denseShape = backend.readSync(denseShape.dataId);
      var $defaultValue = backend.readSync(defaultValue.dataId)[0];
      var _a2 = __read(sparseFillEmptyRowsImplCPU($indices, indices.shape, indices.dtype, $values, values.dtype, $denseShape, $defaultValue), 5), outputIndices = _a2[0], outputIndicesShape = _a2[1], outputValues = _a2[2], emptyRowIndicator = _a2[3], reverseIndexMap = _a2[4];
      return [
        backend.makeTensorInfo(outputIndicesShape, indices.dtype, outputIndices),
        backend.makeTensorInfo([outputIndicesShape[0]], values.dtype, outputValues),
        backend.makeTensorInfo([emptyRowIndicator.length], "bool", new Uint8Array(emptyRowIndicator.map(function(value) {
          return Number(value);
        }))),
        backend.makeTensorInfo([reverseIndexMap.length], indices.dtype, new Int32Array(reverseIndexMap))
      ];
    }
    var sparseFillEmptyRowsConfig = {
      kernelName: tf.SparseFillEmptyRows,
      backendName: "webgl",
      kernelFunc: sparseFillEmptyRows
    };
    function sparseReshape(args) {
      var inputs = args.inputs, backend = args.backend;
      var inputIndices = inputs.inputIndices, inputShape = inputs.inputShape, newShape = inputs.newShape;
      if (inputIndices.shape.length !== 2) {
        throw new Error("Input indices should be a matrix but received shape ".concat(inputIndices.shape));
      }
      if (inputShape.shape.length !== 1) {
        throw new Error("Input shape should be a vector but received shape ".concat(inputShape.shape));
      }
      if (newShape.shape.length !== 1) {
        throw new Error("Target shape should be a vector but received shape ".concat(newShape.shape));
      }
      var $inputShape = Array.from(backend.readSync(inputShape.dataId));
      var $inputIndices = backend.readSync(inputIndices.dataId);
      var targetShape = Array.from(backend.readSync(newShape.dataId));
      var _a2 = __read(sparseReshapeImplCPU($inputIndices, inputIndices.shape, inputIndices.dtype, $inputShape, targetShape), 3), newIndices = _a2[0], indicesShape = _a2[1], outputShape = _a2[2];
      return [
        backend.makeTensorInfo(indicesShape, inputIndices.dtype, newIndices),
        backend.makeTensorInfo([outputShape.length], newShape.dtype, new Int32Array(outputShape))
      ];
    }
    var sparseReshapeConfig = {
      kernelName: tf.SparseReshape,
      backendName: "webgl",
      kernelFunc: sparseReshape
    };
    function sparseSegmentMean(args) {
      var inputs = args.inputs, backend = args.backend;
      var data = inputs.data, indices = inputs.indices, segmentIds = inputs.segmentIds;
      if (data.shape.length < 1) {
        throw new Error("Data should be at least 1 dimensional but received scalar");
      }
      if (indices.shape.length !== 1) {
        throw new Error("Indices should be a vector but received shape\n              ".concat(indices.shape));
      }
      if (segmentIds.shape.length !== 1) {
        throw new Error("Segment ids should be a vector but received shape\n              ".concat(segmentIds.shape));
      }
      var $data = backend.readSync(data.dataId);
      var $indices = backend.readSync(indices.dataId);
      var $segmentIds = backend.readSync(segmentIds.dataId);
      var _a2 = __read(sparseSegmentReductionImplCPU($data, data.shape, data.dtype, $indices, $segmentIds, true), 2), outputData = _a2[0], outputDataShape = _a2[1];
      return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);
    }
    var sparseSegmentMeanConfig = {
      kernelName: tf.SparseSegmentMean,
      backendName: "webgl",
      kernelFunc: sparseSegmentMean
    };
    function sparseSegmentSum(args) {
      var inputs = args.inputs, backend = args.backend;
      var data = inputs.data, indices = inputs.indices, segmentIds = inputs.segmentIds;
      if (data.shape.length < 1) {
        throw new Error("Data should be at least 1 dimensional but received scalar");
      }
      if (indices.shape.length !== 1) {
        throw new Error("Indices should be a vector but received shape\n             ".concat(indices.shape));
      }
      if (segmentIds.shape.length !== 1) {
        throw new Error("Segment ids should be a vector but received shape\n             ".concat(segmentIds.shape));
      }
      var $data = backend.readSync(data.dataId);
      var $indices = backend.readSync(indices.dataId);
      var $segmentIds = backend.readSync(segmentIds.dataId);
      var _a2 = __read(sparseSegmentReductionImplCPU($data, data.shape, data.dtype, $indices, $segmentIds), 2), outputData = _a2[0], outputDataShape = _a2[1];
      return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);
    }
    var sparseSegmentSumConfig = {
      kernelName: tf.SparseSegmentSum,
      backendName: "webgl",
      kernelFunc: sparseSegmentSum
    };
    function sparseToDense(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var sparseIndices = inputs.sparseIndices, sparseValues = inputs.sparseValues, defaultValue = inputs.defaultValue;
      var outputShape = attrs.outputShape;
      var _a2 = tf.backend_util.calculateShapes(sparseValues, sparseIndices, outputShape), sliceRank = _a2.sliceRank, numUpdates = _a2.numUpdates, sliceSize = _a2.sliceSize, strides = _a2.strides, outputSize = _a2.outputSize;
      var sumDupeIndices = false;
      if (sparseValues.dtype === "string") {
        var indicesBuf = backend.bufferSync(sparseIndices);
        var updatesBuf = backend.bufferSync(sparseValues);
        var $defaultValue = tf.util.decodeString(backend.readSync(defaultValue.dataId)[0]);
        var outBuf = scatterImplCPU(indicesBuf, updatesBuf, outputShape, outputSize, sliceSize, numUpdates, sliceRank, strides, $defaultValue, sumDupeIndices);
        return backend.makeTensorInfo(outputShape, outBuf.dtype, outBuf.values);
      }
      var program = new ScatterProgram(numUpdates, sliceRank, sparseIndices.shape.length, sparseValues.shape.length, strides, [outputSize, 1], sumDupeIndices);
      var res = backend.runWebGLProgram(program, [sparseValues, sparseIndices, defaultValue], sparseValues.dtype);
      var reshaped = reshape({ inputs: { x: res }, backend, attrs: { shape: outputShape } });
      backend.disposeIntermediateTensorInfo(res);
      return reshaped;
    }
    var sparseToDenseConfig = {
      kernelName: tf.SparseToDense,
      backendName: "webgl",
      kernelFunc: sparseToDense
    };
    function splitV(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var numOrSizeSplits = attrs.numOrSizeSplits, axis = attrs.axis;
      var $axis = tf.util.parseAxisParam(axis, x.shape)[0];
      var splitSizes = tf.backend_util.prepareSplitSize(x, numOrSizeSplits, $axis);
      var xRank = x.shape.length;
      var begin = new Array(xRank).fill(0);
      var size = x.shape.slice();
      return splitSizes.map(function(s) {
        var sliceSize = __spreadArray([], __read(size), false);
        sliceSize[$axis] = s;
        var sliceT = slice({ inputs: { x }, backend, attrs: { begin, size: sliceSize } });
        begin[$axis] += s;
        return sliceT;
      });
    }
    var splitVConfig = {
      kernelName: tf.SplitV,
      backendName: "webgl",
      kernelFunc: splitV
    };
    var SQRT = "return sqrt(x);";
    var sqrt = unaryKernelFunc({ opSnippet: SQRT, packedOpSnippet: SQRT, cpuKernelImpl: sqrtImplCPU });
    var sqrtConfig = {
      kernelName: tf.Sqrt,
      backendName: "webgl",
      kernelFunc: sqrt
    };
    var SQUARE = "return x * x;";
    var square = unaryKernelFunc({ opSnippet: SQUARE });
    var squareConfig = {
      kernelName: tf.Square,
      backendName: "webgl",
      kernelFunc: square
    };
    var SQUARED_DIFFERENCE = "return (a - b) * (a - b);";
    var squaredDifference = binaryKernelFunc({ opSnippet: SQUARED_DIFFERENCE, packedOpSnippet: SQUARED_DIFFERENCE });
    var squaredDifferenceConfig = {
      kernelName: tf.SquaredDifference,
      backendName: "webgl",
      kernelFunc: squaredDifference
    };
    function staticRegexReplace(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      if (x.dtype !== "string") {
        throw new Error("Input must be of datatype string");
      }
      var $x = backend.readSync(x.dataId);
      var stringInput = tf.backend_util.fromUint8ToStringArray($x);
      var output = staticRegexReplaceImplCPU(stringInput, "string", attrs);
      return backend.makeTensorInfo(x.shape, "string", output);
    }
    var staticRegexReplaceConfig = {
      kernelName: tf.StaticRegexReplace,
      backendName: "webgl",
      kernelFunc: staticRegexReplace
    };
    function step(_a2) {
      var inputs = _a2.inputs, attrs = _a2.attrs, backend = _a2.backend;
      var x = inputs.x;
      var opSnippet = CHECK_NAN_SNIPPET$1 + "\n    return x > 0.0 ? 1.0 : float(".concat(attrs.alpha, ");\n  ");
      var program = new UnaryOpProgram(x.shape, opSnippet);
      return backend.runWebGLProgram(program, [x], x.dtype);
    }
    var stepConfig = {
      kernelName: tf.Step,
      backendName: "webgl",
      kernelFunc: step
    };
    var StridedSliceProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function StridedSliceProgram2(begin, strides, size) {
          this.variableNames = ["x"];
          this.outputShape = size;
          var rank = size.length;
          var inputDtype = getCoordsDataType(size.length);
          var dtype = getCoordsDataType(size.length);
          var newCoords = "";
          if (rank === 1) {
            newCoords = "coords * strides + begin";
          } else {
            var outputAxis_1 = 0;
            newCoords = size.map(function(_, i) {
              outputAxis_1++;
              return size.length === 1 ? "coords * strides[".concat(i, "] + begin[").concat(i, "]") : "coords[".concat(outputAxis_1 - 1, "] * strides[").concat(i, "] + begin[").concat(i, "]");
            }).join(",");
          }
          this.userCode = "\n      ".concat(inputDtype, " begin = ").concat(inputDtype, "(").concat(begin, ");\n      ").concat(inputDtype, " strides = ").concat(inputDtype, "(").concat(strides, ");\n\n      void main() {\n        ").concat(dtype, " coords = getOutputCoords();\n        setOutput(getX(").concat(newCoords, "));\n      }\n    ");
        }
        return StridedSliceProgram2;
      }()
    );
    function stridedSlice(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var begin = attrs.begin, end = attrs.end, strides = attrs.strides, beginMask = attrs.beginMask, endMask = attrs.endMask, ellipsisMask = attrs.ellipsisMask, newAxisMask = attrs.newAxisMask, shrinkAxisMask = attrs.shrinkAxisMask;
      var _a2 = tf.slice_util.sliceInfo(x.shape, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask), finalShapeSparse = _a2.finalShapeSparse, finalShape = _a2.finalShape, isIdentity = _a2.isIdentity, sliceDim0 = _a2.sliceDim0, isSimpleSlice = _a2.isSimpleSlice, $begin = _a2.begin, $end = _a2.end, $strides = _a2.strides;
      var result;
      if (isIdentity) {
        result = reshape({ inputs: { x }, backend, attrs: { shape: finalShape } });
      } else if (sliceDim0 || isSimpleSlice) {
        tf.util.assert(x.shape.length >= 1, function() {
          return "Input must have rank at least 1, got: ".concat(x.shape.length);
        });
        var size = tf.slice_util.computeOutShape($begin, $end, $strides);
        var sliced = slice({ inputs: { x }, backend, attrs: { begin: $begin, size } });
        result = reshape({ inputs: { x: sliced }, backend, attrs: { shape: finalShape } });
        backend.disposeIntermediateTensorInfo(sliced);
      } else {
        var shouldExecuteOnCPU = backend.shouldExecuteOnCPU([x]);
        if (shouldExecuteOnCPU) {
          var values = backend.readSync(x.dataId);
          var xBuf = tf.buffer(x.shape, x.dtype, values);
          var resultValues = stridedSliceImplCPU(finalShapeSparse, xBuf, $strides, $begin);
          result = backend.makeTensorInfo(finalShape, x.dtype, resultValues.values);
        } else {
          var program = new StridedSliceProgram($begin, $strides, finalShapeSparse);
          result = backend.runWebGLProgram(program, [x], x.dtype);
        }
      }
      var resultReshaped = reshape({ inputs: { x: result }, backend, attrs: { shape: finalShape } });
      backend.disposeIntermediateTensorInfo(result);
      return resultReshaped;
    }
    var stridedSliceConfig = {
      kernelName: tf.StridedSlice,
      backendName: "webgl",
      kernelFunc: stridedSlice
    };
    function stringNGrams(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var separator = attrs.separator, nGramWidths = attrs.nGramWidths, leftPad = attrs.leftPad, rightPad = attrs.rightPad, padWidth = attrs.padWidth, preserveShortSequences = attrs.preserveShortSequences;
      var data = inputs.data, dataSplits = inputs.dataSplits;
      var $data = backend.readSync(data.dataId);
      var $dataSplits = backend.readSync(dataSplits.dataId);
      var _a2 = __read(stringNGramsImplCPU($data, $dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences), 2), nGrams = _a2[0], nGramsSplits = _a2[1];
      return [
        backend.makeTensorInfo([nGrams.length], "string", nGrams),
        backend.makeTensorInfo(dataSplits.shape, "int32", nGramsSplits)
      ];
    }
    var stringNGramsConfig = {
      kernelName: tf.StringNGrams,
      backendName: "webgl",
      kernelFunc: stringNGrams
    };
    function stringSplit(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var skipEmpty = attrs.skipEmpty;
      var input = inputs.input, delimiter = inputs.delimiter;
      if (input.dtype !== "string") {
        throw new Error("Input must be of datatype string");
      }
      if (input.shape.length !== 1) {
        throw new Error("Input must be a vector, got shape: ".concat(input.shape));
      }
      if (delimiter.shape.length !== 0) {
        throw new Error("Delimiter must be a scalar, got shape: ".concat(delimiter.shape));
      }
      var $input = backend.readSync(input.dataId);
      var $delimiter = backend.readSync(delimiter.dataId)[0];
      var _a2 = __read(stringSplitImplCPU($input, $delimiter, skipEmpty), 3), indices = _a2[0], values = _a2[1], shape = _a2[2];
      var outputSize = values.length;
      return [
        backend.makeTensorInfo([outputSize, 2], "int32", indices),
        backend.makeTensorInfo([outputSize], "string", values),
        backend.makeTensorInfo([2], "int32", new Int32Array(shape))
      ];
    }
    var stringSplitConfig = {
      kernelName: tf.StringSplit,
      backendName: "webgl",
      kernelFunc: stringSplit
    };
    function stringToHashBucketFast(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var numBuckets = attrs.numBuckets;
      var input = inputs.input;
      if (input.dtype !== "string") {
        throw new Error("Input must be of datatype string");
      }
      if (numBuckets <= 0) {
        throw new Error("Number of buckets must be at least 1");
      }
      var $input = backend.readSync(input.dataId);
      var output = stringToHashBucketFastImplCPU($input, numBuckets);
      return backend.makeTensorInfo(input.shape, "int32", output);
    }
    var stringToHashBucketFastConfig = {
      kernelName: tf.StringToHashBucketFast,
      backendName: "webgl",
      kernelFunc: stringToHashBucketFast
    };
    var TAN = "return tan(x);";
    var tan = unaryKernelFunc({ opSnippet: TAN });
    var tanConfig = {
      kernelName: tf.Tan,
      backendName: "webgl",
      kernelFunc: tan
    };
    var TANH = "\n  float e2x = exp(-2.0 * abs(x));\n  return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n";
    var tanh = unaryKernelFunc({ opSnippet: TANH });
    var tanhConfig = {
      kernelName: tf.Tanh,
      backendName: "webgl",
      kernelFunc: tanh
    };
    function tensorScatterUpdate(args) {
      var inputs = args.inputs, backend = args.backend;
      args.attrs;
      var tensor = inputs.tensor, indices = inputs.indices, updates = inputs.updates;
      var _b = tf.backend_util.calculateShapes(updates, indices, tensor.shape), sliceRank = _b.sliceRank, numUpdates = _b.numUpdates, sliceSize = _b.sliceSize, strides = _b.strides, outputSize = _b.outputSize;
      var flattenShape = [outputSize / sliceSize, sliceSize];
      if (outputSize === 0) {
        return backend.makeTensorInfo(tensor.shape, indices.dtype);
      }
      var flattenIndices = reshape({ inputs: { x: indices }, backend, attrs: { shape: [numUpdates, sliceRank] } });
      var flattenX = reshape({ inputs: { x: updates }, backend, attrs: { shape: [numUpdates, sliceSize] } });
      var flattenTensor = reshape({ inputs: { x: tensor }, backend, attrs: { shape: flattenShape } });
      var program = new ScatterProgram(numUpdates, sliceRank, flattenIndices.shape.length, flattenX.shape.length, strides, flattenShape, false, true);
      var res = backend.runWebGLProgram(program, [flattenX, flattenIndices, flattenTensor], flattenTensor.dtype);
      var reshaped = reshape({ inputs: { x: res }, backend, attrs: { shape: tensor.shape } });
      backend.disposeIntermediateTensorInfo(flattenIndices);
      backend.disposeIntermediateTensorInfo(flattenX);
      backend.disposeIntermediateTensorInfo(flattenTensor);
      backend.disposeIntermediateTensorInfo(res);
      return reshaped;
    }
    var tensorScatterUpdateConfig = {
      kernelName: tf.TensorScatterUpdate,
      backendName: "webgl",
      kernelFunc: tensorScatterUpdate
    };
    var TileProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function TileProgram2(aShape, reps) {
          this.variableNames = ["A"];
          var outputShape = new Array(aShape.length);
          for (var i = 0; i < outputShape.length; i++) {
            outputShape[i] = aShape[i] * reps[i];
          }
          this.outputShape = outputShape;
          this.rank = outputShape.length;
          var dtype = getCoordsDataType(this.rank);
          var sourceCoords = getSourceCoords(aShape);
          this.userCode = "\n      void main() {\n        ".concat(dtype, " resRC = getOutputCoords();\n        setOutput(getA(").concat(sourceCoords, "));\n      }\n    ");
        }
        return TileProgram2;
      }()
    );
    function getSourceCoords(aShape) {
      var rank = aShape.length;
      if (rank > 5) {
        throw Error("Tile for rank ".concat(rank, " is not yet supported"));
      }
      if (rank === 1) {
        return "imod(resRC, ".concat(aShape[0], ")");
      }
      var currentCoords = ["resRC.x", "resRC.y", "resRC.z", "resRC.w", "resRC.u"];
      var sourceCoords = [];
      for (var i = 0; i < aShape.length; i++) {
        sourceCoords.push("imod(".concat(currentCoords[i], ", ").concat(aShape[i], ")"));
      }
      return sourceCoords.join();
    }
    function tile(params) {
      var inputs = params.inputs, backend = params.backend, attrs = params.attrs;
      var x = inputs.x;
      var reps = attrs.reps;
      if (x.dtype === "string" || x.shape.length > 5) {
        var data = backend.readSync(x.dataId);
        var value = x.dtype === "string" ? data.map(function(d) {
          return tf.util.decodeString(d);
        }) : data;
        var buf = tf.buffer(x.shape, x.dtype, value);
        var outBuf = tileImplCPU(buf, reps);
        return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);
      }
      var program = new TileProgram(x.shape, reps);
      var output = backend.runWebGLProgram(program, [x], x.dtype);
      return output;
    }
    var tileConfig = {
      kernelName: tf.Tile,
      backendName: "webgl",
      kernelFunc: tile
    };
    var SwapProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function SwapProgram2(shape) {
          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 = shape;
          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     ";
        }
        return SwapProgram2;
      }()
    );
    var MergeProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function MergeProgram2(shape) {
          this.variableNames = ["x", "indices"];
          this.customUniforms = [
            { name: "n", type: "int" },
            { name: "firstPass", type: "int" },
            { name: "k", type: "int" }
          ];
          this.outputShape = shape;
          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     ";
        }
        return MergeProgram2;
      }()
    );
    function disposeIntermediateTensorInfoOrNull(backend, tensorInfo) {
      if (tensorInfo !== null) {
        backend.disposeIntermediateTensorInfo(tensorInfo);
      }
    }
    function roundUpToPow2(num) {
      var pow2 = 1;
      while (pow2 < num) {
        pow2 *= 2;
      }
      return pow2;
    }
    function topK(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x;
      var k = attrs.k, sorted = attrs.sorted;
      var TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD = tf.env().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD");
      var TOPK_K_CPU_HANDOFF_THRESHOLD = tf.env().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD");
      var xShape = x.shape;
      var lastDim = xShape[xShape.length - 1];
      if (backend.shouldExecuteOnCPU([x]) || lastDim < TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD || k > TOPK_K_CPU_HANDOFF_THRESHOLD) {
        var xVals = backend.readSync(x.dataId);
        var _a2 = __read(topKImplCPU(xVals, xShape, x.dtype, k, sorted), 2), allTopKVals = _a2[0], allTopKIndices = _a2[1];
        return [
          backend.makeTensorInfo(allTopKVals.shape, allTopKVals.dtype, allTopKVals.values),
          backend.makeTensorInfo(allTopKIndices.shape, allTopKIndices.dtype, allTopKIndices.values)
        ];
      }
      if (k === 0) {
        xShape[xShape.length - 1] = 0;
        return [
          backend.makeTensorInfo(xShape, x.dtype, []),
          backend.makeTensorInfo(xShape, "int32", [])
        ];
      }
      if (lastDim === 1) {
        return [
          x,
          fill({ attrs: { shape: xShape, dtype: "int32", value: 0 }, backend })
        ];
      }
      var xtexData = backend.texData.get(x.dataId);
      var xIsPacked = xtexData !== null && xtexData.isPacked;
      var xUnPacked = xIsPacked ? backend.unpackTensor(x) : x;
      var xSize = tf.util.sizeFromShape(xShape);
      var batch = xSize / lastDim;
      var x2D = reshape({ inputs: { x: xUnPacked }, attrs: { shape: [batch, lastDim] }, backend });
      if (xIsPacked) {
        disposeIntermediateTensorInfoOrNull(backend, xUnPacked);
      }
      var kPow2 = roundUpToPow2(k);
      var lastDimPow2 = roundUpToPow2(lastDim);
      var indices = null;
      var getInputs = function() {
        return indices === null ? [x2D, x2D] : [x2D, indices];
      };
      var runSwap = function(dir2, inc2, shape) {
        var inputs2 = getInputs();
        var program = new SwapProgram(shape);
        var fistPass = indices === null ? 1 : 0;
        var customValues2 = [[lastDim], [fistPass], [Number.NEGATIVE_INFINITY], [dir2], [inc2]];
        var prevIndices2 = indices;
        indices = backend.runWebGLProgram(program, inputs2, "int32", customValues2);
        disposeIntermediateTensorInfoOrNull(backend, prevIndices2);
      };
      for (var len = 1; len < kPow2; len *= 2) {
        var dir = len * 2;
        for (var inc = len; inc >= 1; inc /= 2) {
          runSwap(dir, inc, [batch, lastDimPow2]);
        }
      }
      for (var indicesSize = lastDimPow2; indicesSize > kPow2; indicesSize /= 2) {
        var inputs_1 = getInputs();
        var mergeProgram = new MergeProgram([batch, indicesSize / 2]);
        var firstPass = indices === null ? 1 : 0;
        var customValues = [[lastDim], [firstPass], [kPow2]];
        var prevIndices_1 = indices;
        indices = backend.runWebGLProgram(mergeProgram, inputs_1, "int32", customValues);
        disposeIntermediateTensorInfoOrNull(backend, prevIndices_1);
        var len = kPow2 / 2;
        var dir = len * 2;
        for (var inc = len; inc >= 1; inc /= 2) {
          runSwap(dir, inc, indices.shape);
        }
      }
      var prevIndices = indices;
      indices = slice({ inputs: { x: indices }, backend, attrs: { begin: 0, size: [batch, k] } });
      disposeIntermediateTensorInfoOrNull(backend, prevIndices);
      var values = gatherV2({ inputs: { x: x2D, indices }, backend, attrs: { axis: 1, batchDims: 1 } });
      disposeIntermediateTensorInfoOrNull(backend, x2D);
      var newShape = xShape.slice(0, -1);
      newShape.push(k);
      prevIndices = indices;
      indices = reshape({ inputs: { x: indices }, attrs: { shape: newShape }, backend });
      disposeIntermediateTensorInfoOrNull(backend, prevIndices);
      var prevValues = values;
      values = reshape({ inputs: { x: values }, attrs: { shape: newShape }, backend });
      disposeIntermediateTensorInfoOrNull(backend, prevValues);
      return [values, indices];
    }
    var topKConfig = {
      kernelName: tf.TopK,
      backendName: "webgl",
      kernelFunc: topK
    };
    var TransformProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function TransformProgram2(imageHeight, imageWidth, interpolation, fillMode, fillValue, outShape) {
          this.variableNames = ["Image", "Transforms"];
          this.outputShape = outShape;
          var interpolationModeId = interpolation === "nearest" ? 1 : 2;
          var fillModeId;
          switch (fillMode) {
            case "constant":
              fillModeId = 1;
              break;
            case "reflect":
              fillModeId = 2;
              break;
            case "wrap":
              fillModeId = 3;
              break;
            case "nearest":
              fillModeId = 4;
              break;
            default:
              fillModeId = 1;
              break;
          }
          this.userCode = "\n            float mapCoord(float outCoord, float len) {\n              float inCoord = outCoord;\n              if(".concat(fillModeId, " == 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 (").concat(fillModeId, " == 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 (").concat(fillModeId, " == 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 < ").concat(imageHeight, " && 0 <= coordX && coordX < ").concat(imageWidth, ") {\n                  outputValue = getImage(batch, coordY, coordX, channel);\n              } else {\n                outputValue = float(").concat(fillValue, ");\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(").concat(fillValue, ");\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(").concat(imageWidth, "));\n                float mapY = mapCoord(inY, float(").concat(imageHeight, "));\n\n                if (").concat(interpolationModeId, " == 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        ");
        }
        return TransformProgram2;
      }()
    );
    function transform(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var image = inputs.image, transforms = inputs.transforms;
      var interpolation = attrs.interpolation, fillMode = attrs.fillMode, fillValue = attrs.fillValue, outputShape = attrs.outputShape;
      var _a2 = __read(image.shape, 4), batch = _a2[0], imageHeight = _a2[1], imageWidth = _a2[2], numChannels = _a2[3];
      var _b = __read(outputShape != null ? outputShape : [imageHeight, imageWidth], 2), outHeight = _b[0], outWidth = _b[1];
      var outShape = [
        batch,
        outHeight,
        outWidth,
        numChannels
      ];
      var program = new TransformProgram(imageHeight, imageWidth, interpolation, fillMode, fillValue, outShape);
      return backend.runWebGLProgram(program, [image, transforms], "float32");
    }
    var transformConfig = {
      kernelName: tf.Transform,
      backendName: "webgl",
      kernelFunc: transform
    };
    function unique(args) {
      var inputs = args.inputs, attrs = args.attrs, backend = args.backend;
      var axis = attrs.axis;
      var x = inputs.x;
      assertNotComplex(x, "unique");
      console.warn("WARNING: ", "UI might be locked temporarily as data is being downloaded");
      var values = backend.readSync(x.dataId);
      var _a2 = uniqueImplCPU(values, axis, x.shape, x.dtype), outputValues = _a2.outputValues, outputShape = _a2.outputShape, indices = _a2.indices;
      return [
        backend.makeTensorInfo(outputShape, x.dtype, outputValues),
        backend.makeTensorInfo([indices.length], "int32", indices)
      ];
    }
    var uniqueConfig = {
      kernelName: tf.Unique,
      backendName: "webgl",
      kernelFunc: unique
    };
    function unpack(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var value = inputs.value;
      var axis = attrs.axis;
      if (axis < 0) {
        axis += value.shape.length;
      }
      var x = value;
      var xRank = x.shape.length;
      var num = value.shape[axis];
      var outShape = new Array(xRank - 1);
      var outIndex = 0;
      for (var i = 0; i < xRank; i++) {
        if (i !== axis) {
          outShape[outIndex++] = x.shape[i];
        }
      }
      var toDispose = [];
      var begin = new Array(xRank).fill(0);
      var size = x.shape.slice();
      size[axis] = 1;
      var res = new Array(num);
      for (var i = 0; i < res.length; i++) {
        begin[axis] = i;
        var sliced = slice({ inputs: { x }, backend, attrs: { begin, size } });
        var reshaped = reshape({ inputs: { x: sliced }, backend, attrs: { shape: outShape } });
        res[i] = reshaped;
        toDispose.push(sliced);
      }
      toDispose.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return res;
    }
    var unpackConfig = {
      kernelName: tf.Unpack,
      backendName: "webgl",
      kernelFunc: unpack
    };
    var SegmentOpProgram = (
      /** @class */
      /* @__PURE__ */ function() {
        function SegmentOpProgram2(segOpInfo, segOpType) {
          this.variableNames = ["x", "segmentIds"];
          var windowSize = segOpInfo.windowSize;
          var batchSize = segOpInfo.batchSize;
          var inSize = segOpInfo.inSize;
          var numSegments = segOpInfo.numSegments;
          var outSize = numSegments * Math.ceil(inSize / windowSize);
          this.outputShape = [batchSize, outSize];
          var initializationValue = "0.0";
          var returnValue = "sumValue";
          var windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;
          var windowSizeVec4Remainder = windowSize % 4;
          var updateSnippet = "\n        sumValue += dot(values, segFilter);\n    ";
          var checkValueOutOfBounds = "";
          if (inSize % windowSize > 0) {
            checkValueOutOfBounds = "\n        if (inIdx < 0 || inIdx >= ".concat(inSize, ") {\n          return initializationValue;\n        }\n      ");
          }
          var checkSegmentIdOutOfBounds = "";
          if (inSize % windowSize > 0) {
            checkSegmentIdOutOfBounds = "\n        if (inIdx < 0 || inIdx >= ".concat(inSize, ") {\n          return -1.0;\n        }\n      ");
          }
          this.userCode = "\n      const float initializationValue = ".concat(initializationValue, ";\n\n      float getValue(int batch, int inIdx) {\n        ").concat(checkValueOutOfBounds, "\n        return getX(batch, inIdx);\n      }\n\n      float getSegmentIdAtIndex(int inIdx) {\n        ").concat(checkSegmentIdOutOfBounds, "\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          ").concat(numSegments, ")) * float(").concat(windowSize, "));\n        int currentSeg = int(mod(float(outIdx), float(").concat(numSegments, ")));\n\n        float sumValue = 0.0;\n\n        for (int i = 0; i < ").concat(windowSizeNearestVec4, "; 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          ").concat(updateSnippet, "\n        }\n\n        int inIdx = inOffset + ").concat(windowSizeNearestVec4, ";\n        if (").concat(windowSizeVec4Remainder === 1, ") {\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          ").concat(updateSnippet, "\n        } else if (").concat(windowSizeVec4Remainder === 2, ") {\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          ").concat(updateSnippet, "\n        } else if (").concat(windowSizeVec4Remainder === 3, ") {\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          ").concat(updateSnippet, "\n        }\n        setOutput(").concat(returnValue, ");\n      }\n    ");
        }
        return SegmentOpProgram2;
      }()
    );
    function unsortedSegmentSum(args) {
      var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
      var x = inputs.x, segmentIds = inputs.segmentIds;
      var numSegments = attrs.numSegments;
      var xRank = x.shape.length;
      var toDispose = [];
      var axis = 0;
      var permutation = tf.backend_util.getAxesPermutation([axis], xRank);
      var permutedX = x;
      if (permutation != null) {
        permutedX = transpose({ inputs: { x }, backend, attrs: { perm: permutation } });
        toDispose.push(permutedX);
        axis = tf.backend_util.getInnerMostAxes(1, xRank)[0];
      }
      var outShape = tf.backend_util.segment_util.computeOutShape(permutedX.shape, axis, numSegments);
      var inSize = tf.util.sizeFromShape([permutedX.shape[axis]]);
      var a2D = reshape({ inputs: { x: permutedX }, backend, attrs: { shape: [-1, inSize] } });
      toDispose.push(a2D);
      var outputDType = tf.sumOutType(x.dtype);
      var segOpCompute = function(x2, segOpType, segmentIds2, dtype, numSegments2) {
        var batchSize = x2.shape[0];
        var inSize2 = x2.shape[1];
        var windowSize = tf.backend_util.segment_util.segOpComputeOptimalWindowSize(inSize2, numSegments2);
        var segOpInfo = { windowSize, inSize: inSize2, batchSize, numSegments: numSegments2 };
        var program = new SegmentOpProgram(segOpInfo, segOpType);
        var output = backend.compileAndRun(program, [x2, segmentIds2], dtype);
        toDispose.push(output);
        if (output.shape[1] === numSegments2) {
          return output;
        }
        var rangeInfo = range({
          backend,
          attrs: { start: 0, stop: numSegments2, step: 1, dtype: "float32" }
        });
        var tileInfo = tile({
          inputs: { x: rangeInfo },
          backend,
          attrs: { reps: [inSize2 / windowSize] }
        });
        toDispose.push(rangeInfo);
        toDispose.push(tileInfo);
        var result2 = segOpCompute(output, segOpType, tileInfo, dtype, numSegments2);
        return result2;
      };
      var segOpResult = segOpCompute(a2D, "unsortedSegmentSum", segmentIds, outputDType, numSegments);
      var reshaped = reshape({ inputs: { x: segOpResult }, backend, attrs: { shape: outShape } });
      var result = reshaped;
      if (permutation != null) {
        toDispose.push(reshaped);
        var perm = tf.backend_util.getUndoAxesPermutation(permutation);
        result = transpose({ inputs: { x: result }, backend, attrs: { perm } });
      }
      toDispose.forEach(function(t) {
        return backend.disposeIntermediateTensorInfo(t);
      });
      return result;
    }
    var unsortedSegmentSumConfig = {
      kernelName: tf.UnsortedSegmentSum,
      backendName: "webgl",
      kernelFunc: unsortedSegmentSum
    };
    var e_1;
    var _a;
    var kernelConfigs = [
      _fusedMatMulConfig,
      absConfig,
      acosConfig,
      acoshConfig,
      addConfig,
      addNConfig,
      allConfig,
      anyConfig,
      argMaxConfig,
      argMinConfig,
      asinConfig,
      asinhConfig,
      atanConfig,
      atan2Config,
      atanhConfig,
      avgPoolConfig,
      avgPool3DConfig,
      avgPool3DGradConfig,
      avgPoolGradConfig,
      batchMatMulConfig,
      batchNormConfig,
      batchToSpaceNDConfig,
      bincountConfig,
      bitwiseAndConfig,
      broadcastArgsConfig,
      castConfig,
      ceilConfig,
      clipByValueConfig,
      complexConfig,
      complexAbsConfig,
      concatConfig,
      conv2DConfig,
      conv2DBackpropFilterConfig,
      conv2DBackpropInputConfig,
      conv3DConfig,
      conv3DBackpropFilterV2Config,
      conv3DBackpropInputConfig,
      cosConfig,
      coshConfig,
      cropAndResizeConfig,
      cumprodConfig,
      cumsumConfig,
      denseBincountConfig,
      depthToSpaceConfig,
      depthwiseConv2dNativeConfig,
      depthwiseConv2dNativeBackpropFilterConfig,
      depthwiseConv2dNativeBackpropInputConfig,
      diagConfig,
      dilation2DConfig,
      einsumConfig,
      eluConfig,
      eluGradConfig,
      equalConfig,
      erfConfig,
      expConfig,
      expandDimsConfig,
      expm1Config,
      fftConfig,
      fillConfig,
      flipLeftRightConfig,
      floorConfig,
      floorDivConfig,
      fromPixelsConfig,
      fusedConv2DConfig,
      fusedDepthwiseConv2DConfig,
      gatherNdConfig,
      gatherV2Config,
      greaterConfig,
      greaterEqualConfig,
      identityConfig,
      ifftConfig,
      imagConfig,
      isFiniteConfig,
      isInfConfig,
      isNaNConfig,
      leakyReluConfig,
      lessConfig,
      lessEqualConfig,
      linSpaceConfig,
      logConfig,
      log1pConfig,
      logicalAndConfig,
      logicalNotConfig,
      logicalOrConfig,
      LRNConfig,
      LRNGradConfig,
      maxConfig,
      maximumConfig,
      maxPoolConfig,
      maxPool3DConfig,
      maxPool3DGradConfig,
      maxPoolGradConfig,
      maxPoolWithArgmaxConfig,
      meanConfig,
      minConfig,
      minimumConfig,
      mirrorPadConfig,
      modConfig,
      multinomialConfig,
      multiplyConfig,
      negConfig,
      nonMaxSuppressionV3Config,
      nonMaxSuppressionV4Config,
      nonMaxSuppressionV5Config,
      notEqualConfig,
      oneHotConfig,
      onesLikeConfig,
      packConfig,
      padV2Config,
      powConfig,
      preluConfig,
      prodConfig,
      raggedGatherConfig,
      raggedRangeConfig,
      raggedTensorToTensorConfig,
      rangeConfig,
      realConfig,
      realDivConfig,
      reciprocalConfig,
      reluConfig,
      relu6Config,
      reshapeConfig,
      resizeBilinearConfig,
      resizeBilinearGradConfig,
      resizeNearestNeighborConfig,
      resizeNearestNeighborGradConfig,
      reverseConfig,
      rotateWithOffsetConfig,
      roundConfig,
      rsqrtConfig,
      scatterNdConfig,
      searchSortedConfig,
      selectConfig,
      seluConfig,
      sigmoidConfig,
      signConfig,
      sinConfig,
      sinhConfig,
      sliceConfig,
      softmaxConfig,
      softplusConfig,
      spaceToBatchNDConfig,
      sparseFillEmptyRowsConfig,
      sparseReshapeConfig,
      sparseSegmentMeanConfig,
      sparseSegmentSumConfig,
      sparseToDenseConfig,
      splitVConfig,
      sqrtConfig,
      squareConfig,
      squaredDifferenceConfig,
      staticRegexReplaceConfig,
      stepConfig,
      stridedSliceConfig,
      stringNGramsConfig,
      stringSplitConfig,
      stringToHashBucketFastConfig,
      subConfig,
      sumConfig,
      tanConfig,
      tanhConfig,
      tensorScatterUpdateConfig,
      tileConfig,
      topKConfig,
      transformConfig,
      transposeConfig,
      uniqueConfig,
      unpackConfig,
      unsortedSegmentSumConfig,
      zerosLikeConfig
    ];
    try {
      for (kernelConfigs_1 = __values(kernelConfigs), kernelConfigs_1_1 = kernelConfigs_1.next(); !kernelConfigs_1_1.done; kernelConfigs_1_1 = kernelConfigs_1.next()) {
        kernelConfig = kernelConfigs_1_1.value;
        tf.registerKernel(kernelConfig);
      }
    } catch (e_1_1) {
      e_1 = { error: e_1_1 };
    } finally {
      try {
        if (kernelConfigs_1_1 && !kernelConfigs_1_1.done && (_a = kernelConfigs_1.return)) _a.call(kernelConfigs_1);
      } finally {
        if (e_1) throw e_1.error;
      }
    }
    var kernelConfig;
    var kernelConfigs_1;
    var kernelConfigs_1_1;
    exports2.GPGPUContext = GPGPUContext;
    exports2.MathBackendWebGL = MathBackendWebGL;
    exports2.forceHalfFloat = forceHalfFloat;
    exports2.gpgpu_util = gpgpu_util;
    exports2.setWebGLContext = setWebGLContext;
    exports2.version_webgl = version;
    exports2.webgl = webgl;
    exports2.webgl_util = webgl_util;
  }
});

// node_modules/@tensorflow/tfjs/dist/tf.node.js
var require_tf_node = __commonJS({
  "node_modules/@tensorflow/tfjs/dist/tf.node.js"(exports2) {
    "use strict";
    var tfjsCore = require_tf_core_node();
    var LongExports = require_long();
    var tfjsLayers = require_tf_layers_node();
    var tfjsConverter = require_tf_converter_node();
    var tfjsData = require_tf_data_node();
    var tfjsBackendCpu = require_tf_backend_cpu_node();
    var tfjsBackendWebgl = require_tf_backend_webgl_node();
    function _interopNamespaceDefault(e) {
      var n = /* @__PURE__ */ Object.create(null);
      if (e) {
        Object.keys(e).forEach(function(k) {
          if (k !== "default") {
            var d = Object.getOwnPropertyDescriptor(e, k);
            Object.defineProperty(n, k, d.get ? d : {
              enumerable: true,
              get: function() {
                return e[k];
              }
            });
          }
        });
      }
      n.default = e;
      return n;
    }
    var LongExports__namespace = /* @__PURE__ */ _interopNamespaceDefault(LongExports);
    var tfjsData__namespace = /* @__PURE__ */ _interopNamespaceDefault(tfjsData);
    var Abs = "Abs";
    var Acos = "Acos";
    var Acosh = "Acosh";
    var Add = "Add";
    var AddN = "AddN";
    var All = "All";
    var Any = "Any";
    var ArgMax = "ArgMax";
    var ArgMin = "ArgMin";
    var Asin = "Asin";
    var Asinh = "Asinh";
    var Atan = "Atan";
    var Atanh = "Atanh";
    var Atan2 = "Atan2";
    var AvgPool = "AvgPool";
    var AvgPoolGrad = "AvgPoolGrad";
    var AvgPool3D = "AvgPool3D";
    var AvgPool3DGrad = "AvgPool3DGrad";
    var BatchMatMul = "BatchMatMul";
    var BatchToSpaceND = "BatchToSpaceND";
    var BroadcastTo = "BroadcastTo";
    var Cast = "Cast";
    var Ceil = "Ceil";
    var ClipByValue = "ClipByValue";
    var Complex = "Complex";
    var ComplexAbs = "ComplexAbs";
    var Concat = "Concat";
    var Conv2D = "Conv2D";
    var Conv2DBackpropFilter = "Conv2DBackpropFilter";
    var Conv2DBackpropInput = "Conv2DBackpropInput";
    var Conv3D = "Conv3D";
    var Conv3DBackpropFilterV2 = "Conv3DBackpropFilterV2";
    var Conv3DBackpropInputV2 = "Conv3DBackpropInputV2";
    var Cos = "Cos";
    var Cosh = "Cosh";
    var Cumprod = "Cumprod";
    var Cumsum = "Cumsum";
    var DepthToSpace = "DepthToSpace";
    var DepthwiseConv2dNative = "DepthwiseConv2dNative";
    var DepthwiseConv2dNativeBackpropFilter = "DepthwiseConv2dNativeBackpropFilter";
    var DepthwiseConv2dNativeBackpropInput = "DepthwiseConv2dNativeBackpropInput";
    var Dilation2D = "Dilation2D";
    var Dilation2DBackpropInput = "Dilation2DBackpropInput";
    var Dilation2DBackpropFilter = "Dilation2DBackpropFilter";
    var RealDiv = "RealDiv";
    var Elu = "Elu";
    var EluGrad = "EluGrad";
    var Erf = "Erf";
    var Equal = "Equal";
    var Exp = "Exp";
    var ExpandDims = "ExpandDims";
    var Expm1 = "Expm1";
    var FFT = "FFT";
    var Fill = "Fill";
    var Floor = "Floor";
    var FloorDiv = "FloorDiv";
    var FusedBatchNorm = "FusedBatchNorm";
    var GatherV2 = "GatherV2";
    var Greater = "Greater";
    var GreaterEqual = "GreaterEqual";
    var Identity = "Identity";
    var IFFT = "IFFT";
    var Imag = "Imag";
    var IsFinite = "IsFinite";
    var IsInf = "IsInf";
    var IsNan = "IsNan";
    var LeakyRelu = "LeakyRelu";
    var Less = "Less";
    var LessEqual = "LessEqual";
    var Log = "Log";
    var Log1p = "Log1p";
    var LogicalAnd = "LogicalAnd";
    var LogicalNot = "LogicalNot";
    var LogicalOr = "LogicalOr";
    var LogSoftmax = "LogSoftmax";
    var LRN = "LRN";
    var LRNGrad = "LRNGrad";
    var Max = "Max";
    var Maximum = "Maximum";
    var MaxPool = "MaxPool";
    var MaxPoolGrad = "MaxPoolGrad";
    var MaxPool3D = "MaxPool3D";
    var MaxPool3DGrad = "MaxPool3DGrad";
    var Mean = "Mean";
    var Min = "Min";
    var Minimum = "Minimum";
    var MirrorPad = "MirrorPad";
    var Mod = "Mod";
    var Multiply = "Multiply";
    var Neg = "Neg";
    var NotEqual = "NotEqual";
    var OnesLike = "OnesLike";
    var OneHot = "OneHot";
    var Pack = "Pack";
    var PadV2 = "PadV2";
    var Pow = "Pow";
    var Prelu = "Prelu";
    var Prod = "Prod";
    var Real = "Real";
    var Reciprocal = "Reciprocal";
    var Relu = "Relu";
    var Reshape = "Reshape";
    var ResizeNearestNeighbor = "ResizeNearestNeighbor";
    var ResizeNearestNeighborGrad = "ResizeNearestNeighborGrad";
    var ResizeBilinear = "ResizeBilinear";
    var ResizeBilinearGrad = "ResizeBilinearGrad";
    var Relu6 = "Relu6";
    var Reverse = "Reverse";
    var Round = "Round";
    var Rsqrt = "Rsqrt";
    var TensorScatterUpdate = "TensorScatterUpdate";
    var Select = "Select";
    var Selu = "Selu";
    var Slice = "Slice";
    var Sin = "Sin";
    var Sinh = "Sinh";
    var Sign = "Sign";
    var Sigmoid = "Sigmoid";
    var Softplus = "Softplus";
    var Sqrt = "Sqrt";
    var Sum = "Sum";
    var SpaceToBatchND = "SpaceToBatchND";
    var SplitV = "SplitV";
    var Softmax = "Softmax";
    var SquaredDifference = "SquaredDifference";
    var Square = "Square";
    var StridedSlice = "StridedSlice";
    var Sub = "Sub";
    var Tan = "Tan";
    var Tanh = "Tanh";
    var Tile = "Tile";
    var TopK = "TopK";
    var Transpose = "Transpose";
    var Unique = "Unique";
    var Unpack = "Unpack";
    var UnsortedSegmentSum = "UnsortedSegmentSum";
    var ZerosLike = "ZerosLike";
    var Step = "Step";
    var EPSILON_FLOAT32 = 1e-7;
    var EPSILON_FLOAT16 = 1e-4;
    var KernelBackend = class {
      refCount(dataId) {
        return notYetImplemented("refCount");
      }
      incRef(dataId) {
        return notYetImplemented("incRef");
      }
      timerAvailable() {
        return true;
      }
      time(f) {
        return notYetImplemented("time");
      }
      read(dataId) {
        return notYetImplemented("read");
      }
      readSync(dataId) {
        return notYetImplemented("readSync");
      }
      readToGPU(dataId, options) {
        return notYetImplemented("readToGPU");
      }
      numDataIds() {
        return notYetImplemented("numDataIds");
      }
      disposeData(dataId, force) {
        return notYetImplemented("disposeData");
      }
      write(values, shape, dtype) {
        return notYetImplemented("write");
      }
      move(dataId, values, shape, dtype, refCount) {
        return notYetImplemented("move");
      }
      createTensorFromGPUData(values, shape, dtype) {
        return notYetImplemented("createTensorFromGPUData");
      }
      memory() {
        return notYetImplemented("memory");
      }
      /** Returns the highest precision for floats in bits (e.g. 16 or 32) */
      floatPrecision() {
        return notYetImplemented("floatPrecision");
      }
      /** Returns the smallest representable number.  */
      epsilon() {
        return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;
      }
      dispose() {
        return notYetImplemented("dispose");
      }
    };
    function notYetImplemented(kernelName) {
      throw new Error(`'${kernelName}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`);
    }
    function assert(expr, msg) {
      if (!expr) {
        throw new Error(typeof msg === "string" ? msg : msg());
      }
    }
    function assertShapesMatch(shapeA, shapeB, errorMessagePrefix = "") {
      assert(arraysEqual(shapeA, shapeB), () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);
    }
    function sizeFromShape(shape) {
      if (shape.length === 0) {
        return 1;
      }
      let size = shape[0];
      for (let i = 1; i < shape.length; i++) {
        size *= shape[i];
      }
      return size;
    }
    function arraysEqual(n1, n2) {
      if (n1 === n2) {
        return true;
      }
      if (n1 == null || n2 == null) {
        return false;
      }
      if (n1.length !== n2.length) {
        return false;
      }
      for (let i = 0; i < n1.length; i++) {
        if (n1[i] !== n2[i]) {
          return false;
        }
      }
      return true;
    }
    function isInt(a) {
      return a % 1 === 0;
    }
    function rightPad(a, size) {
      if (size <= a.length) {
        return a;
      }
      return a + " ".repeat(size - a.length);
    }
    function parseAxisParam(axis, shape) {
      const rank = shape.length;
      axis = axis == null ? shape.map((s, i) => i) : [].concat(axis);
      assert(axis.every((ax) => ax >= -rank && ax < rank), () => `All values in axis param must be in range [-${rank}, ${rank}) but got axis ${axis}`);
      assert(axis.every((ax) => isInt(ax)), () => `All values in axis param must be integers but got axis ${axis}`);
      return axis.map((a) => a < 0 ? rank + a : a);
    }
    function squeezeShape(shape, axis) {
      const newShape = [];
      const keptDims = [];
      const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;
      const axes = axis == null || isEmptyArray ? null : parseAxisParam(axis, shape).sort();
      let j = 0;
      for (let i = 0; i < shape.length; ++i) {
        if (axes != null) {
          if (axes[j] === i && shape[i] !== 1) {
            throw new Error(`Can't squeeze axis ${i} since its dim '${shape[i]}' is not 1`);
          }
          if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {
            newShape.push(shape[i]);
            keptDims.push(i);
          }
          if (axes[j] <= i) {
            j++;
          }
        }
        if (shape[i] !== 1) {
          newShape.push(shape[i]);
          keptDims.push(i);
        }
      }
      return { newShape, keptDims };
    }
    function checkConversionForErrors(vals, dtype) {
      for (let i = 0; i < vals.length; i++) {
        const num = vals[i];
        if (isNaN(num) || !isFinite(num)) {
          throw Error(`A tensor of type ${dtype} being uploaded contains ${num}.`);
        }
      }
    }
    function isValidDtype(dtype) {
      return dtype === "bool" || dtype === "complex64" || dtype === "float32" || dtype === "int32" || dtype === "string";
    }
    function bytesPerElement(dtype) {
      if (dtype === "float32" || dtype === "int32") {
        return 4;
      } else if (dtype === "complex64") {
        return 8;
      } else if (dtype === "bool") {
        return 1;
      } else {
        throw new Error(`Unknown dtype ${dtype}`);
      }
    }
    function bytesFromStringArray(arr) {
      if (arr == null) {
        return 0;
      }
      let bytes = 0;
      arr.forEach((x) => bytes += x.length);
      return bytes;
    }
    function isString(value) {
      return typeof value === "string" || value instanceof String;
    }
    function isBoolean(value) {
      return typeof value === "boolean";
    }
    function isNumber(value) {
      return typeof value === "number";
    }
    function inferDtype(values) {
      if (Array.isArray(values)) {
        return inferDtype(values[0]);
      }
      if (values instanceof Float32Array) {
        return "float32";
      } else if (values instanceof Int32Array || values instanceof Uint8Array || values instanceof Uint8ClampedArray) {
        return "int32";
      } else if (isNumber(values)) {
        return "float32";
      } else if (isString(values)) {
        return "string";
      } else if (isBoolean(values)) {
        return "bool";
      }
      return "float32";
    }
    function isFunction(f) {
      return !!(f && f.constructor && f.call && f.apply);
    }
    function computeStrides(shape) {
      const rank = shape.length;
      if (rank < 2) {
        return [];
      }
      const strides = new Array(rank - 1);
      strides[rank - 2] = shape[rank - 1];
      for (let i = rank - 3; i >= 0; --i) {
        strides[i] = strides[i + 1] * shape[i + 1];
      }
      return strides;
    }
    function createNestedArray(offset, shape, a, isComplex = false) {
      const ret = new Array();
      if (shape.length === 1) {
        const d = shape[0] * (isComplex ? 2 : 1);
        for (let i = 0; i < d; i++) {
          ret[i] = a[offset + i];
        }
      } else {
        const d = shape[0];
        const rest = shape.slice(1);
        const len = rest.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);
        for (let i = 0; i < d; i++) {
          ret[i] = createNestedArray(offset + i * len, rest, a, isComplex);
        }
      }
      return ret;
    }
    function toNestedArray(shape, a, isComplex = false) {
      if (shape.length === 0) {
        return a[0];
      }
      const size = shape.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);
      if (size === 0) {
        return [];
      }
      if (size !== a.length) {
        throw new Error(`[${shape}] does not match the input size ${a.length}${isComplex ? " for a complex tensor" : ""}.`);
      }
      return createNestedArray(0, shape, a, isComplex);
    }
    function makeOnesTypedArray(size, dtype) {
      const array = makeZerosTypedArray(size, dtype);
      for (let i = 0; i < array.length; i++) {
        array[i] = 1;
      }
      return array;
    }
    function makeZerosTypedArray(size, dtype) {
      if (dtype == null || dtype === "float32" || dtype === "complex64") {
        return new Float32Array(size);
      } else if (dtype === "int32") {
        return new Int32Array(size);
      } else if (dtype === "bool") {
        return new Uint8Array(size);
      } else {
        throw new Error(`Unknown data type ${dtype}`);
      }
    }
    function assertNonNegativeIntegerDimensions(shape) {
      shape.forEach((dimSize) => {
        assert(Number.isInteger(dimSize) && dimSize >= 0, () => `Tensor must have a shape comprised of positive integers but got shape [${shape}].`);
      });
    }
    function isPromise(object) {
      return object && object.then && typeof object.then === "function";
    }
    var TENSORFLOWJS_FLAGS_PREFIX = "tfjsflags";
    var Environment = class {
      // tslint:disable-next-line: no-any
      constructor(global2) {
        this.global = global2;
        this.flags = {};
        this.flagRegistry = {};
        this.urlFlags = {};
        this.getQueryParams = getQueryParams;
        this.populateURLFlags();
      }
      setPlatform(platformName, platform) {
        if (this.platform != null) {
          if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) {
            console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${platformName}.`);
          }
        }
        this.platformName = platformName;
        this.platform = platform;
      }
      registerFlag(flagName, evaluationFn, setHook) {
        this.flagRegistry[flagName] = { evaluationFn, setHook };
        if (this.urlFlags[flagName] != null) {
          const flagValue = this.urlFlags[flagName];
          if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) {
            console.warn(`Setting feature override from URL ${flagName}: ${flagValue}.`);
          }
          this.set(flagName, flagValue);
        }
      }
      async getAsync(flagName) {
        if (flagName in this.flags) {
          return this.flags[flagName];
        }
        this.flags[flagName] = await this.evaluateFlag(flagName);
        return this.flags[flagName];
      }
      get(flagName) {
        if (flagName in this.flags) {
          return this.flags[flagName];
        }
        const flagValue = this.evaluateFlag(flagName);
        if (isPromise(flagValue)) {
          throw new Error(`Flag ${flagName} cannot be synchronously evaluated. Please use getAsync() instead.`);
        }
        this.flags[flagName] = flagValue;
        return this.flags[flagName];
      }
      getNumber(flagName) {
        return this.get(flagName);
      }
      getBool(flagName) {
        return this.get(flagName);
      }
      getString(flagName) {
        return this.get(flagName);
      }
      getFlags() {
        return this.flags;
      }
      // For backwards compatibility.
      get features() {
        return this.flags;
      }
      set(flagName, value) {
        if (this.flagRegistry[flagName] == null) {
          throw new Error(`Cannot set flag ${flagName} as it has not been registered.`);
        }
        this.flags[flagName] = value;
        if (this.flagRegistry[flagName].setHook != null) {
          this.flagRegistry[flagName].setHook(value);
        }
      }
      evaluateFlag(flagName) {
        if (this.flagRegistry[flagName] == null) {
          throw new Error(`Cannot evaluate flag '${flagName}': no evaluation function found.`);
        }
        return this.flagRegistry[flagName].evaluationFn();
      }
      setFlags(flags) {
        this.flags = Object.assign({}, flags);
      }
      reset() {
        this.flags = {};
        this.urlFlags = {};
        this.populateURLFlags();
      }
      populateURLFlags() {
        if (typeof this.global === "undefined" || typeof this.global.location === "undefined" || typeof this.global.location.search === "undefined") {
          return;
        }
        const urlParams = this.getQueryParams(this.global.location.search);
        if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {
          const keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(",");
          keyValues.forEach((keyValue) => {
            const [key, value] = keyValue.split(":");
            this.urlFlags[key] = parseValue(key, value);
          });
        }
      }
    };
    function getQueryParams(queryString) {
      const params = {};
      queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (s, ...t) => {
        decodeParam(params, t[0], t[1]);
        return t.join("=");
      });
      return params;
    }
    function decodeParam(params, name, value) {
      params[decodeURIComponent(name)] = decodeURIComponent(value || "");
    }
    function parseValue(flagName, value) {
      const lowerCaseValue = value.toLowerCase();
      if (lowerCaseValue === "true" || lowerCaseValue === "false") {
        return lowerCaseValue === "true";
      } else if (`${+lowerCaseValue}` === lowerCaseValue) {
        return +lowerCaseValue;
      } else {
        return value;
      }
    }
    function env() {
      return ENV$1;
    }
    var ENV$1 = null;
    function setEnvironmentGlobal(environment) {
      ENV$1 = environment;
    }
    var globalNameSpace;
    function getGlobalNamespace() {
      if (globalNameSpace == null) {
        let ns;
        if (typeof window !== "undefined") {
          ns = window;
        } else if (typeof global !== "undefined") {
          ns = global;
        } else if (typeof process !== "undefined") {
          ns = process;
        } else if (typeof self !== "undefined") {
          ns = self;
        } else {
          throw new Error("Could not find a global object");
        }
        globalNameSpace = ns;
      }
      return globalNameSpace;
    }
    function getGlobalMap() {
      const ns = getGlobalNamespace();
      if (ns._tfGlobals == null) {
        ns._tfGlobals = /* @__PURE__ */ new Map();
      }
      return ns._tfGlobals;
    }
    function getGlobal(key, init) {
      const globalMap = getGlobalMap();
      if (globalMap.has(key)) {
        return globalMap.get(key);
      } else {
        const singleton = init();
        globalMap.set(key, singleton);
        return globalMap.get(key);
      }
    }
    function warn(...msg) {
      if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) {
        console.warn(...msg);
      }
    }
    var kernelRegistry = getGlobal("kernelRegistry", () => /* @__PURE__ */ new Map());
    var gradRegistry = getGlobal("gradRegistry", () => /* @__PURE__ */ new Map());
    function getKernel(kernelName, backendName) {
      const key = makeKey(kernelName, backendName);
      return kernelRegistry.get(key);
    }
    function getGradient(kernelName) {
      return gradRegistry.get(kernelName);
    }
    function getKernelsForBackend(backendName) {
      const it = kernelRegistry.entries();
      const result = [];
      while (true) {
        const { done, value } = it.next();
        if (done) {
          break;
        }
        const [key, config] = value;
        const [backend2] = key.split("_");
        if (backend2 === backendName) {
          result.push(config);
        }
      }
      return result;
    }
    function registerGradient(config) {
      const { kernelName } = config;
      if (gradRegistry.has(kernelName)) {
        if (env().getBool("DEBUG")) {
          warn(`Overriding the gradient for '${kernelName}'`);
        }
      }
      gradRegistry.set(kernelName, config);
    }
    function makeKey(kernelName, backendName) {
      return `${backendName}_${kernelName}`;
    }
    function isTypedArrayBrowser(a) {
      return a instanceof Float32Array || a instanceof Int32Array || a instanceof Uint8Array || a instanceof Uint8ClampedArray;
    }
    var Long = (
      // tslint:disable-next-line
      LongExports__namespace.default || LongExports__namespace
    );
    function hexToLong(hex) {
      return Long.fromString(hex, true, 16);
    }
    var k0 = hexToLong("c3a5c85c97cb3127");
    var k1 = hexToLong("b492b66fbe98f273");
    var k2 = hexToLong("9ae16a3b2f90404f");
    function noConversionNeeded(a, dtype) {
      return a instanceof Float32Array && dtype === "float32" || a instanceof Int32Array && dtype === "int32" || a instanceof Uint8Array && dtype === "bool";
    }
    function toTypedArray(a, dtype) {
      if (dtype === "string") {
        throw new Error("Cannot convert a string[] to a TypedArray");
      }
      if (Array.isArray(a)) {
        a = flatten(a);
      }
      if (env().getBool("DEBUG")) {
        checkConversionForErrors(a, dtype);
      }
      if (noConversionNeeded(a, dtype)) {
        return a;
      }
      if (dtype == null || dtype === "float32" || dtype === "complex64") {
        return new Float32Array(a);
      } else if (dtype === "int32") {
        return new Int32Array(a);
      } else if (dtype === "bool") {
        const bool = new Uint8Array(a.length);
        for (let i = 0; i < bool.length; ++i) {
          if (Math.round(a[i]) !== 0) {
            bool[i] = 1;
          }
        }
        return bool;
      } else {
        throw new Error(`Unknown data type ${dtype}`);
      }
    }
    function now() {
      return env().platform.now();
    }
    function encodeString(s, encoding = "utf-8") {
      encoding = encoding || "utf-8";
      return env().platform.encode(s, encoding);
    }
    function decodeString(bytes, encoding = "utf-8") {
      encoding = encoding || "utf-8";
      return env().platform.decode(bytes, encoding);
    }
    function isTypedArray(a) {
      if (env().platform.isTypedArray != null) {
        return env().platform.isTypedArray(a);
      } else {
        return isTypedArrayBrowser(a);
      }
    }
    function flatten(arr, result = [], skipTypedArray = false) {
      if (result == null) {
        result = [];
      }
      if (typeof arr === "boolean" || typeof arr === "number" || typeof arr === "string" || isPromise(arr) || arr == null || isTypedArray(arr) && skipTypedArray) {
        result.push(arr);
      } else if (Array.isArray(arr) || isTypedArray(arr)) {
        for (let i = 0; i < arr.length; ++i) {
          flatten(arr[i], result, skipTypedArray);
        }
      } else {
        let maxIndex = -1;
        for (const key of Object.keys(arr)) {
          if (/^([1-9]+[0-9]*|0)$/.test(key)) {
            maxIndex = Math.max(maxIndex, Number(key));
          }
        }
        for (let i = 0; i <= maxIndex; i++) {
          flatten(arr[i], result, skipTypedArray);
        }
      }
      return result;
    }
    var Profiler = class {
      constructor(backendTimer, logger) {
        this.backendTimer = backendTimer;
        this.logger = logger;
        if (logger == null) {
          this.logger = new Logger();
        }
      }
      profileKernel(kernelName, inputs, f) {
        let outputs;
        const holdResultWrapperFn = () => {
          outputs = f();
        };
        let timer;
        const start = now();
        if (this.backendTimer.timerAvailable()) {
          timer = this.backendTimer.time(holdResultWrapperFn);
        } else {
          holdResultWrapperFn();
          for (const output of outputs) {
            output.dataSync();
          }
          timer = Promise.resolve({ kernelMs: now() - start });
        }
        if (env().getBool("CHECK_COMPUTATION_FOR_ERRORS")) {
          for (let i = 0; i < outputs.length; i++) {
            const output = outputs[i];
            output.data().then((tensorVals) => {
              checkComputationForErrors(tensorVals, output.dtype, kernelName);
            });
          }
        }
        const kernelProfile = {
          kernelName,
          outputs,
          inputs,
          timeMs: timer.then((timing) => timing.kernelMs),
          extraInfo: timer.then((timing) => timing.getExtraProfileInfo != null ? timing.getExtraProfileInfo() : "")
        };
        return kernelProfile;
      }
      logKernelProfile(kernelProfile) {
        const { kernelName, outputs, timeMs, inputs, extraInfo } = kernelProfile;
        outputs.forEach((result) => {
          Promise.all([result.data(), timeMs, extraInfo]).then((valueContainer) => {
            this.logger.logKernelProfile(kernelName, result, valueContainer[0], valueContainer[1], inputs, valueContainer[2]);
          });
        });
      }
    };
    function checkComputationForErrors(vals, dtype, kernelName) {
      if (dtype !== "float32") {
        return false;
      }
      for (let i = 0; i < vals.length; i++) {
        const num = vals[i];
        if (isNaN(num) || !isFinite(num)) {
          console.warn(`Found ${num} in the result of '${kernelName}'`);
          return true;
        }
      }
      return false;
    }
    var Logger = class {
      logKernelProfile(name, result, vals, timeMs, inputs, extraInfo) {
        const time2 = typeof timeMs === "number" ? rightPad(`${timeMs}ms`, 9) : timeMs["error"];
        const paddedName = rightPad(name, 25);
        const rank = result.rank;
        const size = result.size;
        const shape = rightPad(result.shape.toString(), 14);
        let inputShapesDescription = "";
        for (const name2 in inputs) {
          const input = inputs[name2];
          if (input != null) {
            const inputShape = input.shape || result.shape;
            const inputRank = inputShape.length;
            inputShapesDescription += `${name2}: ${inputRank}D ${inputRank > 0 ? inputShape : ""} `;
          }
        }
        console.log(`%c${paddedName}	%c${time2}	%c${rank}D ${shape}	%c${size}	%c${inputShapesDescription}	%c${extraInfo}`, "font-weight:bold", "color:red", "color:blue", "color: orange", "color: green", "color: steelblue");
      }
    };
    function getFilteredNodesXToY(tape, xs, y) {
      const tensorsFromX = {};
      const nodesFromX = {};
      for (let i = 0; i < xs.length; i++) {
        tensorsFromX[xs[i].id] = true;
      }
      for (let i = 0; i < tape.length; i++) {
        const node = tape[i];
        const nodeInputs = node.inputs;
        for (const inputName in nodeInputs) {
          const input = nodeInputs[inputName];
          let anyInputFromX = false;
          for (let j = 0; j < xs.length; j++) {
            if (tensorsFromX[input.id]) {
              node.outputs.forEach((output) => tensorsFromX[output.id] = true);
              anyInputFromX = true;
              nodesFromX[node.id] = true;
              break;
            }
          }
          if (anyInputFromX) {
            break;
          }
        }
      }
      const tensorsLeadToY = {};
      tensorsLeadToY[y.id] = true;
      const nodesToY = {};
      for (let i = tape.length - 1; i >= 0; i--) {
        const node = tape[i];
        const nodeInputs = node.inputs;
        for (let j = 0; j < node.outputs.length; j++) {
          if (tensorsLeadToY[node.outputs[j].id]) {
            for (const inputName in nodeInputs) {
              tensorsLeadToY[nodeInputs[inputName].id] = true;
              nodesToY[node.id] = true;
            }
            break;
          }
        }
      }
      const filteredTape = [];
      for (let i = 0; i < tape.length; i++) {
        const node = tape[i];
        if (nodesFromX[node.id] && nodesToY[node.id]) {
          const prunedInputs = {};
          for (const inputName in node.inputs) {
            const nodeInput = node.inputs[inputName];
            if (tensorsFromX[nodeInput.id]) {
              prunedInputs[inputName] = nodeInput;
            }
          }
          const prunedNode = Object.assign({}, node);
          prunedNode.inputs = prunedInputs;
          prunedNode.outputs = node.outputs;
          filteredTape.push(prunedNode);
        }
      }
      return filteredTape;
    }
    function backpropagateGradients(tensorAccumulatedGradientMap, filteredTape, tidy2, add2) {
      for (let i = filteredTape.length - 1; i >= 0; i--) {
        const node = filteredTape[i];
        const dys = [];
        node.outputs.forEach((o) => {
          const gradTensor = tensorAccumulatedGradientMap[o.id];
          if (gradTensor != null) {
            dys.push(gradTensor);
          } else {
            dys.push(null);
          }
        });
        if (node.gradient == null) {
          throw new Error(`Cannot compute gradient: gradient function not found for ${node.kernelName}.`);
        }
        const inputGradients = node.gradient(dys);
        for (const inputName in node.inputs) {
          if (!(inputName in inputGradients)) {
            throw new Error(`Cannot backprop through input ${inputName}. Available gradients found: ${Object.keys(inputGradients)}.`);
          }
          const dx = tidy2(() => inputGradients[inputName]());
          if (dx.dtype !== "float32") {
            throw new Error(`Error in gradient for op ${node.kernelName}. The gradient of input ${inputName} must have 'float32' dtype, but has '${dx.dtype}'`);
          }
          const x = node.inputs[inputName];
          if (!arraysEqual(dx.shape, x.shape)) {
            throw new Error(`Error in gradient for op ${node.kernelName}. The gradient of input '${inputName}' has shape '${dx.shape}', which does not match the shape of the input '${x.shape}'`);
          }
          if (tensorAccumulatedGradientMap[x.id] == null) {
            tensorAccumulatedGradientMap[x.id] = dx;
          } else {
            const curGradient = tensorAccumulatedGradientMap[x.id];
            tensorAccumulatedGradientMap[x.id] = add2(curGradient, dx);
            curGradient.dispose();
          }
        }
      }
    }
    var FORMAT_LIMIT_NUM_VALS = 20;
    var FORMAT_NUM_FIRST_LAST_VALS = 3;
    var FORMAT_NUM_SIG_DIGITS = 7;
    function tensorToString(vals, shape, dtype, verbose) {
      const strides = computeStrides(shape);
      const padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides);
      const rank = shape.length;
      const valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol);
      const lines = ["Tensor"];
      if (verbose) {
        lines.push(`  dtype: ${dtype}`);
        lines.push(`  rank: ${rank}`);
        lines.push(`  shape: [${shape}]`);
        lines.push(`  values:`);
      }
      lines.push(valsLines.map((l) => "    " + l).join("\n"));
      return lines.join("\n");
    }
    function computeMaxSizePerColumn(vals, shape, dtype, strides) {
      const n = sizeFromShape(shape);
      const numCols = strides[strides.length - 1];
      const padPerCol = new Array(numCols).fill(0);
      const rank = shape.length;
      const valuesOrTuples = dtype === "complex64" ? createComplexTuples(vals) : vals;
      if (rank > 1) {
        for (let row = 0; row < n / numCols; row++) {
          const offset = row * numCols;
          for (let j = 0; j < numCols; j++) {
            padPerCol[j] = Math.max(padPerCol[j], valToString(valuesOrTuples[offset + j], 0, dtype).length);
          }
        }
      }
      return padPerCol;
    }
    function valToString(val, pad2, dtype) {
      let valStr;
      if (Array.isArray(val)) {
        valStr = `${parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS))} + ${parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS))}j`;
      } else if (isString(val)) {
        valStr = `'${val}'`;
      } else if (dtype === "bool") {
        valStr = boolNumToString(val);
      } else {
        valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString();
      }
      return rightPad(valStr, pad2);
    }
    function boolNumToString(v) {
      return v === 0 ? "false" : "true";
    }
    function subTensorToString(vals, shape, dtype, strides, padPerCol, isLast = true) {
      const storagePerElement = dtype === "complex64" ? 2 : 1;
      const size = shape[0];
      const rank = shape.length;
      if (rank === 0) {
        if (dtype === "complex64") {
          const complexTuple = createComplexTuples(vals);
          return [valToString(complexTuple[0], 0, dtype)];
        }
        if (dtype === "bool") {
          return [boolNumToString(vals[0])];
        }
        return [vals[0].toString()];
      }
      if (rank === 1) {
        if (size > FORMAT_LIMIT_NUM_VALS) {
          const firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement;
          let firstVals = Array.from(vals.slice(0, firstValsSize));
          let lastVals = Array.from(vals.slice((size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement, size * storagePerElement));
          if (dtype === "complex64") {
            firstVals = createComplexTuples(firstVals);
            lastVals = createComplexTuples(lastVals);
          }
          return [
            "[" + firstVals.map((x, i) => valToString(x, padPerCol[i], dtype)).join(", ") + ", ..., " + lastVals.map((x, i) => valToString(x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i], dtype)).join(", ") + "]"
          ];
        }
        const displayVals = dtype === "complex64" ? createComplexTuples(vals) : Array.from(vals);
        return [
          "[" + displayVals.map((x, i) => valToString(x, padPerCol[i], dtype)).join(", ") + "]"
        ];
      }
      const subshape = shape.slice(1);
      const substrides = strides.slice(1);
      const stride = strides[0] * storagePerElement;
      const lines = [];
      if (size > FORMAT_LIMIT_NUM_VALS) {
        for (let i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {
          const start = i * stride;
          const end = start + stride;
          lines.push(...subTensorToString(
            vals.slice(start, end),
            subshape,
            dtype,
            substrides,
            padPerCol,
            false
            /* isLast */
          ));
        }
        lines.push("...");
        for (let i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {
          const start = i * stride;
          const end = start + stride;
          lines.push(...subTensorToString(
            vals.slice(start, end),
            subshape,
            dtype,
            substrides,
            padPerCol,
            i === size - 1
            /* isLast */
          ));
        }
      } else {
        for (let i = 0; i < size; i++) {
          const start = i * stride;
          const end = start + stride;
          lines.push(...subTensorToString(
            vals.slice(start, end),
            subshape,
            dtype,
            substrides,
            padPerCol,
            i === size - 1
            /* isLast */
          ));
        }
      }
      const sep = rank === 2 ? "," : "";
      lines[0] = "[" + (size > 0 ? lines[0] + sep : "");
      for (let i = 1; i < lines.length - 1; i++) {
        lines[i] = " " + lines[i] + sep;
      }
      let newLineSep = ",\n";
      for (let i = 2; i < rank; i++) {
        newLineSep += "\n";
      }
      lines[lines.length - 1] = " " + lines[lines.length - 1] + "]" + (isLast ? "" : newLineSep);
      return lines;
    }
    function createComplexTuples(vals) {
      const complexTuples = [];
      for (let i = 0; i < vals.length; i += 2) {
        complexTuples.push([vals[i], vals[i + 1]]);
      }
      return complexTuples;
    }
    var trackerFn = null;
    var opHandler = null;
    var deprecationWarningFn = null;
    function setTensorTracker(fn) {
      trackerFn = fn;
    }
    function setDeprecationWarningFn(fn) {
      deprecationWarningFn = fn;
    }
    var Tensor = class {
      constructor(shape, dtype, dataId, id) {
        this.kept = false;
        this.isDisposedInternal = false;
        this.shape = shape.slice();
        this.dtype = dtype || "float32";
        this.size = sizeFromShape(shape);
        this.strides = computeStrides(shape);
        this.dataId = dataId;
        this.id = id;
        this.rankType = this.rank < 5 ? this.rank.toString() : "higher";
      }
      get rank() {
        return this.shape.length;
      }
      /**
       * Returns a promise of `tf.TensorBuffer` that holds the underlying data.
       *
       * @doc {heading: 'Tensors', subheading: 'Classes'}
       */
      async buffer() {
        const vals = await this.data();
        return opHandler.buffer(this.shape, this.dtype, vals);
      }
      /**
       * Returns a `tf.TensorBuffer` that holds the underlying data.
       * @doc {heading: 'Tensors', subheading: 'Classes'}
       */
      bufferSync() {
        return opHandler.buffer(this.shape, this.dtype, this.dataSync());
      }
      /**
       * Returns the tensor data as a nested array. The transfer of data is done
       * asynchronously.
       *
       * @doc {heading: 'Tensors', subheading: 'Classes'}
       */
      async array() {
        const vals = await this.data();
        return toNestedArray(this.shape, vals, this.dtype === "complex64");
      }
      /**
       * Returns the tensor data as a nested array. The transfer of data is done
       * synchronously.
       *
       * @doc {heading: 'Tensors', subheading: 'Classes'}
       */
      arraySync() {
        return toNestedArray(this.shape, this.dataSync(), this.dtype === "complex64");
      }
      /**
       * Asynchronously downloads the values from the `tf.Tensor`. Returns a
       * promise of `TypedArray` that resolves when the computation has finished.
       *
       * @doc {heading: 'Tensors', subheading: 'Classes'}
       */
      async data() {
        this.throwIfDisposed();
        const data = trackerFn().read(this.dataId);
        if (this.dtype === "string") {
          const bytes = await data;
          try {
            return bytes.map((b) => decodeString(b));
          } catch (_a) {
            throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");
          }
        }
        return data;
      }
      /**
       * Copy the tensor's data to a new GPU resource. Comparing to the `dataSync()`
       * and `data()`, this method prevents data from being downloaded to CPU.
       *
       * For WebGL backend, the data will be stored on a densely packed texture.
       * This means that the texture will use the RGBA channels to store value.
       *
       * For WebGPU backend, the data will be stored on a buffer. There is no
       * parameter, so can not use a user-defined size to create the buffer.
       *
       * @param options:
       *     For WebGL,
       *         - customTexShape: Optional. If set, will use the user defined
       *     texture shape to create the texture.
       *
       * @returns For WebGL backend, a GPUData contains the new texture and
       *     its information.
       *     {
       *        tensorRef: The tensor that is associated with this texture,
       *        texture: WebGLTexture,
       *        texShape: [number, number] // [height, width]
       *     }
       *
       *     For WebGPU backend, a GPUData contains the new buffer.
       *     {
       *        tensorRef: The tensor that is associated with this buffer,
       *        buffer: GPUBuffer,
       *     }
       *
       *     Remember to dispose the GPUData after it is used by
       *     `res.tensorRef.dispose()`.
       *
       * @doc {heading: 'Tensors', subheading: 'Classes'}
       */
      dataToGPU(options) {
        this.throwIfDisposed();
        return trackerFn().readToGPU(this.dataId, options);
      }
      /**
       * Synchronously downloads the values from the `tf.Tensor`. This blocks the
       * UI thread until the values are ready, which can cause performance issues.
       *
       * @doc {heading: 'Tensors', subheading: 'Classes'}
       */
      dataSync() {
        this.throwIfDisposed();
        const data = trackerFn().readSync(this.dataId);
        if (this.dtype === "string") {
          try {
            return data.map((b) => decodeString(b));
          } catch (_a) {
            throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");
          }
        }
        return data;
      }
      /** Returns the underlying bytes of the tensor's data. */
      async bytes() {
        this.throwIfDisposed();
        const data = await trackerFn().read(this.dataId);
        if (this.dtype === "string") {
          return data;
        } else {
          return new Uint8Array(data.buffer);
        }
      }
      /**
       * Disposes `tf.Tensor` from memory.
       *
       * @doc {heading: 'Tensors', subheading: 'Classes'}
       */
      dispose() {
        if (this.isDisposed) {
          return;
        }
        if (this.kerasMask) {
          this.kerasMask.dispose();
        }
        trackerFn().disposeTensor(this);
        this.isDisposedInternal = true;
      }
      get isDisposed() {
        return this.isDisposedInternal;
      }
      throwIfDisposed() {
        if (this.isDisposed) {
          throw new Error(`Tensor is disposed.`);
        }
      }
      /**
       * Prints the `tf.Tensor`. See `tf.print` for details.
       *
       * @param verbose Whether to print verbose information about the tensor,
       *    including dtype and size.
       *
       * @doc {heading: 'Tensors', subheading: 'Classes'}
       */
      print(verbose = false) {
        return opHandler.print(this, verbose);
      }
      /**
       * Returns a copy of the tensor. See `tf.clone` for details.
       * @doc {heading: 'Tensors', subheading: 'Classes'}
       */
      clone() {
        this.throwIfDisposed();
        return opHandler.clone(this);
      }
      /**
       * Returns a human-readable description of the tensor. Useful for logging.
       *
       * @doc {heading: 'Tensors', subheading: 'Classes'}
       */
      toString(verbose = false) {
        const vals = this.dataSync();
        return tensorToString(vals, this.shape, this.dtype, verbose);
      }
      cast(dtype) {
        this.throwIfDisposed();
        return opHandler.cast(this, dtype);
      }
      variable(trainable = true, name, dtype) {
        this.throwIfDisposed();
        return trackerFn().makeVariable(this, trainable, name, dtype);
      }
    };
    Object.defineProperty(Tensor, Symbol.hasInstance, {
      value: (instance) => {
        return !!instance && instance.data != null && instance.dataSync != null && instance.throwIfDisposed != null;
      }
    });
    function getGlobalTensorClass() {
      return getGlobal("Tensor", () => {
        return Tensor;
      });
    }
    getGlobalTensorClass();
    var Variable = class extends Tensor {
      constructor(initialValue, trainable, name, tensorId) {
        super(initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId);
        this.trainable = trainable;
        this.name = name;
      }
      /**
       * Assign a new `tf.Tensor` to this variable. The new `tf.Tensor` must have
       * the same shape and dtype as the old `tf.Tensor`.
       *
       * @param newValue New tensor to be assigned to this variable.
       *
       * @doc {heading: 'Tensors', subheading: 'Classes'}
       */
      assign(newValue) {
        if (newValue.dtype !== this.dtype) {
          throw new Error(`dtype of the new value (${newValue.dtype}) and previous value (${this.dtype}) must match`);
        }
        if (!arraysEqual(newValue.shape, this.shape)) {
          throw new Error(`shape of the new value (${newValue.shape}) and previous value (${this.shape}) must match`);
        }
        trackerFn().disposeTensor(this);
        this.dataId = newValue.dataId;
        trackerFn().incRef(
          this,
          null
          /* backend */
        );
      }
      dispose() {
        trackerFn().disposeVariable(this);
        this.isDisposedInternal = true;
      }
    };
    Object.defineProperty(Variable, Symbol.hasInstance, {
      value: (instance) => {
        return instance instanceof Tensor && instance.assign != null && instance.assign instanceof Function;
      }
    });
    var Rank;
    (function(Rank2) {
      Rank2["R0"] = "R0";
      Rank2["R1"] = "R1";
      Rank2["R2"] = "R2";
      Rank2["R3"] = "R3";
      Rank2["R4"] = "R4";
      Rank2["R5"] = "R5";
      Rank2["R6"] = "R6";
    })(Rank || (Rank = {}));
    var UpcastInt32AndMap;
    (function(UpcastInt32AndMap2) {
      UpcastInt32AndMap2["float32"] = "float32";
      UpcastInt32AndMap2["int32"] = "int32";
      UpcastInt32AndMap2["bool"] = "int32";
      UpcastInt32AndMap2["complex64"] = "complex64";
    })(UpcastInt32AndMap || (UpcastInt32AndMap = {}));
    var UpcastBoolAndMap;
    (function(UpcastBoolAndMap2) {
      UpcastBoolAndMap2["float32"] = "float32";
      UpcastBoolAndMap2["int32"] = "int32";
      UpcastBoolAndMap2["bool"] = "bool";
      UpcastBoolAndMap2["complex64"] = "complex64";
    })(UpcastBoolAndMap || (UpcastBoolAndMap = {}));
    var UpcastFloat32AndMap;
    (function(UpcastFloat32AndMap2) {
      UpcastFloat32AndMap2["float32"] = "float32";
      UpcastFloat32AndMap2["int32"] = "float32";
      UpcastFloat32AndMap2["bool"] = "float32";
      UpcastFloat32AndMap2["complex64"] = "complex64";
    })(UpcastFloat32AndMap || (UpcastFloat32AndMap = {}));
    var UpcastComplex64AndMap;
    (function(UpcastComplex64AndMap2) {
      UpcastComplex64AndMap2["float32"] = "complex64";
      UpcastComplex64AndMap2["int32"] = "complex64";
      UpcastComplex64AndMap2["bool"] = "complex64";
      UpcastComplex64AndMap2["complex64"] = "complex64";
    })(UpcastComplex64AndMap || (UpcastComplex64AndMap = {}));
    var upcastTypeMap = {
      "float32": UpcastFloat32AndMap,
      "int32": UpcastInt32AndMap,
      "bool": UpcastBoolAndMap,
      "complex64": UpcastComplex64AndMap
    };
    function upcastType(typeA, typeB) {
      if (typeA === "string" || typeB === "string") {
        if (typeA === "string" && typeB === "string") {
          return "string";
        }
        throw new Error(`Can not upcast ${typeA} with ${typeB}`);
      }
      return upcastTypeMap[typeA][typeB];
    }
    function isWebGLData(values) {
      return values != null && typeof values === "object" && "texture" in values && values.texture instanceof WebGLTexture;
    }
    function isWebGPUData(values) {
      return typeof GPUBuffer !== "undefined" && values != null && typeof values === "object" && "buffer" in values && values.buffer instanceof GPUBuffer;
    }
    function makeTypesMatch(a, b) {
      if (a.dtype === b.dtype) {
        return [a, b];
      }
      const dtype = upcastType(a.dtype, b.dtype);
      return [a.cast(dtype), b.cast(dtype)];
    }
    function getTensorsInContainer(result) {
      const list = [];
      const seen = /* @__PURE__ */ new Set();
      walkTensorContainer(result, list, seen);
      return list;
    }
    function walkTensorContainer(container, list, seen) {
      if (container == null) {
        return;
      }
      if (container instanceof Tensor) {
        list.push(container);
        return;
      }
      if (!isIterable(container)) {
        return;
      }
      const iterable = container;
      for (const k in iterable) {
        const val = iterable[k];
        if (!seen.has(val)) {
          seen.add(val);
          walkTensorContainer(val, list, seen);
        }
      }
    }
    function isIterable(obj) {
      return Array.isArray(obj) || typeof obj === "object";
    }
    function isRegisteredKernelInvocation(kernelInvocation) {
      return kernelInvocation.kernelName != null;
    }
    var EngineState = class {
      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 = /* @__PURE__ */ new WeakMap();
        this.profiling = false;
        this.activeProfile = {
          newBytes: 0,
          newTensors: 0,
          peakBytes: 0,
          kernels: [],
          result: null,
          get kernelNames() {
            return Array.from(new Set(this.kernels.map((k) => k.name)));
          }
        };
      }
      dispose() {
        for (const variableName in this.registeredVariables) {
          this.registeredVariables[variableName].dispose();
        }
      }
    };
    var Engine = class _Engine {
      constructor(ENV2) {
        this.ENV = ENV2;
        this.registry = {};
        this.registryFactory = {};
        this.pendingBackendInitId = 0;
        this.state = new EngineState();
      }
      async ready() {
        if (this.pendingBackendInit != null) {
          return this.pendingBackendInit.then(() => {
          });
        }
        if (this.backendInstance != null) {
          return;
        }
        const sortedBackends = this.getSortedBackends();
        for (let i = 0; i < sortedBackends.length; i++) {
          const backendName = sortedBackends[i];
          const success = await this.initializeBackend(backendName).success;
          if (success) {
            await this.setBackend(backendName);
            return;
          }
        }
        throw new Error(`Could not initialize any backends, all backend initializations failed.`);
      }
      get backend() {
        if (this.pendingBackendInit != null) {
          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 (this.backendInstance == null) {
          const { name, asyncInit } = this.initializeBackendsAndReturnBest();
          if (asyncInit) {
            throw new Error(`The highest priority backend '${name}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);
          }
          this.setBackend(name);
        }
        return this.backendInstance;
      }
      backendNames() {
        return Object.keys(this.registryFactory);
      }
      findBackend(backendName) {
        if (!(backendName in this.registry)) {
          if (backendName in this.registryFactory) {
            const { asyncInit } = this.initializeBackend(backendName);
            if (asyncInit) {
              return null;
            }
          } else {
            return null;
          }
        }
        return this.registry[backendName];
      }
      findBackendFactory(backendName) {
        if (!(backendName in this.registryFactory)) {
          return null;
        }
        return this.registryFactory[backendName].factory;
      }
      registerBackend(backendName, factory, priority = 1) {
        if (backendName in this.registryFactory) {
          warn(`${backendName} backend was already registered. Reusing existing backend factory.`);
          return false;
        }
        this.registryFactory[backendName] = { factory, priority };
        return true;
      }
      async setBackend(backendName) {
        if (this.registryFactory[backendName] == null) {
          throw new Error(`Backend name '${backendName}' not found in registry`);
        }
        this.backendName = backendName;
        if (this.registry[backendName] == null) {
          this.backendInstance = null;
          const { success, asyncInit } = this.initializeBackend(backendName);
          const result = asyncInit ? await success : success;
          if (!result) {
            return false;
          }
        }
        this.backendInstance = this.registry[backendName];
        this.setupRegisteredKernels();
        this.profiler = new Profiler(this.backendInstance);
        return true;
      }
      setupRegisteredKernels() {
        const kernels = getKernelsForBackend(this.backendName);
        kernels.forEach((kernel) => {
          if (kernel.setupFunc != null) {
            kernel.setupFunc(this.backendInstance);
          }
        });
      }
      disposeRegisteredKernels(backendName) {
        const kernels = getKernelsForBackend(backendName);
        kernels.forEach((kernel) => {
          if (kernel.disposeFunc != null) {
            kernel.disposeFunc(this.registry[backendName]);
          }
        });
      }
      /**
       * Initializes a backend by looking up the backend name in the factory
       * registry and calling the factory method. Returns a boolean representing
       * whether the initialization of the backend succeeded. Throws an error if
       * there is no backend in the factory registry.
       */
      initializeBackend(backendName) {
        const registryFactoryEntry = this.registryFactory[backendName];
        if (registryFactoryEntry == null) {
          throw new Error(`Cannot initialize backend ${backendName}, no registration found.`);
        }
        try {
          const backend2 = registryFactoryEntry.factory();
          if (backend2 && !(backend2 instanceof KernelBackend) && typeof backend2.then === "function") {
            const promiseId = ++this.pendingBackendInitId;
            const success = backend2.then((backendInstance) => {
              if (promiseId < this.pendingBackendInitId) {
                return false;
              }
              this.registry[backendName] = backendInstance;
              this.pendingBackendInit = null;
              return true;
            }).catch((err) => {
              if (promiseId < this.pendingBackendInitId) {
                return false;
              }
              this.pendingBackendInit = null;
              warn(`Initialization of backend ${backendName} failed`);
              warn(err.stack || err.message);
              return false;
            });
            this.pendingBackendInit = success;
            return { success, asyncInit: true };
          } else {
            this.registry[backendName] = backend2;
            return { success: true, asyncInit: false };
          }
        } catch (err) {
          warn(`Initialization of backend ${backendName} failed`);
          warn(err.stack || err.message);
          return { success: false, asyncInit: false };
        }
      }
      removeBackend(backendName) {
        if (!(backendName in this.registryFactory)) {
          throw new Error(`${backendName} backend not found in registry`);
        }
        if (this.backendName === backendName && this.pendingBackendInit != null) {
          this.pendingBackendInitId++;
        }
        if (backendName in this.registry) {
          this.disposeRegisteredKernels(backendName);
          this.registry[backendName].dispose();
          delete this.registry[backendName];
        }
        delete this.registryFactory[backendName];
        if (this.backendName === backendName) {
          this.pendingBackendInit = null;
          this.backendName = null;
          this.backendInstance = null;
        }
      }
      getSortedBackends() {
        if (Object.keys(this.registryFactory).length === 0) {
          throw new Error("No backend found in registry.");
        }
        return Object.keys(this.registryFactory).sort((a, b) => {
          return this.registryFactory[b].priority - this.registryFactory[a].priority;
        });
      }
      initializeBackendsAndReturnBest() {
        const sortedBackends = this.getSortedBackends();
        for (let i = 0; i < sortedBackends.length; i++) {
          const backendName = sortedBackends[i];
          const { success, asyncInit } = this.initializeBackend(backendName);
          if (asyncInit || success) {
            return { name: backendName, asyncInit };
          }
        }
        throw new Error(`Could not initialize any backends, all backend initializations failed.`);
      }
      moveData(backend2, dataId) {
        const info = this.state.tensorInfo.get(dataId);
        const srcBackend = info.backend;
        const values = this.readSync(dataId);
        const refCount = srcBackend.refCount(dataId);
        srcBackend.disposeData(dataId, true);
        info.backend = backend2;
        backend2.move(dataId, values, info.shape, info.dtype, refCount);
        if (this.shouldCheckForMemLeaks()) {
          this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;
        }
      }
      tidy(nameOrFn, fn) {
        let name = null;
        if (fn == null) {
          if (typeof nameOrFn !== "function") {
            throw new Error("Please provide a function to tidy()");
          }
          fn = nameOrFn;
        } else {
          if (typeof nameOrFn !== "string" && !(nameOrFn instanceof String)) {
            throw new Error("When calling with two arguments, the first argument to tidy() must be a string");
          }
          if (typeof fn !== "function") {
            throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");
          }
          name = nameOrFn;
        }
        let result;
        return this.scopedRun(() => this.startScope(name), () => this.endScope(result), () => {
          result = fn();
          if (result instanceof Promise) {
            console.error("Cannot return a Promise inside of tidy.");
          }
          return result;
        });
      }
      scopedRun(start, end, f) {
        start();
        try {
          const res = f();
          end();
          return res;
        } catch (ex) {
          end();
          throw ex;
        }
      }
      nextTensorId() {
        return _Engine.nextTensorId++;
      }
      nextVariableId() {
        return _Engine.nextVariableId++;
      }
      /**
       * This method is called instead of the public-facing tensor.clone() when
       * saving a tensor for backwards pass. It makes sure to add the clone
       * operation to the tape regardless of being called inside a kernel
       * execution.
       */
      clone(x) {
        const y = ENGINE.runKernel(Identity, { x });
        const inputs = { x };
        const grad2 = (dy) => ({
          x: () => {
            const dtype = "float32";
            const gradInputs = { x: dy };
            const attrs = { dtype };
            return ENGINE.runKernel(
              Cast,
              gradInputs,
              // tslint:disable-next-line: no-unnecessary-type-assertion
              attrs
            );
          }
        });
        const saved = [];
        this.addTapeNode(this.state.activeScope.name, inputs, [y], grad2, saved, {});
        return y;
      }
      /**
       * Execute a kernel with the given name and return the output tensor.
       *
       * @param kernelName The name of the kernel to execute.
       * @param inputs A map of input names to tensors.
       * @param attrs A map of attribute names to their values. An attribute is a
       *     primitive (non-tensor) input to the kernel.
       * @param inputsToSave A list of tensors, inputs to save for the backprop
       *     computation.
       * @param outputsToSave A list of booleans, specifying which output to save
       *     for the backprop computation. These are booleans since the output
       * tensors are not visible to the user.
       */
      runKernel(kernelName, inputs, attrs) {
        if (this.backendName == null) {
          this.backend;
        }
        const hasKernel = getKernel(kernelName, this.backendName) != null;
        if (!hasKernel) {
          throw new Error(`Kernel '${kernelName}' not registered for backend '${this.backendName}'`);
        }
        return this.runKernelFunc({ kernelName, inputs, attrs });
      }
      shouldCheckForMemLeaks() {
        return this.ENV.getBool("IS_TEST");
      }
      checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos) {
        const numDataIdsAfter = this.backend.numDataIds();
        let numOutputDataIds = 0;
        outInfos.forEach((info) => {
          numOutputDataIds += info.dtype === "complex64" ? 3 : 1;
        });
        const numMoves = this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1];
        const dataIdsLeaked = numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves;
        if (dataIdsLeaked > 0) {
          throw new Error(`Backend '${this.backendName}' has an internal memory leak (${dataIdsLeaked} data ids) after running '${kernelName}'`);
        }
      }
      /**
       * Internal helper method to execute a kernel Func
       *
       * Use `runKernel` to execute kernels from outside of engine.
       */
      runKernelFunc(kernelParams) {
        let outputs;
        let saved = [];
        const isTapeOn = this.isTapeOn();
        const startingBytecount = this.state.numBytes;
        const startingNumTensors = this.state.numTensors;
        if (this.shouldCheckForMemLeaks()) {
          this.state.numDataMovesStack.push(0);
        }
        let kernelFunc;
        if (this.backendName == null) {
          this.backend;
        }
        let out;
        const kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ? kernelParams.kernelName : this.state.activeScope != null ? this.state.activeScope.name : "";
        if (isRegisteredKernelInvocation(kernelParams)) {
          const { kernelName, inputs: inputs2, attrs: attrs2 } = kernelParams;
          if (this.backendName == null) {
            this.backend;
          }
          const kernel = getKernel(kernelName, this.backendName);
          assert(kernel != null, () => `Cannot find registered kernel '${kernelName}' for backend '${this.backendName}'`);
          kernelFunc = () => {
            const numDataIdsBefore = this.backend.numDataIds();
            out = kernel.kernelFunc({ inputs: inputs2, attrs: attrs2, backend: this.backend });
            const outInfos = Array.isArray(out) ? out : [out];
            if (this.shouldCheckForMemLeaks()) {
              this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos);
            }
            const outTensors = outInfos.map((outInfo) => {
              if (outInfo.rank != null) {
                return outInfo;
              }
              return this.makeTensorFromTensorInfo(outInfo);
            });
            if (isTapeOn) {
              const tensorsToSave = this.getTensorsForGradient(kernelName, inputs2, outTensors);
              saved = this.saveTensorsForBackwardMode(tensorsToSave);
            }
            return outTensors;
          };
        } else {
          const { forwardFunc } = kernelParams;
          const saveFunc = (tensors) => {
            if (!isTapeOn) {
              return;
            }
            saved = tensors.map((tensor2) => this.keep(this.clone(tensor2)));
          };
          kernelFunc = () => {
            const numDataIdsBefore = this.backend.numDataIds();
            out = this.tidy(() => forwardFunc(this.backend, saveFunc));
            const outs = Array.isArray(out) ? out : [out];
            if (this.shouldCheckForMemLeaks()) {
              this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs);
            }
            return outs;
          };
        }
        const { inputs, attrs } = kernelParams;
        const backwardsFunc = isRegisteredKernelInvocation(kernelParams) ? null : kernelParams.backwardsFunc;
        let kernelProfile;
        this.scopedRun(
          // Stop recording to a tape when running a kernel.
          () => this.state.kernelDepth++,
          () => this.state.kernelDepth--,
          () => {
            if (!this.ENV.getBool("DEBUG") && !this.state.profiling) {
              outputs = kernelFunc();
            } else {
              kernelProfile = this.profiler.profileKernel(kernelOrScopeName, inputs, () => kernelFunc());
              if (this.ENV.getBool("DEBUG")) {
                this.profiler.logKernelProfile(kernelProfile);
              }
              outputs = kernelProfile.outputs;
            }
          }
        );
        if (isTapeOn) {
          this.addTapeNode(kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs);
        }
        if (this.state.profiling) {
          this.state.activeProfile.kernels.push({
            name: kernelOrScopeName,
            bytesAdded: this.state.numBytes - startingBytecount,
            totalBytesSnapshot: this.state.numBytes,
            tensorsAdded: this.state.numTensors - startingNumTensors,
            totalTensorsSnapshot: this.state.numTensors,
            inputShapes: Object.keys(inputs).map((key) => inputs[key] != null ? inputs[key].shape : null),
            outputShapes: outputs.map((item) => item.shape),
            kernelTimeMs: kernelProfile.timeMs,
            extraInfo: kernelProfile.extraInfo
          });
        }
        return Array.isArray(out) ? outputs : outputs[0];
      }
      /**
       * Saves tensors used in forward mode for use in backward mode.
       *
       * @param tensors the list of tensors to save.
       */
      saveTensorsForBackwardMode(tensors) {
        const saved = tensors.map((tensor2) => this.keep(this.clone(tensor2)));
        return saved;
      }
      /**
       * Returns a list of tensors to save for a given gradient calculation.
       *
       * @param kernelName name of kernel to look up gradient for.
       * @param inputs a map of input tensors.
       * @param outputs an array of output tensors from forward mode of kernel.
       */
      getTensorsForGradient(kernelName, inputs, outputs) {
        const gradConfig = getGradient(kernelName);
        if (gradConfig != null) {
          const inputsToSave = gradConfig.inputsToSave || [];
          const outputsToSave = gradConfig.outputsToSave || [];
          let inputTensorsToSave;
          if (gradConfig.saveAllInputs) {
            assert(Array.isArray(inputs), () => "saveAllInputs is true, expected inputs to be an array.");
            inputTensorsToSave = Object.keys(inputs).map((key) => inputs[key]);
          } else {
            inputTensorsToSave = inputsToSave.map((inputName) => inputs[inputName]);
          }
          const outputTensorsToSave = outputs.filter((_, i) => outputsToSave[i]);
          return inputTensorsToSave.concat(outputTensorsToSave);
        }
        return [];
      }
      /**
       * Internal method used by public APIs for tensor creation. Makes a new
       * tensor with the provided shape, dtype and values. It always
       * creates a new data id and writes the values to the underlying backend.
       */
      makeTensor(values, shape, dtype, backend2) {
        if (values == null) {
          throw new Error("Values passed to engine.makeTensor() are null");
        }
        dtype = dtype || "float32";
        backend2 = backend2 || this.backend;
        let backendVals = values;
        if (dtype === "string" && isString(values[0])) {
          backendVals = values.map((d) => encodeString(d));
        }
        const dataId = backend2.write(backendVals, shape, dtype);
        const t = new Tensor(shape, dtype, dataId, this.nextTensorId());
        this.trackTensor(t, backend2);
        if (dtype === "string") {
          const info = this.state.tensorInfo.get(dataId);
          const newBytes = bytesFromStringArray(backendVals);
          this.state.numBytes += newBytes - info.bytes;
          info.bytes = newBytes;
        }
        return t;
      }
      /**
       * Internal method used by backends. Makes a new tensor
       * that is a wrapper around an existing data id. It doesn't create
       * a new data id, only increments the ref count used in memory tracking.
       * @deprecated
       */
      makeTensorFromDataId(dataId, shape, dtype, backend2) {
        dtype = dtype || "float32";
        const tensorInfo = { dataId, shape, dtype };
        return this.makeTensorFromTensorInfo(tensorInfo, backend2);
      }
      /**
       * Internal method used by backends. Makes a new tensor that is a wrapper
       * around an existing data id in TensorInfo. It doesn't create a new data id,
       * only increments the ref count used in memory tracking.
       */
      makeTensorFromTensorInfo(tensorInfo, backend2) {
        const { dataId, shape, dtype } = tensorInfo;
        const t = new Tensor(shape, dtype, dataId, this.nextTensorId());
        this.trackTensor(t, backend2);
        return t;
      }
      makeVariable(initialValue, trainable = true, name, dtype) {
        name = name || this.nextVariableId().toString();
        if (dtype != null && dtype !== initialValue.dtype) {
          initialValue = initialValue.cast(dtype);
        }
        const v = new Variable(initialValue, trainable, name, this.nextTensorId());
        if (this.state.registeredVariables[v.name] != null) {
          throw new Error(`Variable with name ${v.name} was already registered`);
        }
        this.state.registeredVariables[v.name] = v;
        this.incRef(v, this.backend);
        return v;
      }
      trackTensor(a, backend2) {
        this.state.numTensors++;
        if (a.dtype === "string") {
          this.state.numStringTensors++;
        }
        let bytes = 0;
        if (a.dtype !== "complex64" && a.dtype !== "string") {
          bytes = a.size * bytesPerElement(a.dtype);
        }
        this.state.numBytes += bytes;
        if (!this.state.tensorInfo.has(a.dataId)) {
          this.state.numDataBuffers++;
          this.state.tensorInfo.set(a.dataId, {
            backend: backend2 || this.backend,
            dtype: a.dtype,
            shape: a.shape,
            bytes
          });
        }
        if (!(a instanceof Variable)) {
          this.track(a);
        }
      }
      // Track the tensor by dataId and increase the refCount for the dataId in the
      // backend.
      // TODO(pyu10055): This is currently used by makeVariable method, to increase
      // refCount on the backend for the dataId. It can potentially be replaced with
      // Identity op indead of calling backend directly.
      incRef(a, backend2) {
        this.trackTensor(a, backend2);
        this.backend.incRef(a.dataId);
      }
      removeDataId(dataId, backend2) {
        if (this.state.tensorInfo.has(dataId) && this.state.tensorInfo.get(dataId).backend === backend2) {
          this.state.tensorInfo.delete(dataId);
          this.state.numDataBuffers--;
        }
      }
      disposeTensor(a) {
        if (!this.state.tensorInfo.has(a.dataId)) {
          return;
        }
        const info = this.state.tensorInfo.get(a.dataId);
        this.state.numTensors--;
        if (a.dtype === "string") {
          this.state.numStringTensors--;
          this.state.numBytes -= info.bytes;
        }
        if (a.dtype !== "complex64" && a.dtype !== "string") {
          const bytes = a.size * bytesPerElement(a.dtype);
          this.state.numBytes -= bytes;
        }
        if (info.backend.disposeData(a.dataId)) {
          this.removeDataId(a.dataId, info.backend);
        }
      }
      disposeVariables() {
        for (const varName in this.state.registeredVariables) {
          const v = this.state.registeredVariables[varName];
          this.disposeVariable(v);
        }
      }
      disposeVariable(v) {
        this.disposeTensor(v);
        if (this.state.registeredVariables[v.name] != null) {
          delete this.state.registeredVariables[v.name];
        }
      }
      memory() {
        const info = this.backend.memory();
        info.numTensors = this.state.numTensors;
        info.numDataBuffers = this.state.numDataBuffers;
        info.numBytes = this.state.numBytes;
        if (this.state.numStringTensors > 0) {
          info.unreliable = true;
          if (info.reasons == null) {
            info.reasons = [];
          }
          info.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)");
        }
        return info;
      }
      async profile(query) {
        this.state.profiling = true;
        const startBytes = this.state.numBytes;
        const startNumTensors = this.state.numTensors;
        this.state.activeProfile.kernels = [];
        this.state.activeProfile.result = await query();
        this.state.profiling = false;
        this.state.activeProfile.peakBytes = Math.max(...this.state.activeProfile.kernels.map((d) => d.totalBytesSnapshot));
        this.state.activeProfile.newBytes = this.state.numBytes - startBytes;
        this.state.activeProfile.newTensors = this.state.numTensors - startNumTensors;
        for (const kernel of this.state.activeProfile.kernels) {
          kernel.kernelTimeMs = await kernel.kernelTimeMs;
          kernel.extraInfo = await kernel.extraInfo;
        }
        return this.state.activeProfile;
      }
      isTapeOn() {
        return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;
      }
      addTapeNode(kernelName, inputs, outputs, gradientsFunc, saved, attrs) {
        const tapeNode = { id: this.state.nextTapeNodeId++, kernelName, inputs, outputs, saved };
        const gradConfig = getGradient(kernelName);
        if (gradConfig != null) {
          gradientsFunc = gradConfig.gradFunc;
        }
        if (gradientsFunc != null) {
          tapeNode.gradient = (dys) => {
            dys = dys.map((dy, i) => {
              if (dy == null) {
                const output = outputs[i];
                const vals = makeZerosTypedArray(output.size, output.dtype);
                return this.makeTensor(vals, output.shape, output.dtype);
              }
              return dy;
            });
            return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs);
          };
        }
        this.state.activeTape.push(tapeNode);
      }
      keep(result) {
        result.kept = true;
        return result;
      }
      startTape() {
        if (this.state.gradientDepth === 0) {
          this.state.activeTape = [];
        }
        this.state.gradientDepth++;
      }
      endTape() {
        this.state.gradientDepth--;
      }
      /**
       * Start a scope. Use this with endScope() to achieve the same functionality
       * as scope() without the need for a function closure.
       */
      startScope(name) {
        const scopeInfo = {
          track: [],
          name: "unnamed scope",
          id: this.state.nextScopeId++
        };
        if (name) {
          scopeInfo.name = name;
        }
        this.state.scopeStack.push(scopeInfo);
        this.state.activeScope = scopeInfo;
      }
      /**
       * End a scope. Use this with startScope() to achieve the same functionality
       * as scope() without the need for a function closure.
       */
      endScope(result) {
        const tensorsToTrackInParent = getTensorsInContainer(result);
        const tensorsToTrackInParentSet = new Set(tensorsToTrackInParent.map((t) => t.id));
        for (let i = 0; i < this.state.activeScope.track.length; i++) {
          const tensor2 = this.state.activeScope.track[i];
          if (!tensor2.kept && !tensorsToTrackInParentSet.has(tensor2.id)) {
            tensor2.dispose();
          }
        }
        const oldScope = this.state.scopeStack.pop();
        this.state.activeScope = this.state.scopeStack.length === 0 ? null : this.state.scopeStack[this.state.scopeStack.length - 1];
        tensorsToTrackInParent.forEach((tensor2) => {
          if (!tensor2.kept && tensor2.scopeId === oldScope.id) {
            this.track(tensor2);
          }
        });
      }
      /**
       * Returns gradients of `f` with respect to each of the `xs`. The gradients
       * returned are of the same length as `xs`, but some might be null if `f`
       * was not a function of that `x`. It also takes optional dy to multiply the
       * gradient, which defaults to `1`.
       */
      gradients(f, xs, dy, allowNoGradients = false) {
        assert(xs.length > 0, () => "gradients() received an empty list of xs.");
        if (dy != null && dy.dtype !== "float32") {
          throw new Error(`dy must have 'float32' dtype, but has '${dy.dtype}'`);
        }
        const y = this.scopedRun(() => this.startTape(), () => this.endTape(), () => this.tidy("forward", f));
        assert(y instanceof Tensor, () => "The result y returned by f() must be a tensor.");
        const filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y);
        if (!allowNoGradients && filteredTape.length === 0 && xs.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 accumulatedGradientMap = {};
          accumulatedGradientMap[y.id] = dy == null ? ones$1(y.shape) : dy;
          backpropagateGradients(
            accumulatedGradientMap,
            filteredTape,
            // Pass the tidy function to avoid circular dep with `tape.ts`.
            (f2) => this.tidy(f2),
            // Pass an add function to avoide a circular dep with `tape.ts`.
            add$1
          );
          const grads2 = xs.map((x) => accumulatedGradientMap[x.id]);
          if (this.state.gradientDepth === 0) {
            this.state.activeTape.forEach((node) => {
              for (const tensor2 of node.saved) {
                tensor2.dispose();
              }
            });
            this.state.activeTape = null;
          }
          return { value: y, grads: grads2 };
        });
      }
      customGrad(f) {
        assert(isFunction(f), () => "The f passed in customGrad(f) must be a function.");
        return (...inputs) => {
          assert(inputs.every((t) => t instanceof Tensor), () => "The args passed in customGrad(f)(x1, x2,...) must all be tensors");
          let res;
          const inputMap = {};
          inputs.forEach((input, i) => {
            inputMap[i] = input;
          });
          const forwardFunc = (_, save) => {
            res = f(...[...inputs, save]);
            assert(res.value instanceof Tensor, () => "The function f passed in customGrad(f) must return an object where `obj.value` is a tensor");
            assert(isFunction(res.gradFunc), () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.");
            return res.value;
          };
          const backwardsFunc = (dy, saved) => {
            const gradRes = res.gradFunc(dy, saved);
            const grads2 = Array.isArray(gradRes) ? gradRes : [gradRes];
            assert(grads2.length === inputs.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(...).");
            assert(grads2.every((t) => t instanceof Tensor), () => "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 gradMap = {};
            grads2.forEach((grad2, i) => {
              gradMap[i] = () => grad2;
            });
            return gradMap;
          };
          return this.runKernelFunc({
            forwardFunc,
            backwardsFunc,
            inputs: inputMap
          });
        };
      }
      readSync(dataId) {
        const info = this.state.tensorInfo.get(dataId);
        return info.backend.readSync(dataId);
      }
      read(dataId) {
        const info = this.state.tensorInfo.get(dataId);
        return info.backend.read(dataId);
      }
      readToGPU(dataId, options) {
        const info = this.state.tensorInfo.get(dataId);
        return info.backend.readToGPU(dataId, options);
      }
      async time(query) {
        const start = now();
        const timingInfo = await this.backend.time(query);
        timingInfo.wallMs = now() - start;
        return timingInfo;
      }
      /**
       * Tracks a Tensor in the current scope to be automatically cleaned up
       * when the current scope ends, and returns the value.
       *
       * @param result The Tensor to track in the current scope.
       */
      track(result) {
        if (this.state.activeScope != null) {
          result.scopeId = this.state.activeScope.id;
          this.state.activeScope.track.push(result);
        }
        return result;
      }
      get registeredVariables() {
        return this.state.registeredVariables;
      }
      /**
       * Resets the engine state. Removes all backends but does not remove
       * registered backend factories.
       */
      reset() {
        this.pendingBackendInitId++;
        this.state.dispose();
        this.ENV.reset();
        this.state = new EngineState();
        for (const backendName in this.registry) {
          this.disposeRegisteredKernels(backendName);
          this.registry[backendName].dispose();
          delete this.registry[backendName];
        }
        this.backendName = null;
        this.backendInstance = null;
        this.pendingBackendInit = null;
      }
    };
    Engine.nextTensorId = 0;
    Engine.nextVariableId = 0;
    function ones$1(shape) {
      const values = makeOnesTypedArray(sizeFromShape(shape), "float32");
      return ENGINE.makeTensor(values, shape, "float32");
    }
    function getOrMakeEngine() {
      const ns = getGlobalNamespace();
      if (ns._tfengine == null) {
        const environment = new Environment(ns);
        ns._tfengine = new Engine(environment);
      }
      setEnvironmentGlobal(ns._tfengine.ENV);
      setTensorTracker(() => ns._tfengine);
      return ns._tfengine;
    }
    var ENGINE = getOrMakeEngine();
    function add$1(a, b) {
      const inputs = { a, b };
      return ENGINE.runKernel(Add, inputs);
    }
    function inferShape(val, dtype) {
      let firstElem = val;
      if (isTypedArray(val)) {
        return dtype === "string" ? [] : [val.length];
      }
      if (isWebGLData(val)) {
        const usedChannels = val.channels || "RGBA";
        return [val.height, val.width * usedChannels.length];
      } else if (isWebGPUData(val)) {
        return [val.buffer.size / (dtype == null ? 4 : bytesPerElement(dtype))];
      }
      if (!Array.isArray(val)) {
        return [];
      }
      const shape = [];
      while (Array.isArray(firstElem) || isTypedArray(firstElem) && dtype !== "string") {
        shape.push(firstElem.length);
        firstElem = firstElem[0];
      }
      if (Array.isArray(val) && env().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")) {
        deepAssertShapeConsistency(val, shape, []);
      }
      return shape;
    }
    function deepAssertShapeConsistency(val, shape, indices) {
      indices = indices || [];
      if (!Array.isArray(val) && !isTypedArray(val)) {
        assert(shape.length === 0, () => `Element arr[${indices.join("][")}] is a primitive, but should be an array/TypedArray of ${shape[0]} elements`);
        return;
      }
      assert(shape.length > 0, () => `Element arr[${indices.join("][")}] should be a primitive, but is an array of ${val.length} elements`);
      assert(val.length === shape[0], () => `Element arr[${indices.join("][")}] should have ${shape[0]} elements, but has ${val.length} elements`);
      const subShape = shape.slice(1);
      for (let i = 0; i < val.length; ++i) {
        deepAssertShapeConsistency(val[i], subShape, indices.concat(i));
      }
    }
    function assertDtype(expectedDtype, actualDType, argName, functionName) {
      if (expectedDtype === "string_or_numeric") {
        return;
      }
      if (expectedDtype == null) {
        throw new Error(`Expected dtype cannot be null.`);
      }
      if (expectedDtype !== "numeric" && expectedDtype !== actualDType || expectedDtype === "numeric" && actualDType === "string") {
        throw new Error(`Argument '${argName}' passed to '${functionName}' must be ${expectedDtype} tensor, but got ${actualDType} tensor`);
      }
    }
    function convertToTensor(x, argName, functionName, parseAsDtype = "numeric") {
      if (x instanceof getGlobalTensorClass()) {
        assertDtype(parseAsDtype, x.dtype, argName, functionName);
        return x;
      }
      let inferredDtype = inferDtype(x);
      if (inferredDtype !== "string" && ["bool", "int32", "float32"].indexOf(parseAsDtype) >= 0) {
        inferredDtype = parseAsDtype;
      }
      assertDtype(parseAsDtype, inferredDtype, argName, functionName);
      if (x == null || !isTypedArray(x) && !Array.isArray(x) && typeof x !== "number" && typeof x !== "boolean" && typeof x !== "string") {
        const type = x == null ? "null" : x.constructor.name;
        throw new Error(`Argument '${argName}' passed to '${functionName}' must be a Tensor or TensorLike, but got '${type}'`);
      }
      const inferredShape = inferShape(x, inferredDtype);
      if (!isTypedArray(x) && !Array.isArray(x)) {
        x = [x];
      }
      const skipTypedArray = true;
      const values = inferredDtype !== "string" ? toTypedArray(x, inferredDtype) : flatten(x, [], skipTypedArray);
      return ENGINE.makeTensor(values, inferredShape, inferredDtype);
    }
    function convertToTensorArray(arg, argName, functionName, parseAsDtype = "numeric") {
      if (!Array.isArray(arg)) {
        throw new Error(`Argument ${argName} passed to ${functionName} must be a \`Tensor[]\` or \`TensorLike[]\``);
      }
      const tensors = arg;
      return tensors.map((t, i) => convertToTensor(t, `${argName}[${i}]`, functionName, parseAsDtype));
    }
    var OP_SCOPE_SUFFIX = "__op";
    function op(f) {
      const keys = Object.keys(f);
      if (keys.length !== 1) {
        throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${keys.length} keys.`);
      }
      let opName = keys[0];
      const fn = f[opName];
      if (opName.endsWith("_")) {
        opName = opName.substring(0, opName.length - 1);
      }
      opName = opName + OP_SCOPE_SUFFIX;
      const f2 = (...args) => {
        ENGINE.startScope(opName);
        try {
          const result = fn(...args);
          if (isPromise(result)) {
            console.error("Cannot return a Promise inside of tidy.");
          }
          ENGINE.endScope(result);
          return result;
        } catch (ex) {
          ENGINE.endScope(null);
          throw ex;
        }
      };
      Object.defineProperty(f2, "name", { value: opName, configurable: true });
      return f2;
    }
    function cast_(x, dtype) {
      const $x = convertToTensor(x, "x", "cast");
      if (!isValidDtype(dtype)) {
        throw new Error(`Failed to cast to unknown dtype ${dtype}`);
      }
      if (dtype === "string" && $x.dtype !== "string" || dtype !== "string" && $x.dtype === "string") {
        throw new Error("Only strings can be casted to strings");
      }
      const inputs = { x: $x };
      const attrs = { dtype };
      return ENGINE.runKernel(Cast, inputs, attrs);
    }
    var cast = /* @__PURE__ */ op({ cast_ });
    function mul_(a, b) {
      let $a = convertToTensor(a, "a", "mul");
      let $b = convertToTensor(b, "b", "mul");
      [$a, $b] = makeTypesMatch($a, $b);
      const inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Multiply, inputs);
    }
    var mul = /* @__PURE__ */ op({ mul_ });
    function step_(x, alpha = 0) {
      const $x = convertToTensor(x, "x", "step");
      const inputs = { x: $x };
      const attrs = { alpha };
      return ENGINE.runKernel(Step, inputs, attrs);
    }
    var step = /* @__PURE__ */ op({ step_ });
    var absGradConfig = {
      kernelName: Abs,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => mul(dy, step(cast(x, "float32"), -1)) };
      }
    };
    function floorDiv_(a, b) {
      let $a = convertToTensor(a, "a", "floorDiv");
      let $b = convertToTensor(b, "b", "floorDiv");
      [$a, $b] = makeTypesMatch($a, $b);
      const inputs = { a: $a, b: $b };
      return ENGINE.runKernel(FloorDiv, inputs);
    }
    var floorDiv = /* @__PURE__ */ op({ floorDiv_ });
    function div_(a, b) {
      let $a = convertToTensor(a, "a", "div");
      let $b = convertToTensor(b, "b", "div");
      [$a, $b] = makeTypesMatch($a, $b);
      if ($a.dtype === "int32" && $b.dtype === "int32") {
        return floorDiv($a, $b);
      }
      const inputs = { a: $a, b: $b };
      const attrs = {};
      return ENGINE.runKernel(RealDiv, inputs, attrs);
    }
    var div = /* @__PURE__ */ op({ div_ });
    function neg_(x) {
      const $x = convertToTensor(x, "x", "neg");
      const inputs = { x: $x };
      return ENGINE.runKernel(Neg, inputs);
    }
    var neg = /* @__PURE__ */ op({ neg_ });
    function makeTensor(values, shape, inferredShape, dtype) {
      if (dtype == null) {
        dtype = inferDtype(values);
      } else if (dtype === "complex64") {
        throw new Error(`Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).`);
      }
      if (isWebGPUData(values) || isWebGLData(values)) {
        if (dtype !== "float32" && dtype !== "int32") {
          throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${dtype}.`);
        }
        return ENGINE.backend.createTensorFromGPUData(values, shape || inferredShape, dtype);
      }
      if (!isTypedArray(values) && !Array.isArray(values) && typeof values !== "number" && typeof values !== "boolean" && typeof values !== "string") {
        throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");
      }
      if (shape != null) {
        assertNonNegativeIntegerDimensions(shape);
        const providedSize = sizeFromShape(shape);
        const inferredSize = sizeFromShape(inferredShape);
        assert(providedSize === inferredSize, () => `Based on the provided shape, [${shape}], the tensor should have ${providedSize} values but has ${inferredSize}`);
        for (let i = 0; i < inferredShape.length; ++i) {
          const inferred = inferredShape[i];
          const flatDimsDontMatch = i === inferredShape.length - 1 ? inferred !== sizeFromShape(shape.slice(i)) : true;
          assert(inferredShape[i] === shape[i] || !flatDimsDontMatch, () => `Error creating a new Tensor. Inferred shape (${inferredShape}) does not match the provided shape (${shape}). `);
        }
      }
      if (!isTypedArray(values) && !Array.isArray(values)) {
        values = [values];
      }
      shape = shape || inferredShape;
      values = dtype !== "string" ? toTypedArray(values, dtype) : flatten(values, [], true);
      return ENGINE.makeTensor(values, shape, dtype);
    }
    function scalar(value, dtype) {
      if ((isTypedArray(value) && dtype !== "string" || Array.isArray(value)) && dtype !== "complex64") {
        throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");
      }
      if (dtype === "string" && isTypedArray(value) && !(value instanceof Uint8Array)) {
        throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");
      }
      const shape = [];
      const inferredShape = [];
      return makeTensor(value, shape, inferredShape, dtype);
    }
    function sqrt_(x) {
      const $x = convertToTensor(x, "x", "sqrt", "float32");
      const inputs = { x: $x };
      return ENGINE.runKernel(Sqrt, inputs);
    }
    var sqrt = /* @__PURE__ */ op({ sqrt_ });
    function square_(x) {
      const $x = convertToTensor(x, "x", "square");
      const attrs = {};
      return ENGINE.runKernel("Square", { x: $x }, attrs);
    }
    var square = /* @__PURE__ */ op({ square_ });
    function sub_(a, b) {
      let $a = convertToTensor(a, "a", "sub");
      let $b = convertToTensor(b, "b", "sub");
      [$a, $b] = makeTypesMatch($a, $b);
      const inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Sub, inputs);
    }
    var sub = /* @__PURE__ */ op({ sub_ });
    var acosGradConfig = {
      kernelName: Acos,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return {
          x: () => {
            const a = square(cast(x, "float32"));
            const b = sqrt(sub(scalar(1), a));
            return neg(div(dy, b));
          }
        };
      }
    };
    var acoshGradConfig = {
      kernelName: Acosh,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return {
          x: () => {
            const a = sqrt(sub(square(cast(x, "float32")), 1));
            return div(dy, a);
          }
        };
      }
    };
    function getReductionAxes(inShape, outShape) {
      const result = [];
      for (let i = 0; i < outShape.length; i++) {
        const inDim = inShape[inShape.length - i - 1];
        const outAxis = outShape.length - i - 1;
        const outDim = outShape[outAxis];
        if (inDim == null || inDim === 1 && outDim > 1) {
          result.unshift(outAxis);
        }
      }
      return result;
    }
    function assertAndGetBroadcastShape(shapeA, shapeB) {
      const l = Math.max(shapeA.length, shapeB.length);
      const result = new Array(l);
      for (let i = 0; i < l; i++) {
        let a = shapeA[shapeA.length - i - 1];
        if (a == null) {
          a = 1;
        }
        let b = shapeB[shapeB.length - i - 1];
        if (b == null) {
          b = 1;
        }
        if (a === 1) {
          result[l - i - 1] = b;
        } else if (b === 1) {
          result[l - i - 1] = a;
        } else if (a !== b) {
          const errMsg = `Operands could not be broadcast together with shapes ${shapeA} and ${shapeB}.`;
          throw Error(errMsg);
        } else {
          result[l - i - 1] = a;
        }
      }
      return result;
    }
    function reshape_(x, shape) {
      const $x = convertToTensor(x, "x", "reshape", "string_or_numeric");
      const inputs = { x: $x };
      const attrs = { shape };
      return ENGINE.runKernel(Reshape, inputs, attrs);
    }
    var reshape = /* @__PURE__ */ op({ reshape_ });
    function sum_(x, axis = null, keepDims = false) {
      let $x = convertToTensor(x, "x", "sum");
      if ($x.dtype === "bool") {
        $x = cast($x, "int32");
      }
      const inputs = { x: $x };
      const attrs = { axis, keepDims };
      return ENGINE.runKernel(Sum, inputs, attrs);
    }
    var sum = /* @__PURE__ */ op({ sum_ });
    var addGradConfig = {
      kernelName: Add,
      inputsToSave: ["a", "b"],
      gradFunc: (dy, saved) => {
        const [a, b] = saved;
        const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
        const derA = () => {
          let res = dy;
          const reduceAxes = getReductionAxes(a.shape, outShape);
          if (reduceAxes.length > 0) {
            res = sum(res, reduceAxes);
          }
          return reshape(res, a.shape);
        };
        const derB = () => {
          let res = dy;
          const reduceAxes = getReductionAxes(b.shape, outShape);
          if (reduceAxes.length > 0) {
            res = sum(res, reduceAxes);
          }
          return reshape(res, b.shape);
        };
        return { a: derA, b: derB };
      }
    };
    var addNGradConfig = {
      kernelName: AddN,
      saveAllInputs: true,
      gradFunc: (dy, saved) => {
        const ders = {};
        saved.forEach((_, i) => {
          ders[i] = () => dy.clone();
        });
        return ders;
      }
    };
    function zerosLike_(x) {
      const $x = convertToTensor(x, "x", "zerosLike");
      const inputs = { x: $x };
      return ENGINE.runKernel(ZerosLike, inputs);
    }
    var zerosLike = /* @__PURE__ */ op({ zerosLike_ });
    var argMaxGradConfig = {
      kernelName: ArgMax,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => zerosLike(x) };
      }
    };
    var argMinGradConfig = {
      kernelName: ArgMin,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => zerosLike(x) };
      }
    };
    var asinGradConfig = {
      kernelName: Asin,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => div(dy, sqrt(sub(scalar(1), square(cast(x, "float32"))))) };
      }
    };
    function add_(a, b) {
      let $a = convertToTensor(a, "a", "add");
      let $b = convertToTensor(b, "b", "add");
      [$a, $b] = makeTypesMatch($a, $b);
      const inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Add, inputs);
    }
    var add = /* @__PURE__ */ op({ add_ });
    var asinhGradConfig = {
      kernelName: Asinh,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return {
          x: () => {
            const a = sqrt(add(scalar(1), square(cast(x, "float32"))));
            return div(dy, a);
          }
        };
      }
    };
    var atan2GradConfig = {
      kernelName: Atan2,
      inputsToSave: ["a", "b"],
      gradFunc: (dy, saved) => {
        const [a, b] = saved;
        const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
        const derA = () => {
          const d = add(square(a), square(b));
          let res = mul(dy, div(b, d));
          const reduceAxes = getReductionAxes(a.shape, outShape);
          if (reduceAxes.length > 0) {
            res = sum(res, reduceAxes);
          }
          return reshape(res, a.shape);
        };
        const derB = () => {
          const d = add(square(a), square(b));
          let res = neg(mul(dy, div(a, d)));
          const reduceAxes = getReductionAxes(b.shape, outShape);
          if (reduceAxes.length > 0) {
            res = sum(res, reduceAxes);
          }
          return reshape(res, b.shape);
        };
        return { a: derA, b: derB };
      }
    };
    var atanGradConfig = {
      kernelName: Atan,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => div(dy, add(square(cast(x, "float32")), 1)) };
      }
    };
    var atanhGradConfig = {
      kernelName: Atanh,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => div(dy, sub(scalar(1), square(cast(x, "float32")))) };
      }
    };
    function computePool2DInfo(inShape, filterSize, strides, dilations, pad2, roundingMode, dataFormat = "channelsLast") {
      const [filterHeight, filterWidth] = parseTupleParam(filterSize);
      let filterShape;
      if (dataFormat === "channelsLast") {
        filterShape = [filterHeight, filterWidth, inShape[3], inShape[3]];
      } else if (dataFormat === "channelsFirst") {
        filterShape = [filterHeight, filterWidth, inShape[1], inShape[1]];
      } else {
        throw new Error(`Unknown dataFormat ${dataFormat}`);
      }
      return computeConv2DInfo(inShape, filterShape, strides, dilations, pad2, roundingMode, false, dataFormat);
    }
    function computeConv2DInfo(inShape, filterShape, strides, dilations, pad2, roundingMode, depthwise = false, dataFormat = "channelsLast") {
      let [batchSize, inHeight, inWidth, inChannels] = [-1, -1, -1, -1];
      if (dataFormat === "channelsLast") {
        [batchSize, inHeight, inWidth, inChannels] = inShape;
      } else if (dataFormat === "channelsFirst") {
        [batchSize, inChannels, inHeight, inWidth] = inShape;
      } else {
        throw new Error(`Unknown dataFormat ${dataFormat}`);
      }
      const [filterHeight, filterWidth, , filterChannels] = filterShape;
      const [strideHeight, strideWidth] = parseTupleParam(strides);
      const [dilationHeight, dilationWidth] = parseTupleParam(dilations);
      const effectiveFilterHeight = getEffectiveFilterSize(filterHeight, dilationHeight);
      const effectiveFilterWidth = getEffectiveFilterSize(filterWidth, dilationWidth);
      const { padInfo, outHeight, outWidth } = getPadAndOutInfo(pad2, inHeight, inWidth, strideHeight, strideWidth, effectiveFilterHeight, effectiveFilterWidth, roundingMode, dataFormat);
      const outChannels = depthwise ? filterChannels * inChannels : filterChannels;
      let outShape;
      if (dataFormat === "channelsFirst") {
        outShape = [batchSize, outChannels, outHeight, outWidth];
      } else if (dataFormat === "channelsLast") {
        outShape = [batchSize, outHeight, outWidth, outChannels];
      }
      return {
        batchSize,
        dataFormat,
        inHeight,
        inWidth,
        inChannels,
        outHeight,
        outWidth,
        outChannels,
        padInfo,
        strideHeight,
        strideWidth,
        filterHeight,
        filterWidth,
        effectiveFilterHeight,
        effectiveFilterWidth,
        dilationHeight,
        dilationWidth,
        inShape,
        outShape,
        filterShape
      };
    }
    function computeOutputShape2D(inShape, fieldSize, stride, zeroPad, roundingMode) {
      if (zeroPad == null) {
        zeroPad = computeDefaultPad(inShape, fieldSize, stride);
      }
      const inputRows = inShape[0];
      const inputCols = inShape[1];
      const outputRows = round$1((inputRows - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
      const outputCols = round$1((inputCols - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
      return [outputRows, outputCols];
    }
    function computeDefaultPad(inputShape, fieldSize, stride, dilation = 1) {
      const effectiveFieldSize = getEffectiveFilterSize(fieldSize, dilation);
      return Math.floor((inputShape[0] * (stride - 1) - stride + effectiveFieldSize) / 2);
    }
    function parseTupleParam(param) {
      if (typeof param === "number") {
        return [param, param, param];
      }
      if (param.length === 2) {
        return [param[0], param[1], 1];
      }
      return param;
    }
    function getEffectiveFilterSize(filterSize, dilation) {
      if (dilation <= 1) {
        return filterSize;
      }
      return filterSize + (filterSize - 1) * (dilation - 1);
    }
    function getPadAndOutInfo(pad2, inHeight, inWidth, strideHeight, strideWidth, filterHeight, filterWidth, roundingMode, dataFormat) {
      let padInfo;
      let outHeight;
      let outWidth;
      if (typeof pad2 === "number") {
        const padType = pad2 === 0 ? "VALID" : "NUMBER";
        padInfo = { top: pad2, bottom: pad2, left: pad2, right: pad2, type: padType };
        const outShape = computeOutputShape2D([inHeight, inWidth], filterHeight, strideHeight, pad2, roundingMode);
        outHeight = outShape[0];
        outWidth = outShape[1];
      } else if (pad2 === "same") {
        outHeight = Math.ceil(inHeight / strideHeight);
        outWidth = Math.ceil(inWidth / strideWidth);
        const padAlongHeight = Math.max(0, (outHeight - 1) * strideHeight + filterHeight - inHeight);
        const padAlongWidth = Math.max(0, (outWidth - 1) * strideWidth + filterWidth - inWidth);
        const top = Math.floor(padAlongHeight / 2);
        const bottom = padAlongHeight - top;
        const left = Math.floor(padAlongWidth / 2);
        const right = padAlongWidth - left;
        padInfo = { top, bottom, left, right, type: "SAME" };
      } else if (pad2 === "valid") {
        padInfo = { top: 0, bottom: 0, left: 0, right: 0, type: "VALID" };
        outHeight = Math.ceil((inHeight - filterHeight + 1) / strideHeight);
        outWidth = Math.ceil((inWidth - filterWidth + 1) / strideWidth);
      } else if (typeof pad2 === "object") {
        const top = dataFormat === "channelsLast" ? pad2[1][0] : pad2[2][0];
        const bottom = dataFormat === "channelsLast" ? pad2[1][1] : pad2[2][1];
        const left = dataFormat === "channelsLast" ? pad2[2][0] : pad2[3][0];
        const right = dataFormat === "channelsLast" ? pad2[2][1] : pad2[3][1];
        const padType = top === 0 && bottom === 0 && left === 0 && right === 0 ? "VALID" : "EXPLICIT";
        padInfo = { top, bottom, left, right, type: padType };
        outHeight = round$1((inHeight - filterHeight + top + bottom) / strideHeight + 1, roundingMode);
        outWidth = round$1((inWidth - filterWidth + left + right) / strideWidth + 1, roundingMode);
      } else {
        throw Error(`Unknown padding parameter: ${pad2}`);
      }
      return { padInfo, outHeight, outWidth };
    }
    function round$1(value, roundingMode) {
      if (!roundingMode) {
        return Math.trunc(value);
      }
      switch (roundingMode) {
        case "round":
          return Math.round(value);
        case "ceil":
          return Math.ceil(value);
        case "floor":
          return Math.floor(value);
        default:
          throw new Error(`Unknown roundingMode ${roundingMode}`);
      }
    }
    function tupleValuesAreOne(param) {
      const [dimA, dimB, dimC] = parseTupleParam(param);
      return dimA === 1 && dimB === 1 && dimC === 1;
    }
    function eitherStridesOrDilationsAreOne(strides, dilations) {
      return tupleValuesAreOne(strides) || tupleValuesAreOne(dilations);
    }
    function stridesOrDilationsArePositive(values) {
      return parseTupleParam(values).every((value) => value > 0);
    }
    function checkPadOnDimRoundingMode(opDesc, pad2, dimRoundingMode) {
      if (dimRoundingMode != null) {
        if (typeof pad2 === "string") {
          throw Error(`Error in ${opDesc}: pad must be an integer when using dimRoundingMode ${dimRoundingMode} but got pad ${pad2}.`);
        } else if (typeof pad2 === "number") {
          assert(isInt(pad2), () => `Error in ${opDesc}: pad must be an integer when using dimRoundingMode ${dimRoundingMode} but got pad ${pad2}.`);
        } else if (typeof pad2 === "object") {
          pad2.forEach((p) => {
            p.forEach((v) => {
              assert(isInt(v), () => `Error in ${opDesc}: pad must be an integer when using dimRoundingMode ${dimRoundingMode} but got pad ${v}.`);
            });
          });
        } else {
          throw Error(`Error in ${opDesc}: Unknown padding parameter: ${pad2}`);
        }
      }
    }
    function avgPool3dGrad_(dy, input, filterSize, strides, pad2, dimRoundingMode) {
      const $dy = convertToTensor(dy, "dy", "avgPool3dGrad");
      const $input = convertToTensor(input, "input", "avgPool3dGrad");
      let dy5D = $dy;
      let input5D = $input;
      let reshapedTo5D = false;
      if ($input.rank === 4) {
        reshapedTo5D = true;
        dy5D = reshape($dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2], $dy.shape[3]]);
        input5D = reshape($input, [
          1,
          $input.shape[0],
          $input.shape[1],
          $input.shape[2],
          $input.shape[3]
        ]);
      }
      assert(dy5D.rank === 5, () => `Error in avgPool3dGrad: dy must be rank 5 but got rank ${dy5D.rank}.`);
      assert(input5D.rank === 5, () => `Error in avgPool3dGrad: input must be rank 5 but got rank ${input5D.rank}.`);
      checkPadOnDimRoundingMode("avgPool3dGrad", pad2, dimRoundingMode);
      const inputs = { dy: dy5D, input: input5D };
      const attrs = { filterSize, strides, pad: pad2, dimRoundingMode };
      const res = ENGINE.runKernel(AvgPool3DGrad, inputs, attrs);
      if (reshapedTo5D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
      }
      return res;
    }
    var avgPool3dGrad = /* @__PURE__ */ op({ avgPool3dGrad_ });
    var avgPool3DGradConfig = {
      kernelName: AvgPool3D,
      inputsToSave: ["x"],
      gradFunc: (dy, saved, attrs) => {
        const [x] = saved;
        const { filterSize, strides, pad: pad2, dimRoundingMode } = attrs;
        return {
          x: () => avgPool3dGrad(dy, x, filterSize, strides, pad2, dimRoundingMode)
        };
      }
    };
    function avgPoolGrad_(dy, input, filterSize, strides, pad2) {
      const $dy = convertToTensor(dy, "dy", "avgPoolGrad");
      const $input = convertToTensor(input, "input", "avgPoolGrad");
      assert($input.rank === $dy.rank, () => `Rank of input (${$input.rank}) does not match rank of dy (${$dy.rank})`);
      let input4D = $input;
      let dy4D = $dy;
      let reshapedTo4D = false;
      if ($input.rank === 3) {
        reshapedTo4D = true;
        input4D = reshape($input, [1, $input.shape[0], $input.shape[1], $input.shape[2]]);
        dy4D = reshape($dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2]]);
      }
      assert(dy4D.rank === 4, () => `Error in avgPoolGrad: dy must be rank 4 but got rank ${dy4D.rank}.`);
      assert(input4D.rank === 4, () => `Error in avgPoolGrad: input must be rank 4 but got rank ${input4D.rank}.`);
      const inputs = { dy: dy4D, input: input4D };
      const attrs = { filterSize, strides, pad: pad2 };
      const res = ENGINE.runKernel(AvgPoolGrad, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var avgPoolGrad = /* @__PURE__ */ op({ avgPoolGrad_ });
    var avgPoolGradConfig = {
      kernelName: AvgPool,
      inputsToSave: ["x"],
      gradFunc: (dy, saved, attrs) => {
        const [x] = saved;
        const { filterSize, strides, pad: pad2 } = attrs;
        return { x: () => avgPoolGrad(dy, x, filterSize, strides, pad2) };
      }
    };
    function matMul_(a, b, transposeA = false, transposeB = false) {
      let $a = convertToTensor(a, "a", "matMul");
      let $b = convertToTensor(b, "b", "matMul");
      [$a, $b] = makeTypesMatch($a, $b);
      const inputs = { a: $a, b: $b };
      const attrs = { transposeA, transposeB };
      return ENGINE.runKernel(BatchMatMul, inputs, attrs);
    }
    var matMul$1 = /* @__PURE__ */ op({ matMul_ });
    var batchMatMulGradConfig = {
      kernelName: BatchMatMul,
      inputsToSave: ["a", "b"],
      gradFunc: (dy, saved, attrs) => {
        const [a, b] = saved;
        const { transposeA, transposeB } = attrs;
        if (!transposeA && !transposeB) {
          return {
            a: () => matMul$1(dy, b, false, true),
            b: () => matMul$1(a, dy, true, false)
          };
        } else if (!transposeA && transposeB) {
          return {
            a: () => matMul$1(dy, b, false, false),
            b: () => matMul$1(dy, a, true, false)
          };
        } else if (transposeA && !transposeB) {
          return {
            a: () => matMul$1(b, dy, false, true),
            b: () => matMul$1(a, dy, false, false)
          };
        } else {
          return {
            a: () => matMul$1(b, dy, true, true),
            b: () => matMul$1(dy, a, true, true)
          };
        }
      }
    };
    function spaceToBatchND_(x, blockShape, paddings) {
      const $x = convertToTensor(x, "x", "spaceToBatchND");
      assert($x.rank >= 1 + blockShape.length, () => `input rank ${$x.rank} should be > than [blockShape] ${blockShape.length}`);
      assert(paddings.length === blockShape.length, () => `paddings.shape[0] ${paddings.length} must be equal to [blockShape] ${blockShape.length}`);
      assert($x.shape.reduce((a, b, i) => {
        if (i > 0 && i <= blockShape.length) {
          return a && (b + paddings[i - 1][0] + paddings[i - 1][1]) % blockShape[i - 1] === 0;
        }
        return a;
      }, true), () => `input spatial dimensions ${$x.shape.slice(1)} with paddings ${paddings.toString()} must be divisible by blockShapes ${blockShape.toString()}`);
      const inputs = { x: $x };
      const attrs = { blockShape, paddings };
      return ENGINE.runKernel(SpaceToBatchND, inputs, attrs);
    }
    var spaceToBatchND = /* @__PURE__ */ op({ spaceToBatchND_ });
    var batchToSpaceNDGradConfig = {
      kernelName: BatchToSpaceND,
      gradFunc: (dy, saved, attrs) => {
        const { blockShape, crops } = attrs;
        return { x: () => spaceToBatchND(dy, blockShape, crops) };
      }
    };
    var broadcastToGradConfig = {
      kernelName: BroadcastTo,
      gradFunc: (dy, saved, attrs) => {
        const broadCastToAttrs = attrs;
        const inputShape = broadCastToAttrs.inputShape;
        const outputShape = broadCastToAttrs.shape;
        const reps = Array.from(outputShape);
        for (let i = inputShape.length - 1; i >= 0; i--) {
          if (inputShape[i] === outputShape[i]) {
            reps[i] = 1;
          } else if (inputShape[i] !== 1) {
            throw new Error(`broadcastTo(): [${inputShape}] cannot be broadcast to [${outputShape}].`);
          }
        }
        const axes = [];
        for (let i = 0; i < reps.length; i++) {
          if (reps[i] > 1) {
            axes.push(i);
          }
        }
        return { x: () => sum(
          dy,
          axes,
          true
          /* keepDims */
        ) };
      }
    };
    var castGradConfig = {
      kernelName: Cast,
      gradFunc: (dy) => {
        return { x: () => dy.clone() };
      }
    };
    var ceilGradConfig = {
      kernelName: Ceil,
      gradFunc: (dy) => {
        return { x: () => zerosLike(dy) };
      }
    };
    function greaterEqual_(a, b) {
      let $a = convertToTensor(a, "a", "greaterEqual", "string_or_numeric");
      let $b = convertToTensor(b, "b", "greaterEqual", "string_or_numeric");
      [$a, $b] = makeTypesMatch($a, $b);
      assertAndGetBroadcastShape($a.shape, $b.shape);
      const inputs = { a: $a, b: $b };
      return ENGINE.runKernel(GreaterEqual, inputs);
    }
    var greaterEqual = /* @__PURE__ */ op({ greaterEqual_ });
    function lessEqual_(a, b) {
      let $a = convertToTensor(a, "a", "lessEqual", "string_or_numeric");
      let $b = convertToTensor(b, "b", "lessEqual", "string_or_numeric");
      [$a, $b] = makeTypesMatch($a, $b);
      assertAndGetBroadcastShape($a.shape, $b.shape);
      const inputs = { a: $a, b: $b };
      return ENGINE.runKernel(LessEqual, inputs);
    }
    var lessEqual = /* @__PURE__ */ op({ lessEqual_ });
    function logicalAnd_(a, b) {
      const $a = convertToTensor(a, "a", "logicalAnd", "bool");
      const $b = convertToTensor(b, "b", "logicalAnd", "bool");
      assertAndGetBroadcastShape($a.shape, $b.shape);
      const inputs = { a: $a, b: $b };
      return ENGINE.runKernel(LogicalAnd, inputs);
    }
    var logicalAnd = /* @__PURE__ */ op({ logicalAnd_ });
    function clone_(x) {
      const $x = convertToTensor(x, "x", "clone", "string_or_numeric");
      const inputs = { x: $x };
      return ENGINE.runKernel(Identity, inputs);
    }
    var clone = /* @__PURE__ */ op({ clone_ });
    function broadcastTo_(x, shape) {
      let input = convertToTensor(x, "broadcastTo", "x");
      const xShape = input.shape;
      assertNonNegativeIntegerDimensions(shape);
      if (shape.length < input.rank) {
        throw new Error(`broadcastTo(): shape.length=${shape.length} < input.rank=${input.rank}.`);
      }
      if (shape.length > input.rank) {
        const newShape = input.shape.slice();
        while (newShape.length < shape.length) {
          newShape.unshift(1);
        }
        input = reshape(input, newShape);
      }
      const inputShape = input.shape;
      const reps = Array.from(shape);
      for (let i = shape.length - 1; i >= 0; i--) {
        if (inputShape[i] === shape[i]) {
          reps[i] = 1;
        } else if (input.shape[i] !== 1) {
          throw new Error(`broadcastTo(): [${xShape}] cannot be broadcast to [${shape}].`);
        }
      }
      const axes = reps.map((n, i) => n > 1 ? i : -1).filter((i) => i >= 0);
      if (axes.length === 0) {
        return clone(input);
      }
      const inputs = { x: input };
      const attrs = { reps };
      return ENGINE.runKernel(Tile, inputs, attrs);
    }
    var broadcastTo = /* @__PURE__ */ op({ broadcastTo_ });
    function where_(condition, a, b) {
      const $a = convertToTensor(a, "a", "where");
      const $b = convertToTensor(b, "b", "where");
      const $condition = convertToTensor(condition, "condition", "where", "bool");
      const broadcastShape = assertAndGetBroadcastShape(assertAndGetBroadcastShape($condition.shape, $a.shape), $b.shape);
      const $broadcastedCondition = broadcastTo($condition, broadcastShape);
      const $broadcastedA = broadcastTo($a, broadcastShape);
      const $broadcastedB = broadcastTo($b, broadcastShape);
      const inputs = {
        condition: $broadcastedCondition,
        t: $broadcastedA,
        e: $broadcastedB
      };
      return ENGINE.runKernel(Select, inputs);
    }
    var where = /* @__PURE__ */ op({ where_ });
    var clipByValueGradConfig = {
      kernelName: ClipByValue,
      inputsToSave: ["x"],
      gradFunc: (dy, saved, attrs) => {
        const [x] = saved;
        const { clipValueMin, clipValueMax } = attrs;
        return {
          x: () => where(logicalAnd(greaterEqual(x, clipValueMin), lessEqual(x, clipValueMax)), dy, zerosLike(dy))
        };
      }
    };
    var complexAbsGradConfig = {
      kernelName: ComplexAbs,
      inputsToSave: ["x"],
      gradFunc: absGradConfig.gradFunc
    };
    function split_(x, numOrSizeSplits, axis = 0) {
      const $x = convertToTensor(x, "x", "split");
      const inputs = { x: $x };
      const attr = { numOrSizeSplits, axis };
      return ENGINE.runKernel(SplitV, inputs, attr);
    }
    var split = /* @__PURE__ */ op({ split_ });
    var concatGradConfig = {
      kernelName: Concat,
      saveAllInputs: true,
      gradFunc: (dy, saved, attrs) => {
        const shapes = saved.map((t) => t.shape);
        const { axis } = attrs;
        const $axis = parseAxisParam(axis, saved[0].shape)[0];
        const sizeSplits = shapes.map((s) => s[$axis]);
        const derTensors = split(dy, sizeSplits, $axis);
        return derTensors.map((t) => () => t);
      }
    };
    function conv2DBackpropFilter_(x, dy, filterShape, strides, pad2, dataFormat = "NHWC", dimRoundingMode) {
      let x4D = x;
      if (x.rank === 3) {
        x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
      }
      let dy4D = dy;
      if (dy4D.rank === 3) {
        dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
      }
      assert(x4D.rank === 4, () => `Error in conv2dDerFilter: input must be rank 4, but got shape ${x4D.shape}.`);
      assert(dy4D.rank === 4, () => `Error in conv2dDerFilter: dy must be rank 4, but got shape ${dy4D.shape}.`);
      assert(filterShape.length === 4, () => `Error in conv2dDerFilter: filterShape must be length 4, but got ${filterShape}.`);
      const inDepth = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
      const outDepth = dataFormat === "NHWC" ? dy4D.shape[3] : dy4D.shape[1];
      assert(inDepth === filterShape[2], () => `Error in conv2dDerFilter: depth of input ${inDepth}) must match input depth in filter (${filterShape[2]}.`);
      assert(outDepth === filterShape[3], () => `Error in conv2dDerFilter: depth of dy (${outDepth}) must match output depth for filter (${filterShape[3]}).`);
      checkPadOnDimRoundingMode("conv2dDerFilter", pad2, dimRoundingMode);
      const inputs = { x: x4D, dy: dy4D };
      const attrs = { strides, pad: pad2, dataFormat, dimRoundingMode, filterShape };
      return ENGINE.runKernel(Conv2DBackpropFilter, inputs, attrs);
    }
    var conv2DBackpropFilter = /* @__PURE__ */ op({ conv2DBackpropFilter_ });
    function conv2DBackpropInput_(xShape, dy, filter, strides, pad2, dataFormat = "NHWC", dimRoundingMode) {
      assert(xShape.length === dy.rank, () => `Length of inShape (${xShape.length}) and rank of dy (${dy.rank}) must match`);
      let xShape4D = xShape;
      let dy4D = dy;
      let reshapedTo4D = false;
      if (dy.rank === 3) {
        reshapedTo4D = true;
        dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
        xShape4D = [1, xShape[0], xShape[1], xShape[2]];
      }
      assert(xShape4D.length === 4, () => `Error in conv2dDerInput: inShape must be length 4, but got length ${xShape4D.length}.`);
      assert(dy4D.rank === 4, () => `Error in conv2dDerInput: dy must be rank 4, but got rank ${dy4D.rank}`);
      assert(filter.rank === 4, () => `Error in conv2dDerInput: filter must be rank 4, but got rank ${filter.rank}`);
      const inDepth = dataFormat === "NHWC" ? xShape4D[3] : xShape4D[1];
      const outDepth = dataFormat === "NHWC" ? dy4D.shape[3] : dy4D.shape[1];
      assert(inDepth === filter.shape[2], () => `Error in conv2dDerInput: depth of input (${inDepth}) must match input depth for filter ${filter.shape[2]}.`);
      assert(outDepth === filter.shape[3], () => `Error in conv2dDerInput: depth of output (${outDepth}) must match output depth for filter ${filter.shape[3]}.`);
      checkPadOnDimRoundingMode("conv2dDerInput", pad2, dimRoundingMode);
      const inputs = { dy: dy4D, filter };
      const attrs = { strides, pad: pad2, dataFormat, dimRoundingMode, inputShape: xShape4D };
      const res = ENGINE.runKernel(Conv2DBackpropInput, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var conv2DBackpropInput = /* @__PURE__ */ op({ conv2DBackpropInput_ });
    var conv2DGradConfig = {
      kernelName: Conv2D,
      inputsToSave: ["x", "filter"],
      gradFunc: (dy, saved, attrs) => {
        const [x4D, $filter] = saved;
        const { dilations, strides, pad: pad2, dataFormat } = attrs;
        assert(tupleValuesAreOne(dilations), () => `Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${dilations}'`);
        return {
          x: () => conv2DBackpropInput(x4D.shape, dy, $filter, strides, pad2, dataFormat),
          filter: () => conv2DBackpropFilter(x4D, dy, $filter.shape, strides, pad2, dataFormat)
        };
      }
    };
    function conv2d_(x, filter, strides, pad2, dataFormat = "NHWC", dilations = [1, 1], dimRoundingMode) {
      const $x = convertToTensor(x, "x", "conv2d", "float32");
      const $filter = convertToTensor(filter, "filter", "conv2d", "float32");
      let x4D = $x;
      let reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, () => `Error in conv2d: input must be rank 4, but got rank ${x4D.rank}.`);
      assert($filter.rank === 4, () => `Error in conv2d: filter must be rank 4, but got rank ${$filter.rank}.`);
      checkPadOnDimRoundingMode("conv2d", pad2, dimRoundingMode);
      const inDepth = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
      assert(inDepth === $filter.shape[2], () => `Error in conv2d: depth of input (${inDepth}) must match input depth for filter ${$filter.shape[2]}.`);
      assert(eitherStridesOrDilationsAreOne(strides, dilations), () => `Error in conv2D: Either strides or dilations must be 1. Got strides ${strides} and dilations '${dilations}'`);
      assert(stridesOrDilationsArePositive(dilations), () => "Error in conv2D: Dilated rates should be larger than 0.");
      assert(stridesOrDilationsArePositive(strides), () => "Error in conv2D: Strides should be larger than 0.");
      const inputs = { x: x4D, filter: $filter };
      const attrs = { strides, pad: pad2, dataFormat, dilations, dimRoundingMode };
      const res = ENGINE.runKernel(Conv2D, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var conv2d$1 = /* @__PURE__ */ op({ conv2d_ });
    var conv2DBackpropInputGradConfig = {
      kernelName: Conv2DBackpropInput,
      inputsToSave: ["dy", "filter"],
      gradFunc: (ddx, saved, attrs) => {
        const [dy, filter] = saved;
        const { strides, pad: pad2, dataFormat, dimRoundingMode } = attrs;
        return {
          dy: () => conv2d$1(ddx, filter, strides, pad2, dataFormat, 1, dimRoundingMode),
          filter: () => conv2DBackpropFilter(ddx, dy, filter.shape, strides, pad2, dataFormat, dimRoundingMode)
        };
      }
    };
    function conv3DBackpropFilter_(x, dy, filterShape, strides, pad2) {
      let x5D = x;
      if (x.rank === 4) {
        x5D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2], x.shape[3]]);
      }
      let dy5D = dy;
      if (dy5D.rank === 4) {
        dy5D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);
      }
      assert(x5D.rank === 5, () => `Error in conv3dDerFilter: input must be rank 5, but got shape ${x5D.shape}.`);
      assert(dy5D.rank === 5, () => `Error in conv3dDerFilter: dy must be rank 5, but got shape ${dy5D.shape}.`);
      assert(filterShape.length === 5, () => `Error in conv3dDerFilter: filterShape must be length 5, but got ${filterShape}.`);
      assert(x5D.shape[4] === filterShape[3], () => `Error in conv3dDerFilter: depth of input ${x5D.shape[4]}) must match input depth in filter (${filterShape[3]}.`);
      assert(dy5D.shape[4] === filterShape[4], () => `Error in conv3dDerFilter: depth of dy (${dy5D.shape[4]}) must match output depth for filter (${filterShape[4]}).`);
      const inputs = { x: x5D, dy: dy5D };
      const attrs = { strides, pad: pad2, filterShape };
      return ENGINE.runKernel(Conv3DBackpropFilterV2, inputs, attrs);
    }
    var conv3DBackpropFilter = /* @__PURE__ */ op({ conv3DBackpropFilter_ });
    function conv3DBackpropInput_(xShape, dy, filter, strides, pad2) {
      assert(xShape.length === dy.rank, () => `Length of inShape (${xShape.length}) and rank of dy (${dy.rank}) must match`);
      let xShape5D = xShape;
      let dy5D = dy;
      let reshapedTo5D = false;
      if (dy.rank === 4) {
        reshapedTo5D = true;
        dy5D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);
        xShape5D = [1, xShape[0], xShape[1], xShape[2], xShape[3]];
      }
      const inDepth = xShape5D[4];
      const outDepth = dy5D.shape[4];
      assert(xShape5D.length === 5, () => `Error in conv3dDerInput: inShape must be length 5, but got length ${xShape5D.length}.`);
      assert(dy5D.rank === 5, () => `Error in conv3dDerInput: dy must be rank 5, but got rank ${dy5D.rank}`);
      assert(filter.rank === 5, () => `Error in conv3dDerInput: filter must be rank 5, but got rank ${filter.rank}`);
      assert(inDepth === filter.shape[3], () => `Error in conv3dDerInput: depth of input (${inDepth}) must match input depth for filter ${filter.shape[3]}.`);
      assert(outDepth === filter.shape[4], () => `Error in conv3dDerInput: depth of output (${outDepth}) must match output depth for filter ${filter.shape[4]}.`);
      const inputs = { dy: dy5D, filter };
      const attrs = { pad: pad2, strides, inputShape: xShape5D };
      const res = ENGINE.runKernel(Conv3DBackpropInputV2, inputs, attrs);
      if (reshapedTo5D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
      }
      return res;
    }
    var conv3DBackpropInput = /* @__PURE__ */ op({ conv3DBackpropInput_ });
    var conv3DGradConfig = {
      kernelName: Conv3D,
      inputsToSave: ["x", "filter"],
      gradFunc: (dy, saved, attrs) => {
        const { dilations, strides, pad: pad2 } = attrs;
        assert(tupleValuesAreOne(dilations), () => `Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${dilations}'`);
        const [x5D, $filter] = saved;
        return {
          x: () => conv3DBackpropInput(x5D.shape, dy, $filter, strides, pad2),
          filter: () => conv3DBackpropFilter(x5D, dy, $filter.shape, strides, pad2)
        };
      }
    };
    function sin_(x) {
      const $x = convertToTensor(x, "x", "sin", "float32");
      const inputs = { x: $x };
      return ENGINE.runKernel(Sin, inputs);
    }
    var sin = /* @__PURE__ */ op({ sin_ });
    var cosGradConfig = {
      kernelName: Cos,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => mul(neg(sin(cast(x, "float32"))), dy) };
      }
    };
    function sinh_(x) {
      const $x = convertToTensor(x, "x", "sinh");
      const inputs = { x: $x };
      return ENGINE.runKernel(Sinh, inputs);
    }
    var sinh = /* @__PURE__ */ op({ sinh_ });
    var coshGradConfig = {
      kernelName: Cosh,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => mul(sinh(cast(x, "float32")), dy) };
      }
    };
    function axesAreInnerMostDims(axes, rank) {
      for (let i = 0; i < axes.length; ++i) {
        if (axes[axes.length - i - 1] !== rank - 1 - i) {
          return false;
        }
      }
      return true;
    }
    function combineLocations(outputLoc, reduceLoc, axes) {
      const rank = outputLoc.length + reduceLoc.length;
      const loc = [];
      let outIdx = 0;
      let reduceIdx = 0;
      for (let dim = 0; dim < rank; dim++) {
        if (axes.indexOf(dim) === -1) {
          loc.push(outputLoc[outIdx++]);
        } else {
          loc.push(reduceLoc[reduceIdx++]);
        }
      }
      return loc;
    }
    function computeOutAndReduceShapes(aShape, axes) {
      const outShape = [];
      const rank = aShape.length;
      for (let dim = 0; dim < rank; dim++) {
        if (axes.indexOf(dim) === -1) {
          outShape.push(aShape[dim]);
        }
      }
      const reduceShape = axes.map((dim) => aShape[dim]);
      return [outShape, reduceShape];
    }
    function expandShapeToKeepDim(shape, axes) {
      const reduceSubShape = axes.map((x) => 1);
      return combineLocations(shape, reduceSubShape, axes);
    }
    function getAxesPermutation(axes, rank) {
      if (axesAreInnerMostDims(axes, rank)) {
        return null;
      }
      const result = [];
      for (let i = 0; i < rank; ++i) {
        if (axes.indexOf(i) === -1) {
          result.push(i);
        }
      }
      axes.forEach((axis) => result.push(axis));
      return result;
    }
    function getUndoAxesPermutation(axes) {
      return axes.map((axis, i) => [i, axis]).sort((a, b) => a[1] - b[1]).map((x) => x[0]);
    }
    function cumsum_(x, axis = 0, exclusive = false, reverse2 = false) {
      const $x = convertToTensor(x, "x", "cumsum");
      const inputs = { x: $x };
      const attrs = { axis, exclusive, reverse: reverse2 };
      return ENGINE.runKernel(Cumsum, inputs, attrs);
    }
    var cumsum = /* @__PURE__ */ op({ cumsum_ });
    function deprecationWarn(msg) {
      if (env().getBool("DEPRECATION_WARNINGS_ENABLED")) {
        console.warn(msg + " You can disable deprecation warnings with tf.disableDeprecationWarnings().");
      }
    }
    setDeprecationWarningFn(deprecationWarn);
    function tidy(nameOrFn, fn) {
      return ENGINE.tidy(nameOrFn, fn);
    }
    function dispose(container) {
      const tensors = getTensorsInContainer(container);
      tensors.forEach((tensor2) => tensor2.dispose());
    }
    function complex_(real2, imag2) {
      const $real = convertToTensor(real2, "real", "complex");
      const $imag = convertToTensor(imag2, "imag", "complex");
      assertShapesMatch($real.shape, $imag.shape, `real and imag shapes, ${$real.shape} and ${$imag.shape}, must match in call to tf.complex().`);
      const inputs = { real: $real, imag: $imag };
      return ENGINE.runKernel(Complex, inputs);
    }
    var complex = /* @__PURE__ */ op({ complex_ });
    function imag_(input) {
      const $input = convertToTensor(input, "input", "imag");
      const inputs = { input: $input };
      return ENGINE.runKernel(Imag, inputs);
    }
    var imag = /* @__PURE__ */ op({ imag_ });
    function real_(input) {
      const $input = convertToTensor(input, "input", "real");
      const inputs = { input: $input };
      return ENGINE.runKernel(Real, inputs);
    }
    var real = /* @__PURE__ */ op({ real_ });
    function transpose_(x, perm, conjugate) {
      const $x = convertToTensor(x, "x", "transpose");
      if (perm == null) {
        perm = $x.shape.map((s, i) => i).reverse();
      }
      assert($x.rank === perm.length, () => `Error in transpose: rank of input ${$x.rank} must match length of perm ${perm}.`);
      perm.forEach((axis) => {
        assert(axis >= 0 && axis < $x.rank, () => `All entries in 'perm' must be between 0 and ${$x.rank - 1} but got ${perm}`);
      });
      if ($x.rank <= 1) {
        return $x.clone();
      }
      const inputs = { x: $x };
      const attrs = { perm };
      if ($x.dtype === "complex64") {
        return tidy(() => {
          let $real = real($x);
          let $imag = imag($x);
          $real = ENGINE.runKernel(Transpose, { x: $real }, attrs);
          $imag = ENGINE.runKernel(Transpose, { x: $imag }, attrs);
          if (conjugate) {
            $imag = neg($imag);
          }
          return complex($real, $imag);
        });
      }
      return ENGINE.runKernel(Transpose, inputs, attrs);
    }
    var transpose = /* @__PURE__ */ op({ transpose_ });
    var cumsumGradConfig = {
      kernelName: Cumsum,
      inputsToSave: ["x"],
      gradFunc: (dy, saved, attrs) => {
        const [x] = saved;
        const { axis, exclusive, reverse: reverse2 } = attrs;
        return {
          x: () => {
            const permutation = getAxesPermutation([axis], x.rank);
            let out = cumsum(dy, axis, exclusive, !reverse2);
            if (permutation != null) {
              out = transpose(out, permutation);
            }
            return out;
          }
        };
      }
    };
    function depthwiseConv2dNativeBackpropFilter_(x, dy, filterShape, strides, pad2, dilations = [1, 1], dimRoundingMode) {
      let x4D = x;
      if (x.rank === 3) {
        x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
      }
      let dy4D = dy;
      if (dy4D.rank === 3) {
        dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
      }
      const inputs = { x: x4D, dy: dy4D };
      const attrs = { strides, pad: pad2, dimRoundingMode, dilations, filterShape };
      return ENGINE.runKernel(DepthwiseConv2dNativeBackpropFilter, inputs, attrs);
    }
    var depthwiseConv2dNativeBackpropFilter = op({ depthwiseConv2dNativeBackpropFilter_ });
    function depthwiseConv2dNativeBackpropInput_(xShape, dy, filter, strides, pad2, dilations = [1, 1], dimRoundingMode) {
      let dy4D = dy;
      let reshapedTo4D = false;
      if (dy.rank === 3) {
        reshapedTo4D = true;
        dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
      }
      const inputs = { dy: dy4D, filter };
      const attrs = { strides, pad: pad2, dimRoundingMode, dilations, inputShape: xShape };
      const res = (
        // tslint:disable-next-line: no-unnecessary-type-assertion
        ENGINE.runKernel(DepthwiseConv2dNativeBackpropInput, inputs, attrs)
      );
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var depthwiseConv2dNativeBackpropInput = op({ depthwiseConv2dNativeBackpropInput_ });
    var depthwiseConv2dNativeGradConfig = {
      kernelName: DepthwiseConv2dNative,
      inputsToSave: ["x", "filter"],
      gradFunc: (dy, saved, attrs) => {
        const { dilations, strides, pad: pad2, dimRoundingMode } = attrs;
        const $dilations = dilations == null ? [1, 1] : dilations;
        assert(tupleValuesAreOne($dilations), () => `Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${$dilations}'`);
        const [x, filter] = saved;
        assert(x.rank === 4, () => `Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${x.rank}.`);
        assert(filter.rank === 4, () => `Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${filter.rank}.`);
        assert(x.shape[3] === filter.shape[2], () => `Error in gradient of depthwiseConv2d: number of input channels (${x.shape[3]}) must match the inChannels dimension in filter ${filter.shape[2]}.`);
        assert(eitherStridesOrDilationsAreOne(strides, $dilations), () => `Error in gradient of depthwiseConv2d: Either strides or dilations must be  1. Got strides ${strides} and dilations '${$dilations}'.`);
        checkPadOnDimRoundingMode("depthwiseConv2d", pad2, dimRoundingMode);
        return {
          x: () => depthwiseConv2dNativeBackpropInput(x.shape, dy, filter, strides, pad2, $dilations, dimRoundingMode),
          filter: () => depthwiseConv2dNativeBackpropFilter(x, dy, filter.shape, strides, pad2, $dilations, dimRoundingMode)
        };
      }
    };
    var dilation2dGradConfig = {
      kernelName: Dilation2D,
      inputsToSave: ["x", "filter"],
      gradFunc: (dy, saved, attrs) => {
        const [x, filter] = saved;
        const inputInputs = { x, filter, dy };
        const filterInputs = { x, filter, dy };
        return {
          x: () => ENGINE.runKernel(Dilation2DBackpropInput, inputInputs, attrs),
          filter: () => ENGINE.runKernel(Dilation2DBackpropFilter, filterInputs, attrs)
        };
      }
    };
    var eluGradConfig = {
      kernelName: Elu,
      outputsToSave: [true],
      gradFunc: (dy, saved) => {
        const [y] = saved;
        const inputs = { dy, y };
        return { x: () => ENGINE.runKernel(EluGrad, inputs) };
      }
    };
    function exp_(x) {
      const $x = convertToTensor(x, "x", "exp");
      const inputs = { x: $x };
      return ENGINE.runKernel(Exp, inputs);
    }
    var exp = /* @__PURE__ */ op({ exp_ });
    var erfGradConfig = {
      kernelName: Erf,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        const a = mul(exp(neg(square(x))), 2 / Math.sqrt(Math.PI));
        return { x: () => mul(dy, a) };
      }
    };
    var expGradConfig = {
      kernelName: Exp,
      outputsToSave: [true],
      gradFunc: (dy, saved) => {
        const [y] = saved;
        return { x: () => mul(dy, y) };
      }
    };
    var expandDimsGradConfig = {
      kernelName: ExpandDims,
      inputsToSave: ["input"],
      gradFunc: (dy, saved) => {
        const [input] = saved;
        return { input: () => reshape(dy, input.shape) };
      }
    };
    var expm1GradConfig = {
      kernelName: Expm1,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => mul(dy, exp(x)) };
      }
    };
    var floorGradConfig = {
      kernelName: Floor,
      gradFunc: (dy) => {
        return { x: () => zerosLike(dy) };
      }
    };
    var floorDivGradConfig = {
      kernelName: FloorDiv,
      inputsToSave: ["a", "b"],
      gradFunc: (dy, saved) => {
        const [a, b] = saved;
        const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
        const derA = () => {
          const res = div(dy, cast(b, "float32"));
          const reduceAxes = getReductionAxes(a.shape, outShape);
          if (reduceAxes.length > 0) {
            return reshape(sum(res, reduceAxes), a.shape);
          }
          return res;
        };
        const derB = () => {
          let res = mul(dy, cast(a, "float32"));
          const reduceAxes = getReductionAxes(b.shape, outShape);
          if (reduceAxes.length > 0) {
            res = reshape(sum(res, reduceAxes), b.shape);
          }
          const tmp = square(b);
          return neg(div(res, cast(tmp, "float32")));
        };
        return { a: derA, b: derB };
      }
    };
    function rsqrt_(x) {
      const $x = convertToTensor(x, "x", "rsqrt", "float32");
      const inputs = { x: $x };
      return ENGINE.runKernel(Rsqrt, inputs);
    }
    var rsqrt = /* @__PURE__ */ op({ rsqrt_ });
    function tile_(x, reps) {
      const $x = convertToTensor(x, "x", "tile", "string_or_numeric");
      assert($x.rank === reps.length, () => `Error in transpose: rank of input ${$x.rank} must match length of reps ${reps}.`);
      const inputs = { x: $x };
      const attrs = { reps };
      return ENGINE.runKernel(Tile, inputs, attrs);
    }
    var tile = /* @__PURE__ */ op({ tile_ });
    var fusedBatchNormGradConfig = {
      kernelName: FusedBatchNorm,
      inputsToSave: ["x", "mean", "variance", "scale"],
      gradFunc: (dy, saved, attrs) => {
        const { varianceEpsilon } = attrs;
        const [x, mean2, variance, scale] = saved;
        const scaleValue = scale == null ? scalar(1) : scale;
        const reductionAxes = getReductionAxes(mean2.shape, x.shape);
        const tileShape = [];
        if (mean2.rank === 1) {
          for (let i = 0; i < x.shape.length - 1; ++i) {
            tileShape.push(x.shape[i]);
          }
          tileShape.push(1);
        }
        const xMinusMean = sub(x, mean2);
        const dyTimesScaleValue = mul(dy, scaleValue);
        const oneOverSqrtVariance = rsqrt(add(variance, scalar(varianceEpsilon)));
        const minusHalfRCube = mul(mul(mul(oneOverSqrtVariance, oneOverSqrtVariance), oneOverSqrtVariance), scalar(-0.5));
        const derX = () => {
          if (mean2.rank === 1) {
            return reshape(mul(mul(dy, tile(reshape(oneOverSqrtVariance, [1, 1, 1, mean2.shape[0]]), tileShape)), scaleValue), x.shape);
          } else {
            return reshape(mul(mul(dy, oneOverSqrtVariance), scaleValue), x.shape);
          }
        };
        const derMean = () => {
          let meanDer = mul(mul(oneOverSqrtVariance, scalar(-1)), dyTimesScaleValue);
          if (mean2.rank === 1) {
            meanDer = sum(meanDer, reductionAxes);
          }
          return reshape(meanDer, mean2.shape);
        };
        const derVariance = () => {
          let varianceDer = mul(mul(minusHalfRCube, xMinusMean), dyTimesScaleValue);
          if (mean2.rank === 1) {
            varianceDer = sum(varianceDer, reductionAxes);
          }
          return reshape(varianceDer, mean2.shape);
        };
        const derScale = () => {
          const xMinusMean2TimesRsqrt = mul(xMinusMean, oneOverSqrtVariance);
          let scaleDer = mul(dy, xMinusMean2TimesRsqrt);
          if (mean2.rank === 1) {
            scaleDer = sum(scaleDer, reductionAxes);
          }
          return reshape(scaleDer, mean2.shape);
        };
        const derOffset = () => {
          let offsetDer = dy;
          if (mean2.rank === 1) {
            offsetDer = sum(offsetDer, reductionAxes);
          }
          return reshape(offsetDer, mean2.shape);
        };
        return {
          x: derX,
          mean: derMean,
          variance: derVariance,
          scale: derScale,
          offset: derOffset
        };
      }
    };
    function stack_(tensors, axis = 0) {
      const $tensors = convertToTensorArray(tensors, "tensors", "stack", "string_or_numeric");
      assert($tensors.length >= 1, () => "Pass at least one tensor to tf.stack");
      if ($tensors.length > 0) {
        assert(axis <= $tensors[0].rank, () => "Axis must be <= rank of the tensor");
      }
      const inputs = $tensors;
      const attrs = { axis };
      return ENGINE.runKernel(Pack, inputs, attrs);
    }
    var stack = /* @__PURE__ */ op({ stack_ });
    function unsortedSegmentSum_(x, segmentIds, numSegments) {
      const $x = convertToTensor(x, "x", "unsortedSegmentSum");
      const $segmentIds = convertToTensor(segmentIds, "segmentIds", "unsortedSegmentSum", "int32");
      assert(isInt(numSegments), () => "numSegments must be of dtype int");
      const inputs = { x: $x, segmentIds: $segmentIds };
      const attrs = { numSegments };
      return ENGINE.runKernel(UnsortedSegmentSum, inputs, attrs);
    }
    var unsortedSegmentSum = /* @__PURE__ */ op({ unsortedSegmentSum_ });
    var gatherGradConfig = {
      kernelName: GatherV2,
      inputsToSave: ["x", "indices"],
      gradFunc: (dy, saved, attrs) => {
        const [x, indices] = saved;
        const { axis, batchDims } = attrs;
        const parsedAxis = parseAxisParam(axis, x.shape)[0];
        const derXBatch = (x2, indices2, dy2) => {
          return () => {
            const paramsShape = x2.shape;
            const indicesSize = indices2.size;
            const outerShape = paramsShape.slice(0, parsedAxis);
            const outerDims = outerShape.length;
            const innerShape = paramsShape.slice(axis, paramsShape.length).slice(1);
            const innerDims = innerShape.length;
            const outerAxesIndices = arrayRange(0, outerDims);
            const innerAxesIndices = arrayRange(outerDims + 1, outerDims + 1 + innerDims);
            const valuesShape = arrayConcat([
              outerShape,
              [indicesSize],
              innerShape
            ]);
            const values = reshape(dy2, valuesShape);
            const reshapedIndices = reshape(indices2, [indicesSize]);
            const transposeDims = arrayConcat([[outerDims], outerAxesIndices, innerAxesIndices]);
            const valuesTranspose = transpose(values, transposeDims);
            let paramsGrad = unsortedSegmentSum(valuesTranspose, reshapedIndices, x2.shape[parsedAxis]);
            const invertTransposeDims = getUndoAxesPermutation(transposeDims);
            paramsGrad = transpose(paramsGrad, invertTransposeDims);
            return paramsGrad;
          };
        };
        if (batchDims === 1) {
          const batchSize = x.shape[0];
          const xBatch = x.split(batchSize, 0);
          const derXBatched = () => {
            const stacked = stack(xBatch.map((x2, i) => {
              return derXBatch(x2, indices.slice(i, 1), dy.slice(i, 1))();
            }));
            return stacked.reshape(x.shape);
          };
          return { x: derXBatched, indices: () => indices };
        } else {
          return { x: derXBatch(x, indices, dy), indices: () => indices };
        }
      }
    };
    function arrayRange(start, stop) {
      const result = [];
      for (let i = start; i < stop; ++i) {
        result.push(i);
      }
      return result;
    }
    function arrayConcat(arrays) {
      const result = [];
      for (let i = 0; i < arrays.length; ++i) {
        for (let j = 0; j < arrays[i].length; ++j) {
          result.push(arrays[i][j]);
        }
      }
      return result;
    }
    var greaterEqualGradConfig = {
      kernelName: GreaterEqual,
      inputsToSave: ["a", "b"],
      gradFunc: (dy, saved) => {
        const [a, b] = saved;
        return { a: () => zerosLike(a), b: () => zerosLike(b) };
      }
    };
    var identityGradConfig = {
      kernelName: Identity,
      gradFunc: (dy) => {
        return { x: () => cast(dy, "float32") };
      }
    };
    var isFiniteGradConfig = {
      kernelName: IsFinite,
      gradFunc: (dy) => {
        return { x: () => zerosLike(dy) };
      }
    };
    var isInfGradConfig = {
      kernelName: IsInf,
      gradFunc: (dy) => {
        return { x: () => zerosLike(dy) };
      }
    };
    var isNanGradConfig = {
      kernelName: IsNan,
      gradFunc: (dy) => {
        return { x: () => zerosLike(dy) };
      }
    };
    function greater_(a, b) {
      let $a = convertToTensor(a, "a", "greater", "string_or_numeric");
      let $b = convertToTensor(b, "b", "greater", "string_or_numeric");
      [$a, $b] = makeTypesMatch($a, $b);
      assertAndGetBroadcastShape($a.shape, $b.shape);
      const inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Greater, inputs);
    }
    var greater = /* @__PURE__ */ op({ greater_ });
    var leakyReluGradConfig = {
      kernelName: LeakyRelu,
      inputsToSave: ["x"],
      gradFunc: (dy, saved, attrs) => {
        const [x] = saved;
        const { alpha } = attrs;
        const mask = greater(x, 0);
        return { x: () => where(mask, dy, mul(dy, alpha)) };
      }
    };
    var log1pGradConfig = {
      kernelName: Log1p,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => div(dy, add(x, 1)) };
      }
    };
    var logGradConfig = {
      kernelName: Log,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => div(dy, cast(x, "float32")) };
      }
    };
    var logSoftmaxGradConfig = {
      kernelName: LogSoftmax,
      inputsToSave: [],
      outputsToSave: [true],
      gradFunc: (dy, saved, attrs) => {
        const [value] = saved;
        const { axis } = attrs;
        return {
          logits: () => {
            const keepDims = true;
            const softmax2 = exp(value);
            return sub(dy, mul(sum(dy, axis, keepDims), softmax2));
          }
        };
      }
    };
    function localResponseNormalizationBackprop_(x, y, dy, depthRadius = 5, bias = 1, alpha = 1, beta = 0.5) {
      const inputs = { x, y, dy };
      const attrs = { depthRadius, bias, alpha, beta };
      return ENGINE.runKernel(LRNGrad, inputs, attrs);
    }
    var localResponseNormalizationBackprop = op({ localResponseNormalizationBackprop_ });
    var lrnGradConfig = {
      kernelName: LRN,
      inputsToSave: ["x"],
      outputsToSave: [true],
      gradFunc: (dy, saved, attrs) => {
        const [x, y] = saved;
        const { depthRadius, bias, alpha, beta } = attrs;
        return {
          x: () => localResponseNormalizationBackprop(x, y, dy, depthRadius, bias, alpha, beta)
        };
      }
    };
    function equal_(a, b) {
      let $a = convertToTensor(a, "a", "equal", "string_or_numeric");
      let $b = convertToTensor(b, "b", "equal", "string_or_numeric");
      [$a, $b] = makeTypesMatch($a, $b);
      assertAndGetBroadcastShape($a.shape, $b.shape);
      const inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Equal, inputs);
    }
    var equal = /* @__PURE__ */ op({ equal_ });
    function gradForMinAndMax(dy, y, xOrig, origAxes) {
      if (y.rank < xOrig.rank) {
        y = reshape(y, expandShapeToKeepDim(y.shape, origAxes));
      }
      if (dy.rank < xOrig.rank) {
        dy = reshape(dy, expandShapeToKeepDim(dy.shape, origAxes));
      }
      return {
        x: () => {
          const dx = mul(dy, cast(equal(xOrig, y), dy.dtype));
          return dx;
        }
      };
    }
    var maxGradConfig = {
      kernelName: Max,
      inputsToSave: ["x"],
      outputsToSave: [true],
      gradFunc: (dy, saved, attrs) => {
        const maxAttrs = attrs;
        const { reductionIndices } = maxAttrs;
        const x = saved[0];
        const y = saved[1];
        const origAxes = parseAxisParam(reductionIndices, x.shape);
        const maxGrad = gradForMinAndMax(dy, y, x, origAxes);
        return {
          x: () => {
            return maxGrad["x"]();
          }
        };
      }
    };
    function less_(a, b) {
      let $a = convertToTensor(a, "a", "less", "string_or_numeric");
      let $b = convertToTensor(b, "b", "less", "string_or_numeric");
      [$a, $b] = makeTypesMatch($a, $b);
      assertAndGetBroadcastShape($a.shape, $b.shape);
      const inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Less, inputs);
    }
    var less = /* @__PURE__ */ op({ less_ });
    var maximumGradConfig = {
      kernelName: Maximum,
      inputsToSave: ["a", "b"],
      gradFunc: (dy, saved) => {
        const [a, b] = saved;
        const derA = () => mul(dy, cast(greaterEqual(a, b), "float32"));
        const derB = () => mul(dy, cast(less(a, b), "float32"));
        return { a: derA, b: derB };
      }
    };
    function maxPool3dGrad_(dy, input, output, filterSize, strides, pad2, dimRoundingMode) {
      const $dy = convertToTensor(dy, "dy", "maxPool3dGrad");
      const $input = convertToTensor(input, "input", "maxPool3dGrad");
      const $output = convertToTensor(output, "output", "maxPool3dGrad");
      let dy5D = $dy;
      let input5D = $input;
      let output5D = $output;
      let reshapedTo5D = false;
      if ($input.rank === 4) {
        reshapedTo5D = true;
        dy5D = reshape($dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2], $dy.shape[3]]);
        input5D = reshape($input, [
          1,
          $input.shape[0],
          $input.shape[1],
          $input.shape[2],
          $input.shape[3]
        ]);
        output5D = reshape($output, [
          1,
          $output.shape[0],
          $output.shape[1],
          $output.shape[2],
          $output.shape[3]
        ]);
      }
      assert(dy5D.rank === 5, () => `Error in maxPool3dGrad: dy must be rank 5 but got rank ${dy5D.rank}.`);
      assert(input5D.rank === 5, () => `Error in maxPool3dGrad: input must be rank 5 but got rank ${input5D.rank}.`);
      assert(output5D.rank === 5, () => `Error in maxPool3dGrad: output must be rank 5 but got rank ${output5D.rank}.`);
      checkPadOnDimRoundingMode("maxPool3dGrad", pad2, dimRoundingMode);
      const inputs = { dy: dy5D, input: input5D, output: output5D };
      const attrs = { filterSize, strides, pad: pad2, dimRoundingMode };
      const res = ENGINE.runKernel(MaxPool3DGrad, inputs, attrs);
      if (reshapedTo5D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
      }
      return res;
    }
    var maxPool3dGrad = /* @__PURE__ */ op({ maxPool3dGrad_ });
    var maxPool3DGradConfig = {
      kernelName: MaxPool3D,
      inputsToSave: ["x"],
      outputsToSave: [true],
      gradFunc: (dy, saved, attrs) => {
        const [x, y] = saved;
        const { filterSize, strides, pad: pad2, dimRoundingMode } = attrs;
        return {
          x: () => maxPool3dGrad(dy, x, y, filterSize, strides, pad2, dimRoundingMode)
        };
      }
    };
    function maxPoolGrad_(dy, input, output, filterSize, strides, pad2, dimRoundingMode) {
      const $dy = convertToTensor(dy, "dy", "maxPoolGrad");
      const $input = convertToTensor(input, "input", "maxPoolGrad");
      const $output = convertToTensor(output, "output", "maxPoolGrad");
      assert($input.rank === $dy.rank, () => `Rank of input (${$input.rank}) does not match rank of dy (${$dy.rank})`);
      assert($dy.rank === 4, () => `Error in maxPoolGrad: dy must be rank 4 but got rank ${$dy.rank}.`);
      assert($input.rank === 4, () => `Error in maxPoolGrad: input must be rank 4 but got rank ${$input.rank}.`);
      checkPadOnDimRoundingMode("maxPoolGrad", pad2, dimRoundingMode);
      const inputs = { dy: $dy, input: $input, output: $output };
      const attrs = { filterSize, strides, pad: pad2, dimRoundingMode };
      return ENGINE.runKernel(MaxPoolGrad, inputs, attrs);
    }
    var maxPoolGrad = /* @__PURE__ */ op({ maxPoolGrad_ });
    var maxPoolGradConfig = {
      kernelName: MaxPool,
      inputsToSave: ["x"],
      outputsToSave: [true],
      gradFunc: (dy, saved, attrs) => {
        const [x, y] = saved;
        const { filterSize, strides, pad: pad2 } = attrs;
        return {
          x: () => maxPoolGrad(dy, x, y, filterSize, strides, pad2)
        };
      }
    };
    function zeros(shape, dtype = "float32") {
      assertNonNegativeIntegerDimensions(shape);
      if (dtype === "complex64") {
        const real2 = zeros(shape, "float32");
        const imag2 = zeros(shape, "float32");
        return complex(real2, imag2);
      }
      const values = makeZerosTypedArray(sizeFromShape(shape), dtype);
      return ENGINE.makeTensor(values, shape, dtype);
    }
    function ones(shape, dtype = "float32") {
      assertNonNegativeIntegerDimensions(shape);
      if (dtype === "complex64") {
        const real2 = ones(shape, "float32");
        const imag2 = zeros(shape, "float32");
        return complex(real2, imag2);
      }
      const values = makeOnesTypedArray(sizeFromShape(shape), dtype);
      return ENGINE.makeTensor(values, shape, dtype);
    }
    var meanGradConfig = {
      kernelName: Mean,
      inputsToSave: ["x"],
      gradFunc: (dy, saved, attrs) => {
        const [x] = saved;
        const { axis } = attrs;
        const axes = parseAxisParam(axis, x.shape);
        const shapes = computeOutAndReduceShapes(x.shape, axes);
        const reduceShape = shapes[1];
        const reduceSize = sizeFromShape(reduceShape);
        const derX = () => {
          const expandedDyShape = x.shape.slice();
          axes.forEach((axis2) => {
            expandedDyShape[axis2] = 1;
          });
          const expandedDy = reshape(dy, expandedDyShape);
          const res = div(mul(expandedDy, ones(x.shape, "float32")), reduceSize);
          return res;
        };
        return { x: derX };
      }
    };
    var minGradConfig = {
      kernelName: Min,
      inputsToSave: ["x"],
      outputsToSave: [true],
      gradFunc: (dy, saved, attrs) => {
        const minAttrs = attrs;
        const { axis } = minAttrs;
        const [x, y] = saved;
        const origAxes = parseAxisParam(axis, x.shape);
        const minGrad = gradForMinAndMax(dy, y, x, origAxes);
        return {
          x: () => {
            return minGrad["x"]();
          }
        };
      }
    };
    var minimumGradConfig = {
      kernelName: Minimum,
      inputsToSave: ["a", "b"],
      gradFunc: (dy, saved) => {
        const [a, b] = saved;
        const derA = () => mul(dy, cast(lessEqual(a, b), "float32"));
        const derB = () => mul(dy, cast(greater(a, b), "float32"));
        return { a: derA, b: derB };
      }
    };
    function slice_(x, begin, size) {
      const $x = convertToTensor(x, "x", "slice", "string_or_numeric");
      if ($x.rank === 0) {
        throw new Error("Slicing scalar is not possible");
      }
      const inputs = { x: $x };
      const attrs = { begin, size };
      return ENGINE.runKernel(Slice, inputs, attrs);
    }
    var slice = /* @__PURE__ */ op({ slice_ });
    var mirrorPadGradConfig = {
      kernelName: MirrorPad,
      inputsToSave: ["x"],
      gradFunc: (dy, saved, attrs) => {
        const x = saved[0];
        const { paddings } = attrs;
        const begin = paddings.map((p) => p[0]);
        return { x: () => slice(dy, begin, x.shape) };
      }
    };
    function floor_(x) {
      const $x = convertToTensor(x, "x", "floor", "float32");
      const inputs = { x: $x };
      return ENGINE.runKernel(Floor, inputs);
    }
    var floor = /* @__PURE__ */ op({ floor_ });
    var modGradConfig = {
      kernelName: Mod,
      inputsToSave: ["a", "b"],
      gradFunc: (dy, saved) => {
        const [a, b] = saved;
        const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
        const derA = () => {
          const reduceAxes = getReductionAxes(a.shape, outShape);
          if (reduceAxes.length > 0) {
            return reshape(sum(dy, reduceAxes), a.shape);
          }
          return dy;
        };
        const derB = () => {
          const res = mul(dy, neg(floor(div(a, b))));
          const reduceAxes = getReductionAxes(b.shape, outShape);
          if (reduceAxes.length > 0) {
            return reshape(sum(res, reduceAxes), b.shape);
          }
          return res;
        };
        return { a: derA, b: derB };
      }
    };
    var multiplyGradConfig = {
      kernelName: Multiply,
      inputsToSave: ["a", "b"],
      gradFunc: (dy, saved) => {
        const [a, b] = saved;
        const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
        const derA = () => {
          const res = mul(dy, cast(b, "float32"));
          const reduceAxes = getReductionAxes(a.shape, outShape);
          if (reduceAxes.length > 0) {
            return reshape(sum(res, reduceAxes), a.shape);
          }
          return res;
        };
        const derB = () => {
          const res = mul(dy, cast(a, "float32"));
          const reduceAxes = getReductionAxes(b.shape, outShape);
          if (reduceAxes.length > 0) {
            return reshape(sum(res, reduceAxes), b.shape);
          }
          return res;
        };
        return { a: derA, b: derB };
      }
    };
    var negGradConfig = {
      kernelName: Neg,
      gradFunc: (dy) => {
        return { x: () => neg(dy) };
      }
    };
    var oneHotGradConfig = {
      kernelName: OneHot,
      inputsToSave: ["indices"],
      gradFunc: (dy, saved) => {
        const indices = saved[0];
        return { indices: () => zeros(indices.shape, "float32") };
      }
    };
    var onesLikeGradConfig = {
      kernelName: OnesLike,
      gradFunc: (dy) => {
        return { x: () => zerosLike(dy) };
      }
    };
    function unstack_(x, axis = 0) {
      const $x = convertToTensor(x, "x", "unstack", "string_or_numeric");
      assert(axis >= -$x.shape.length && axis < $x.shape.length, () => `Axis = ${axis} is not in [-${$x.shape.length}, ${$x.shape.length})`);
      const inputs = { value: $x };
      const attrs = { axis };
      return ENGINE.runKernel(Unpack, inputs, attrs);
    }
    var unstack = /* @__PURE__ */ op({ unstack_ });
    var packGradConfig = {
      kernelName: Pack,
      saveAllInputs: true,
      gradFunc: (dy, saved, attrs) => {
        const { axis } = attrs;
        const derTensors = unstack(dy, axis);
        return derTensors.map((t) => () => t);
      }
    };
    var padV2GradConfig = {
      kernelName: PadV2,
      inputsToSave: ["x"],
      gradFunc: (dy, saved, attrs) => {
        const x = saved[0];
        const { paddings } = attrs;
        const begin = paddings.map((p) => p[0]);
        return { x: () => slice(dy, begin, x.shape) };
      }
    };
    function log_(x) {
      const $x = convertToTensor(x, "x", "log", "float32");
      const inputs = { x: $x };
      return ENGINE.runKernel(Log, inputs);
    }
    var log = /* @__PURE__ */ op({ log_ });
    function pow_(base, exp2) {
      let $base = convertToTensor(base, "base", "pow");
      let $exp = convertToTensor(exp2, "exp", "pow");
      [$base, $exp] = makeTypesMatch($base, $exp);
      const inputs = { a: $base, b: $exp };
      return ENGINE.runKernel(Pow, inputs);
    }
    var pow = /* @__PURE__ */ op({ pow_ });
    var powGradConfig = {
      kernelName: Pow,
      inputsToSave: ["a", "b"],
      outputsToSave: [true],
      gradFunc: (dy, saved) => {
        const [a, b, y] = saved;
        const base = a;
        const exp2 = b;
        const outShape = assertAndGetBroadcastShape(base.shape, exp2.shape);
        const derBase = () => {
          const expFloat = cast(exp2, "float32");
          let res = mul(dy, mul(expFloat, pow(base, sub(expFloat, scalar(1)))));
          const reduceAxes = getReductionAxes(base.shape, outShape);
          if (reduceAxes.length > 0) {
            res = sum(res, reduceAxes);
          }
          return reshape(res, base.shape);
        };
        const derExp = () => {
          const condition = greater(base, 0);
          const logBase = where(condition, log(base), zerosLike(base));
          let res = mul(dy, mul(y, logBase));
          const reduceAxes = getReductionAxes(exp2.shape, outShape);
          if (reduceAxes.length > 0) {
            res = sum(res, reduceAxes);
          }
          return reshape(res, exp2.shape);
        };
        return { a: derBase, b: derExp };
      }
    };
    var preluGradConfig = {
      kernelName: Prelu,
      inputsToSave: ["x", "alpha"],
      gradFunc: (dy, saved) => {
        const [x, alpha] = saved;
        const mask = greater(x, 0);
        return {
          x: () => where(mask, dy, mul(dy, alpha)),
          alpha: () => {
            let res = where(mask, zerosLike(dy), mul(dy, x));
            const reduceAxes = getReductionAxes(alpha.shape, dy.shape);
            if (reduceAxes.length > 0) {
              res = sum(res, reduceAxes);
            }
            return reshape(res, alpha.shape);
          }
        };
      }
    };
    function isBrowser() {
      return typeof window !== "undefined" && window.document != null || //@ts-ignore
      typeof WorkerGlobalScope !== "undefined";
    }
    var ENV = env();
    ENV.registerFlag("DEBUG", () => false, (debugValue) => {
      if (debugValue) {
        console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.");
      }
    });
    ENV.registerFlag("IS_BROWSER", () => isBrowser());
    ENV.registerFlag("IS_NODE", () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined");
    ENV.registerFlag("IS_CHROME", () => typeof navigator !== "undefined" && navigator != null && navigator.userAgent != null && /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor));
    ENV.registerFlag("IS_SAFARI", () => typeof navigator !== "undefined" && navigator != null && navigator.userAgent != null && /Safari/.test(navigator.userAgent) && /Apple/.test(navigator.vendor));
    ENV.registerFlag("PROD", () => false);
    ENV.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY", () => ENV.getBool("DEBUG"));
    ENV.registerFlag("DEPRECATION_WARNINGS_ENABLED", () => true);
    ENV.registerFlag("IS_TEST", () => false);
    ENV.registerFlag("CHECK_COMPUTATION_FOR_ERRORS", () => ENV.getBool("DEBUG"));
    ENV.registerFlag("WRAP_TO_IMAGEBITMAP", () => false);
    ENV.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU", () => false);
    ENV.registerFlag("USE_SETTIMEOUTCUSTOM", () => false);
    var CompositeArrayBuffer = class _CompositeArrayBuffer {
      /**
       * Concatenate a number of ArrayBuffers into one.
       *
       * @param buffers An array of ArrayBuffers to concatenate, or a single
       *     ArrayBuffer.
       * @returns Result of concatenating `buffers` in order.
       */
      static join(buffers) {
        return new _CompositeArrayBuffer(buffers).slice();
      }
      constructor(buffers) {
        this.shards = [];
        this.previousShardIndex = 0;
        if (buffers == null) {
          return;
        }
        if (!(buffers instanceof Array)) {
          buffers = [buffers];
        }
        buffers = buffers.map((bufferOrTypedArray) => {
          if (isTypedArray(bufferOrTypedArray)) {
            return bufferOrTypedArray.buffer;
          }
          return bufferOrTypedArray;
        });
        if (buffers.length === 0) {
          return;
        }
        this.bufferUniformSize = buffers[0].byteLength;
        let start = 0;
        for (let i = 0; i < buffers.length; i++) {
          const buffer2 = buffers[i];
          if (i !== buffers.length - 1 && buffer2.byteLength !== this.bufferUniformSize) {
            this.bufferUniformSize = void 0;
          }
          const end = start + buffer2.byteLength;
          this.shards.push({ buffer: buffer2, start, end });
          start = end;
        }
        if (this.shards.length === 0) {
          this.byteLength = 0;
        }
        this.byteLength = this.shards[this.shards.length - 1].end;
      }
      slice(start = 0, end = this.byteLength) {
        if (this.shards.length === 0) {
          return new ArrayBuffer(0);
        }
        start = isNaN(Number(start)) ? 0 : start;
        end = isNaN(Number(end)) ? 0 : end;
        start = Math.max(0, start);
        end = Math.min(this.byteLength, end);
        if (end <= start) {
          return new ArrayBuffer(0);
        }
        const startShardIndex = this.findShardForByte(start);
        if (startShardIndex === -1) {
          throw new Error(`Could not find start shard for byte ${start}`);
        }
        const size = end - start;
        const outputBuffer = new ArrayBuffer(size);
        const outputArray = new Uint8Array(outputBuffer);
        let sliced = 0;
        for (let i = startShardIndex; i < this.shards.length; i++) {
          const shard = this.shards[i];
          const globalStart = start + sliced;
          const localStart = globalStart - shard.start;
          const outputStart = sliced;
          const globalEnd = Math.min(end, shard.end);
          const localEnd = globalEnd - shard.start;
          const outputSlice = new Uint8Array(shard.buffer, localStart, localEnd - localStart);
          outputArray.set(outputSlice, outputStart);
          sliced += outputSlice.length;
          if (end < shard.end) {
            break;
          }
        }
        return outputBuffer;
      }
      /**
       * Get the index of the shard that contains the byte at `byteIndex`.
       */
      findShardForByte(byteIndex) {
        if (this.shards.length === 0 || byteIndex < 0 || byteIndex >= this.byteLength) {
          return -1;
        }
        if (this.bufferUniformSize != null) {
          this.previousShardIndex = Math.floor(byteIndex / this.bufferUniformSize);
          return this.previousShardIndex;
        }
        function check(shard) {
          if (byteIndex < shard.start) {
            return -1;
          }
          if (byteIndex >= shard.end) {
            return 1;
          }
          return 0;
        }
        if (check(this.shards[this.previousShardIndex]) === 0) {
          return this.previousShardIndex;
        }
        const index2 = search(this.shards, check);
        if (index2 === -1) {
          return -1;
        }
        this.previousShardIndex = index2;
        return this.previousShardIndex;
      }
    };
    function search(sortedArray, compare) {
      let min2 = 0;
      let max2 = sortedArray.length;
      while (min2 <= max2) {
        const middle = Math.floor((max2 - min2) / 2) + min2;
        const side = compare(sortedArray[middle]);
        if (side === 0) {
          return middle;
        } else if (side < 0) {
          max2 = middle;
        } else {
          min2 = middle + 1;
        }
      }
      return -1;
    }
    var useNodeBuffer = typeof Buffer !== "undefined" && (typeof Blob === "undefined" || typeof atob === "undefined" || typeof btoa === "undefined");
    function stringByteLength(str) {
      if (useNodeBuffer) {
        return Buffer.byteLength(str, "utf8");
      }
      return new Blob([str]).size;
    }
    function arrayBufferToBase64String(buffer2) {
      if (useNodeBuffer) {
        return Buffer.from(buffer2).toString("base64");
      }
      const buf = new Uint8Array(buffer2);
      let s = "";
      for (let i = 0, l = buf.length; i < l; i++) {
        s += String.fromCharCode(buf[i]);
      }
      return btoa(s);
    }
    function base64StringToArrayBuffer(str) {
      if (useNodeBuffer) {
        const buf = Buffer.from(str, "base64");
        return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
      }
      const s = atob(str);
      const buffer2 = new Uint8Array(s.length);
      for (let i = 0; i < s.length; ++i) {
        buffer2.set([s.charCodeAt(i)], i);
      }
      return buffer2.buffer;
    }
    function getModelJSONForModelArtifacts(artifacts, manifest) {
      const result = {
        modelTopology: artifacts.modelTopology,
        format: artifacts.format,
        generatedBy: artifacts.generatedBy,
        convertedBy: artifacts.convertedBy,
        weightsManifest: manifest
      };
      if (artifacts.signature != null) {
        result.signature = artifacts.signature;
      }
      if (artifacts.userDefinedMetadata != null) {
        result.userDefinedMetadata = artifacts.userDefinedMetadata;
      }
      if (artifacts.modelInitializer != null) {
        result.modelInitializer = artifacts.modelInitializer;
      }
      if (artifacts.initializerSignature != null) {
        result.initializerSignature = artifacts.initializerSignature;
      }
      if (artifacts.trainingConfig != null) {
        result.trainingConfig = artifacts.trainingConfig;
      }
      return result;
    }
    function getModelArtifactsForJSONSync(modelJSON, weightSpecs, weightData) {
      const modelArtifacts = {
        modelTopology: modelJSON.modelTopology,
        format: modelJSON.format,
        generatedBy: modelJSON.generatedBy,
        convertedBy: modelJSON.convertedBy
      };
      if (modelJSON.trainingConfig != null) {
        modelArtifacts.trainingConfig = modelJSON.trainingConfig;
      }
      if (modelJSON.weightsManifest != null) {
        if (!weightSpecs) {
          throw new Error("modelJSON has weightsManifest but weightSpecs is null");
        }
        if (!weightData) {
          throw new Error("modelJSON has weightsManifest but weightData is null");
        }
        modelArtifacts.weightSpecs = weightSpecs;
        modelArtifacts.weightData = weightData;
      }
      if (modelJSON.signature != null) {
        modelArtifacts.signature = modelJSON.signature;
      }
      if (modelJSON.userDefinedMetadata != null) {
        modelArtifacts.userDefinedMetadata = modelJSON.userDefinedMetadata;
      }
      if (modelJSON.modelInitializer != null) {
        modelArtifacts.modelInitializer = modelJSON.modelInitializer;
      }
      if (modelJSON.initializerSignature != null) {
        modelArtifacts.initializerSignature = modelJSON.initializerSignature;
      }
      return modelArtifacts;
    }
    async function getModelArtifactsForJSON(modelJSON, loadWeights2) {
      let weightSpecs;
      let weightData;
      if (modelJSON.weightsManifest != null) {
        [weightSpecs, weightData] = await loadWeights2(modelJSON.weightsManifest);
      }
      return getModelArtifactsForJSONSync(modelJSON, weightSpecs, weightData);
    }
    function getModelArtifactsInfoForJSON(modelArtifacts) {
      if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
        throw new Error("Expected JSON model topology, received ArrayBuffer.");
      }
      return {
        dateSaved: /* @__PURE__ */ new Date(),
        modelTopologyType: "JSON",
        modelTopologyBytes: modelArtifacts.modelTopology == null ? 0 : stringByteLength(JSON.stringify(modelArtifacts.modelTopology)),
        weightSpecsBytes: modelArtifacts.weightSpecs == null ? 0 : stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)),
        weightDataBytes: modelArtifacts.weightData == null ? 0 : new CompositeArrayBuffer(modelArtifacts.weightData).byteLength
      };
    }
    function getWeightSpecs(weightsManifest) {
      const weightSpecs = [];
      for (const entry of weightsManifest) {
        weightSpecs.push(...entry.weights);
      }
      return weightSpecs;
    }
    var IORouterRegistry = class _IORouterRegistry {
      constructor() {
        this.saveRouters = [];
        this.loadRouters = [];
      }
      static getInstance() {
        if (_IORouterRegistry.instance == null) {
          _IORouterRegistry.instance = new _IORouterRegistry();
        }
        return _IORouterRegistry.instance;
      }
      /**
       * Register a save-handler router.
       *
       * @param saveRouter A function that maps a URL-like string onto an instance
       * of `IOHandler` with the `save` method defined or `null`.
       */
      static registerSaveRouter(saveRouter) {
        _IORouterRegistry.getInstance().saveRouters.push(saveRouter);
      }
      /**
       * Register a load-handler router.
       *
       * @param loadRouter A function that maps a URL-like string onto an instance
       * of `IOHandler` with the `load` method defined or `null`.
       */
      static registerLoadRouter(loadRouter) {
        _IORouterRegistry.getInstance().loadRouters.push(loadRouter);
      }
      /**
       * Look up IOHandler for saving, given a URL-like string.
       *
       * @param url
       * @returns If only one match is found, an instance of IOHandler with the
       * `save` method defined. If no match is found, `null`.
       * @throws Error, if more than one match is found.
       */
      static getSaveHandlers(url) {
        return _IORouterRegistry.getHandlers(url, "save");
      }
      /**
       * Look up IOHandler for loading, given a URL-like string.
       *
       * @param url
       * @param loadOptions Optional, custom load options.
       * @returns All valid handlers for `url`, given the currently registered
       *   handler routers.
       */
      static getLoadHandlers(url, loadOptions) {
        return _IORouterRegistry.getHandlers(url, "load", loadOptions);
      }
      static getHandlers(url, handlerType, loadOptions) {
        const validHandlers = [];
        const routers = handlerType === "load" ? _IORouterRegistry.getInstance().loadRouters : _IORouterRegistry.getInstance().saveRouters;
        routers.forEach((router) => {
          const handler = router(url, loadOptions);
          if (handler !== null) {
            validHandlers.push(handler);
          }
        });
        return validHandlers;
      }
    };
    var DATABASE_NAME = "tensorflowjs";
    var DATABASE_VERSION = 1;
    var MODEL_STORE_NAME = "models_store";
    var INFO_STORE_NAME = "model_info_store";
    function getIndexedDBFactory() {
      if (!env().getBool("IS_BROWSER")) {
        throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");
      }
      const theWindow = typeof window === "undefined" ? self : window;
      const factory = theWindow.indexedDB || theWindow.mozIndexedDB || theWindow.webkitIndexedDB || theWindow.msIndexedDB || theWindow.shimIndexedDB;
      if (factory == null) {
        throw new Error("The current browser does not appear to support IndexedDB.");
      }
      return factory;
    }
    function setUpDatabase(openRequest) {
      const db = openRequest.result;
      db.createObjectStore(MODEL_STORE_NAME, { keyPath: "modelPath" });
      db.createObjectStore(INFO_STORE_NAME, { keyPath: "modelPath" });
    }
    var BrowserIndexedDB = class {
      constructor(modelPath) {
        this.indexedDB = getIndexedDBFactory();
        if (modelPath == null || !modelPath) {
          throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");
        }
        this.modelPath = modelPath;
      }
      async save(modelArtifacts) {
        if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
          throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");
        }
        return this.databaseAction(this.modelPath, modelArtifacts);
      }
      async load() {
        return this.databaseAction(this.modelPath);
      }
      /**
       * Perform database action to put model artifacts into or read model artifacts
       * from IndexedDB object store.
       *
       * Whether the action is put or get depends on whether `modelArtifacts` is
       * specified. If it is specified, the action will be put; otherwise the action
       * will be get.
       *
       * @param modelPath A unique string path for the model.
       * @param modelArtifacts If specified, it will be the model artifacts to be
       *   stored in IndexedDB.
       * @returns A `Promise` of `SaveResult`, if the action is put, or a `Promise`
       *   of `ModelArtifacts`, if the action is get.
       */
      databaseAction(modelPath, modelArtifacts) {
        return new Promise((resolve, reject) => {
          const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
          openRequest.onupgradeneeded = () => setUpDatabase(openRequest);
          openRequest.onsuccess = () => {
            const db = openRequest.result;
            if (modelArtifacts == null) {
              const modelTx = db.transaction(MODEL_STORE_NAME, "readonly");
              const modelStore = modelTx.objectStore(MODEL_STORE_NAME);
              const getRequest = modelStore.get(this.modelPath);
              getRequest.onsuccess = () => {
                if (getRequest.result == null) {
                  db.close();
                  return reject(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));
                } else {
                  resolve(getRequest.result.modelArtifacts);
                }
              };
              getRequest.onerror = (error) => {
                db.close();
                return reject(getRequest.error);
              };
              modelTx.oncomplete = () => db.close();
            } else {
              modelArtifacts.weightData = CompositeArrayBuffer.join(modelArtifacts.weightData);
              const modelArtifactsInfo = getModelArtifactsInfoForJSON(modelArtifacts);
              const infoTx = db.transaction(INFO_STORE_NAME, "readwrite");
              let infoStore = infoTx.objectStore(INFO_STORE_NAME);
              let putInfoRequest;
              try {
                putInfoRequest = infoStore.put({ modelPath: this.modelPath, modelArtifactsInfo });
              } catch (error) {
                return reject(error);
              }
              let modelTx;
              putInfoRequest.onsuccess = () => {
                modelTx = db.transaction(MODEL_STORE_NAME, "readwrite");
                const modelStore = modelTx.objectStore(MODEL_STORE_NAME);
                let putModelRequest;
                try {
                  putModelRequest = modelStore.put({
                    modelPath: this.modelPath,
                    modelArtifacts,
                    modelArtifactsInfo
                  });
                } catch (error) {
                  return reject(error);
                }
                putModelRequest.onsuccess = () => resolve({ modelArtifactsInfo });
                putModelRequest.onerror = (error) => {
                  infoStore = infoTx.objectStore(INFO_STORE_NAME);
                  const deleteInfoRequest = infoStore.delete(this.modelPath);
                  deleteInfoRequest.onsuccess = () => {
                    db.close();
                    return reject(putModelRequest.error);
                  };
                  deleteInfoRequest.onerror = (error2) => {
                    db.close();
                    return reject(putModelRequest.error);
                  };
                };
              };
              putInfoRequest.onerror = (error) => {
                db.close();
                return reject(putInfoRequest.error);
              };
              infoTx.oncomplete = () => {
                if (modelTx == null) {
                  db.close();
                } else {
                  modelTx.oncomplete = () => db.close();
                }
              };
            }
          };
          openRequest.onerror = (error) => reject(openRequest.error);
        });
      }
    };
    BrowserIndexedDB.URL_SCHEME = "indexeddb://";
    var indexedDBRouter = (url) => {
      if (!env().getBool("IS_BROWSER")) {
        return null;
      } else {
        if (!Array.isArray(url) && url.startsWith(BrowserIndexedDB.URL_SCHEME)) {
          return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length));
        } else {
          return null;
        }
      }
    };
    IORouterRegistry.registerSaveRouter(indexedDBRouter);
    IORouterRegistry.registerLoadRouter(indexedDBRouter);
    function browserIndexedDB(modelPath) {
      return new BrowserIndexedDB(modelPath);
    }
    var PATH_SEPARATOR = "/";
    var PATH_PREFIX = "tensorflowjs_models";
    var INFO_SUFFIX = "info";
    var MODEL_TOPOLOGY_SUFFIX = "model_topology";
    var WEIGHT_SPECS_SUFFIX = "weight_specs";
    var WEIGHT_DATA_SUFFIX = "weight_data";
    var MODEL_METADATA_SUFFIX = "model_metadata";
    function getModelKeys(path) {
      return {
        info: [PATH_PREFIX, path, INFO_SUFFIX].join(PATH_SEPARATOR),
        topology: [PATH_PREFIX, path, MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR),
        weightSpecs: [PATH_PREFIX, path, WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR),
        weightData: [PATH_PREFIX, path, WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR),
        modelMetadata: [PATH_PREFIX, path, MODEL_METADATA_SUFFIX].join(PATH_SEPARATOR)
      };
    }
    function removeItems(keys) {
      for (const key of Object.values(keys)) {
        window.localStorage.removeItem(key);
      }
    }
    var BrowserLocalStorage = class {
      constructor(modelPath) {
        if (!env().getBool("IS_BROWSER") || typeof window === "undefined" || typeof window.localStorage === "undefined") {
          throw new Error("The current environment does not support local storage.");
        }
        this.LS = window.localStorage;
        if (modelPath == null || !modelPath) {
          throw new Error("For local storage, modelPath must not be null, undefined or empty.");
        }
        this.modelPath = modelPath;
        this.keys = getModelKeys(this.modelPath);
      }
      /**
       * Save model artifacts to browser local storage.
       *
       * See the documentation to `browserLocalStorage` for details on the saved
       * artifacts.
       *
       * @param modelArtifacts The model artifacts to be stored.
       * @returns An instance of SaveResult.
       */
      async save(modelArtifacts) {
        if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
          throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");
        } else {
          const topology = JSON.stringify(modelArtifacts.modelTopology);
          const weightSpecs = JSON.stringify(modelArtifacts.weightSpecs);
          const modelArtifactsInfo = getModelArtifactsInfoForJSON(modelArtifacts);
          const weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);
          try {
            this.LS.setItem(this.keys.info, JSON.stringify(modelArtifactsInfo));
            this.LS.setItem(this.keys.topology, topology);
            this.LS.setItem(this.keys.weightSpecs, weightSpecs);
            this.LS.setItem(this.keys.weightData, arrayBufferToBase64String(weightBuffer));
            const metadata = {
              format: modelArtifacts.format,
              generatedBy: modelArtifacts.generatedBy,
              convertedBy: modelArtifacts.convertedBy,
              signature: modelArtifacts.signature != null ? modelArtifacts.signature : void 0,
              userDefinedMetadata: modelArtifacts.userDefinedMetadata != null ? modelArtifacts.userDefinedMetadata : void 0,
              modelInitializer: modelArtifacts.modelInitializer != null ? modelArtifacts.modelInitializer : void 0,
              initializerSignature: modelArtifacts.initializerSignature != null ? modelArtifacts.initializerSignature : void 0,
              trainingConfig: modelArtifacts.trainingConfig != null ? modelArtifacts.trainingConfig : void 0
            };
            this.LS.setItem(this.keys.modelMetadata, JSON.stringify(metadata));
            return { modelArtifactsInfo };
          } catch (err) {
            removeItems(this.keys);
            throw new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${modelArtifactsInfo.modelTopologyBytes}, weightSpecsBytes=${modelArtifactsInfo.weightSpecsBytes}, weightDataBytes=${modelArtifactsInfo.weightDataBytes}.`);
          }
        }
      }
      /**
       * Load a model from local storage.
       *
       * See the documentation to `browserLocalStorage` for details on the saved
       * artifacts.
       *
       * @returns The loaded model (if loading succeeds).
       */
      async load() {
        const info = JSON.parse(this.LS.getItem(this.keys.info));
        if (info == null) {
          throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);
        }
        if (info.modelTopologyType !== "JSON") {
          throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");
        }
        const out = {};
        const topology = JSON.parse(this.LS.getItem(this.keys.topology));
        if (topology == null) {
          throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);
        }
        out.modelTopology = topology;
        const weightSpecs = JSON.parse(this.LS.getItem(this.keys.weightSpecs));
        if (weightSpecs == null) {
          throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);
        }
        out.weightSpecs = weightSpecs;
        const metadataString = this.LS.getItem(this.keys.modelMetadata);
        if (metadataString != null) {
          const metadata = JSON.parse(metadataString);
          out.format = metadata.format;
          out.generatedBy = metadata.generatedBy;
          out.convertedBy = metadata.convertedBy;
          if (metadata.signature != null) {
            out.signature = metadata.signature;
          }
          if (metadata.userDefinedMetadata != null) {
            out.userDefinedMetadata = metadata.userDefinedMetadata;
          }
          if (metadata.modelInitializer != null) {
            out.modelInitializer = metadata.modelInitializer;
          }
          if (metadata.initializerSignature != null) {
            out.initializerSignature = metadata.initializerSignature;
          }
          if (metadata.trainingConfig != null) {
            out.trainingConfig = metadata.trainingConfig;
          }
        }
        const weightDataBase64 = this.LS.getItem(this.keys.weightData);
        if (weightDataBase64 == null) {
          throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);
        }
        out.weightData = base64StringToArrayBuffer(weightDataBase64);
        return out;
      }
    };
    BrowserLocalStorage.URL_SCHEME = "localstorage://";
    var localStorageRouter = (url) => {
      if (!env().getBool("IS_BROWSER")) {
        return null;
      } else {
        if (!Array.isArray(url) && url.startsWith(BrowserLocalStorage.URL_SCHEME)) {
          return browserLocalStorage(url.slice(BrowserLocalStorage.URL_SCHEME.length));
        } else {
          return null;
        }
      }
    };
    IORouterRegistry.registerSaveRouter(localStorageRouter);
    IORouterRegistry.registerLoadRouter(localStorageRouter);
    function browserLocalStorage(modelPath) {
      return new BrowserLocalStorage(modelPath);
    }
    var DEFAULT_FILE_NAME_PREFIX = "model";
    var DEFAULT_JSON_EXTENSION_NAME = ".json";
    var DEFAULT_WEIGHT_DATA_EXTENSION_NAME = ".weights.bin";
    function defer(f) {
      return new Promise((resolve) => setTimeout(resolve)).then(f);
    }
    var BrowserDownloads = class _BrowserDownloads {
      constructor(fileNamePrefix) {
        if (!env().getBool("IS_BROWSER")) {
          throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");
        }
        if (fileNamePrefix.startsWith(_BrowserDownloads.URL_SCHEME)) {
          fileNamePrefix = fileNamePrefix.slice(_BrowserDownloads.URL_SCHEME.length);
        }
        if (fileNamePrefix == null || fileNamePrefix.length === 0) {
          fileNamePrefix = DEFAULT_FILE_NAME_PREFIX;
        }
        this.modelJsonFileName = fileNamePrefix + DEFAULT_JSON_EXTENSION_NAME;
        this.weightDataFileName = fileNamePrefix + DEFAULT_WEIGHT_DATA_EXTENSION_NAME;
      }
      async save(modelArtifacts) {
        if (typeof document === "undefined") {
          throw new Error("Browser downloads are not supported in this environment since `document` is not present");
        }
        const weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);
        const weightsURL = window.URL.createObjectURL(new Blob([weightBuffer], { type: "application/octet-stream" }));
        if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
          throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");
        } else {
          const weightsManifest = [{
            paths: ["./" + this.weightDataFileName],
            weights: modelArtifacts.weightSpecs
          }];
          const modelJSON = getModelJSONForModelArtifacts(modelArtifacts, weightsManifest);
          const modelJsonURL = window.URL.createObjectURL(new Blob([JSON.stringify(modelJSON)], { type: "application/json" }));
          const jsonAnchor = this.modelJsonAnchor == null ? document.createElement("a") : this.modelJsonAnchor;
          jsonAnchor.download = this.modelJsonFileName;
          jsonAnchor.href = modelJsonURL;
          await defer(() => jsonAnchor.dispatchEvent(new MouseEvent("click")));
          if (modelArtifacts.weightData != null) {
            const weightDataAnchor = this.weightDataAnchor == null ? document.createElement("a") : this.weightDataAnchor;
            weightDataAnchor.download = this.weightDataFileName;
            weightDataAnchor.href = weightsURL;
            await defer(() => weightDataAnchor.dispatchEvent(new MouseEvent("click")));
          }
          return { modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts) };
        }
      }
    };
    BrowserDownloads.URL_SCHEME = "downloads://";
    var browserDownloadsRouter = (url) => {
      if (!env().getBool("IS_BROWSER")) {
        return null;
      } else {
        if (!Array.isArray(url) && url.startsWith(BrowserDownloads.URL_SCHEME)) {
          return browserDownloads(url.slice(BrowserDownloads.URL_SCHEME.length));
        } else {
          return null;
        }
      }
    };
    IORouterRegistry.registerSaveRouter(browserDownloadsRouter);
    function browserDownloads(fileNamePrefix = "model") {
      return new BrowserDownloads(fileNamePrefix);
    }
    function monitorPromisesProgress(promises, onProgress, startFraction, endFraction) {
      checkPromises(promises);
      startFraction = startFraction == null ? 0 : startFraction;
      endFraction = endFraction == null ? 1 : endFraction;
      checkFraction(startFraction, endFraction);
      let resolvedPromise = 0;
      const registerMonitor = (promise) => {
        promise.then((value) => {
          const fraction = startFraction + ++resolvedPromise / promises.length * (endFraction - startFraction);
          onProgress(fraction);
          return value;
        });
        return promise;
      };
      function checkPromises(promises2) {
        assert(promises2 != null && Array.isArray(promises2) && promises2.length > 0, () => "promises must be a none empty array");
      }
      function checkFraction(startFraction2, endFraction2) {
        assert(startFraction2 >= 0 && startFraction2 <= 1, () => `Progress fraction must be in range [0, 1], but got startFraction ${startFraction2}`);
        assert(endFraction2 >= 0 && endFraction2 <= 1, () => `Progress fraction must be in range [0, 1], but got endFraction ${endFraction2}`);
        assert(endFraction2 >= startFraction2, () => `startFraction must be no more than endFraction, but got startFraction ${startFraction2} and endFraction ${endFraction2}`);
      }
      return Promise.all(promises.map(registerMonitor));
    }
    async function loadWeightsAsArrayBuffer(fetchURLs, loadOptions) {
      if (loadOptions == null) {
        loadOptions = {};
      }
      const fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch : loadOptions.fetchFunc;
      const requests = fetchURLs.map((fetchURL) => fetchFunc(fetchURL, loadOptions.requestInit, { isBinary: true }));
      const fetchStartFraction = 0;
      const fetchEndFraction = 0.5;
      const responses = loadOptions.onProgress == null ? await Promise.all(requests) : await monitorPromisesProgress(requests, loadOptions.onProgress, fetchStartFraction, fetchEndFraction);
      const bufferPromises = responses.map((response) => response.arrayBuffer());
      const bufferStartFraction = 0.5;
      const bufferEndFraction = 1;
      const buffers = loadOptions.onProgress == null ? await Promise.all(bufferPromises) : await monitorPromisesProgress(bufferPromises, loadOptions.onProgress, bufferStartFraction, bufferEndFraction);
      return buffers;
    }
    function streamWeights(fetchURLs, loadOptions) {
      var _a;
      const fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch : loadOptions.fetchFunc;
      let fetchIndex = 0;
      let chunkReader;
      (_a = loadOptions.onProgress) === null || _a === void 0 ? void 0 : _a.call(loadOptions, 0);
      return new ReadableStream({
        pull: async (controller) => {
          var _a2;
          while (fetchIndex < fetchURLs.length) {
            if (!chunkReader) {
              const body = (await fetchFunc(fetchURLs[fetchIndex], loadOptions.requestInit, { isBinary: true })).body;
              chunkReader = body.getReader();
            }
            const { done, value } = await chunkReader.read();
            if (done) {
              fetchIndex++;
              chunkReader = void 0;
              (_a2 = loadOptions.onProgress) === null || _a2 === void 0 ? void 0 : _a2.call(loadOptions, fetchIndex / fetchURLs.length);
              continue;
            }
            controller.enqueue(value);
            return;
          }
          controller.close();
        }
      });
    }
    var OCTET_STREAM_MIME_TYPE = "application/octet-stream";
    var JSON_TYPE = "application/json";
    var HTTPRequest = class {
      constructor(path, loadOptions) {
        this.DEFAULT_METHOD = "POST";
        if (loadOptions == null) {
          loadOptions = {};
        }
        this.weightPathPrefix = loadOptions.weightPathPrefix;
        this.weightUrlConverter = loadOptions.weightUrlConverter;
        if (loadOptions.fetchFunc != null) {
          assert(typeof loadOptions.fetchFunc === "function", () => "Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)");
          this.fetch = loadOptions.fetchFunc;
        } else {
          this.fetch = env().platform.fetch;
        }
        assert(path != null && path.length > 0, () => "URL path for http must not be null, undefined or empty.");
        if (Array.isArray(path)) {
          assert(path.length === 2, () => `URL paths for http must have a length of 2, (actual length is ${path.length}).`);
        }
        this.path = path;
        if (loadOptions.requestInit != null && loadOptions.requestInit.body != null) {
          throw new Error("requestInit is expected to have no pre-existing body, but has one.");
        }
        this.requestInit = loadOptions.requestInit || {};
        this.loadOptions = loadOptions;
      }
      async save(modelArtifacts) {
        if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
          throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");
        }
        const init = Object.assign({ method: this.DEFAULT_METHOD }, this.requestInit);
        init.body = new FormData();
        const weightsManifest = [{
          paths: ["./model.weights.bin"],
          weights: modelArtifacts.weightSpecs
        }];
        const modelTopologyAndWeightManifest = getModelJSONForModelArtifacts(modelArtifacts, weightsManifest);
        init.body.append("model.json", new Blob([JSON.stringify(modelTopologyAndWeightManifest)], { type: JSON_TYPE }), "model.json");
        if (modelArtifacts.weightData != null) {
          const weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);
          init.body.append("model.weights.bin", new Blob([weightBuffer], { type: OCTET_STREAM_MIME_TYPE }), "model.weights.bin");
        }
        const response = await this.fetch(this.path, init);
        if (response.ok) {
          return {
            modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts),
            responses: [response]
          };
        } else {
          throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${response.status}.`);
        }
      }
      async loadModelJSON() {
        const modelConfigRequest = await this.fetch(this.path, this.requestInit);
        if (!modelConfigRequest.ok) {
          throw new Error(`Request to ${this.path} failed with status code ${modelConfigRequest.status}. Please verify this URL points to the model JSON of the model to load.`);
        }
        let modelJSON;
        try {
          modelJSON = await modelConfigRequest.json();
        } catch (e) {
          let message = `Failed to parse model JSON of response from ${this.path}.`;
          if (this.path.endsWith(".pb")) {
            message += " 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.";
          } else {
            message += " Please make sure the server is serving valid JSON for this request.";
          }
          throw new Error(message);
        }
        const modelTopology = modelJSON.modelTopology;
        const weightsManifest = modelJSON.weightsManifest;
        if (modelTopology == null && weightsManifest == null) {
          throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);
        }
        return modelJSON;
      }
      /**
       * Load model artifacts via HTTP request(s).
       *
       * See the documentation to `tf.io.http` for details on the saved
       * artifacts.
       *
       * @returns The loaded model artifacts (if loading succeeds).
       */
      async load() {
        if (this.loadOptions.streamWeights) {
          return this.loadStream();
        }
        const modelJSON = await this.loadModelJSON();
        return getModelArtifactsForJSON(modelJSON, (weightsManifest) => this.loadWeights(weightsManifest));
      }
      async loadStream() {
        const modelJSON = await this.loadModelJSON();
        const fetchURLs = await this.getWeightUrls(modelJSON.weightsManifest);
        const weightSpecs = getWeightSpecs(modelJSON.weightsManifest);
        const stream = () => streamWeights(fetchURLs, this.loadOptions);
        return Object.assign(Object.assign({}, modelJSON), { weightSpecs, getWeightStream: stream });
      }
      async getWeightUrls(weightsManifest) {
        const weightPath = Array.isArray(this.path) ? this.path[1] : this.path;
        const [prefix, suffix] = parseUrl(weightPath);
        const pathPrefix = this.weightPathPrefix || prefix;
        const fetchURLs = [];
        const urlPromises = [];
        for (const weightsGroup of weightsManifest) {
          for (const path of weightsGroup.paths) {
            if (this.weightUrlConverter != null) {
              urlPromises.push(this.weightUrlConverter(path));
            } else {
              fetchURLs.push(pathPrefix + path + suffix);
            }
          }
        }
        if (this.weightUrlConverter) {
          fetchURLs.push(...await Promise.all(urlPromises));
        }
        return fetchURLs;
      }
      async loadWeights(weightsManifest) {
        const fetchURLs = await this.getWeightUrls(weightsManifest);
        const weightSpecs = getWeightSpecs(weightsManifest);
        const buffers = await loadWeightsAsArrayBuffer(fetchURLs, this.loadOptions);
        return [weightSpecs, buffers];
      }
    };
    HTTPRequest.URL_SCHEME_REGEX = /^https?:\/\//;
    function parseUrl(url) {
      const lastSlash = url.lastIndexOf("/");
      const lastSearchParam = url.lastIndexOf("?");
      const prefix = url.substring(0, lastSlash);
      const suffix = lastSearchParam > lastSlash ? url.substring(lastSearchParam) : "";
      return [prefix + "/", suffix];
    }
    function isHTTPScheme(url) {
      return url.match(HTTPRequest.URL_SCHEME_REGEX) != null;
    }
    var httpRouter = (url, loadOptions) => {
      if (typeof fetch === "undefined" && (loadOptions == null || loadOptions.fetchFunc == null)) {
        return null;
      } else {
        let isHTTP = true;
        if (Array.isArray(url)) {
          isHTTP = url.every((urlItem) => isHTTPScheme(urlItem));
        } else {
          isHTTP = isHTTPScheme(url);
        }
        if (isHTTP) {
          return http(url, loadOptions);
        }
      }
      return null;
    };
    IORouterRegistry.registerSaveRouter(httpRouter);
    IORouterRegistry.registerLoadRouter(httpRouter);
    function http(path, loadOptions) {
      return new HTTPRequest(path, loadOptions);
    }
    function oneHot_(indices, depth, onValue = 1, offValue = 0, dtype = "int32") {
      if (depth < 2) {
        throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`);
      }
      const $indices = convertToTensor(indices, "indices", "oneHot", "int32");
      const inputs = { indices: $indices };
      const attrs = { dtype, depth, onValue, offValue };
      return ENGINE.runKernel(OneHot, inputs, attrs);
    }
    var oneHot = /* @__PURE__ */ op({ oneHot_ });
    function validateUpdateShape(shape, indices, updates) {
      const sliceDim = indices.rank > 1 ? indices.shape[indices.rank - 1] : 1;
      const batchDim = indices.rank > 1 ? indices.rank - 1 : 1;
      const shapeError = `Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${updates.shape}, indices.shape: ${indices.shape}, shape: ${shape}, sliceDim: ${sliceDim}, and batchDim: ${batchDim}.`;
      if (updates.rank < batchDim) {
        throw new Error(shapeError + ` update.rank < ${batchDim}. `);
      }
      if (shape.length < sliceDim + (updates.rank - batchDim)) {
        throw new Error(shapeError + ` Output shape length < ${sliceDim + (updates.rank - batchDim)}`);
      }
      if (updates.rank !== batchDim + shape.length - sliceDim) {
        throw new Error(shapeError + ` update.rank != ${batchDim + shape.length - sliceDim}`);
      }
      for (let d = 0; d < batchDim; ++d) {
        if (updates.shape[d] !== indices.shape[d]) {
          throw new Error(shapeError + ` updates.shape[${d}] (${updates.shape[d]}) != indices.shape[${d}] (${indices.shape[d]}).`);
        }
      }
      for (let d = 0; d < updates.rank - batchDim; ++d) {
        if (updates.shape[d + batchDim] !== shape[d + sliceDim]) {
          throw new Error(shapeError + ` updates.shape[${d + batchDim}] (${updates.shape[d + batchDim]}) != shape[${d + batchDim}] (${shape[d + batchDim]})`);
        }
      }
    }
    function validateInput$1(updates, indices, shape) {
      if (indices.rank < 1) {
        throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${indices.rank}.`);
      }
      if (updates.rank < 1) {
        throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${updates.rank}.`);
      }
      if (indices.dtype !== "int32") {
        throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${indices.dtype}`);
      }
      if (shape.length < 1) {
        throw new Error(`Output rank must be greater or equal to 1, but got shape: ${shape}`);
      }
      if (shape.length === 0) {
        if (indices.size === 0) {
          throw new Error(`Indices specified for empty output. indices shape: ${indices.shape}`);
        }
        if (updates.size === 0) {
          throw new Error(`Updates specified for empty output. updates shape: ${updates.shape}`);
        }
      }
      validateUpdateShape(shape, indices, updates);
    }
    function parseSliceParams(x, begin, size) {
      let begin_;
      const xRank = x.shape.length;
      if (typeof begin === "number") {
        begin_ = [begin, ...new Array(xRank - 1).fill(0)];
      } else if (begin.length < xRank) {
        begin_ = begin.concat(new Array(xRank - begin.length).fill(0));
      } else {
        begin_ = begin.slice();
      }
      begin_.forEach((d) => {
        assert(d !== -1, () => "slice() does not support negative begin indexing.");
      });
      let size_;
      if (size == null) {
        size_ = new Array(xRank).fill(-1);
      } else if (typeof size === "number") {
        size_ = [size, ...new Array(xRank - 1).fill(-1)];
      } else if (size.length < xRank) {
        size_ = size.concat(new Array(xRank - size.length).fill(-1));
      } else {
        size_ = size;
      }
      size_ = size_.map((d, i) => {
        if (d >= 0) {
          return d;
        } else {
          assert(d === -1, () => `Negative size values should be exactly -1 but got ${d} for the slice() size at index ${i}.`);
          return x.shape[i] - begin_[i];
        }
      });
      return [begin_, size_];
    }
    var Serializable = class {
      /**
       * Return the class name for this class to use in serialization contexts.
       *
       * Generally speaking this will be the same thing that constructor.name
       * would have returned.  However, the class name needs to be robust
       * against minification for serialization/deserialization to work properly.
       *
       * There's also places such as initializers.VarianceScaling, where
       * implementation details between different languages led to different
       * class hierarchies and a non-leaf node is used for serialization purposes.
       */
      getClassName() {
        return this.constructor.className;
      }
      /**
       * Creates an instance of T from a ConfigDict.
       *
       * This works for most descendants of serializable.  A few need to
       * provide special handling.
       * @param cls A Constructor for the class to instantiate.
       * @param config The Configuration for the object.
       */
      /** @nocollapse */
      static fromConfig(cls, config) {
        return new cls(config);
      }
    };
    function abs_(x) {
      const $x = convertToTensor(x, "x", "abs");
      if ($x.dtype === "complex64") {
        const inputs = { x: $x };
        return ENGINE.runKernel(ComplexAbs, inputs);
      } else {
        const inputs = { x: $x };
        return ENGINE.runKernel(Abs, inputs);
      }
    }
    var abs = /* @__PURE__ */ op({ abs_ });
    function acos_(x) {
      const $x = convertToTensor(x, "x", "acos");
      const inputs = { x: $x };
      return ENGINE.runKernel(Acos, inputs);
    }
    var acos = /* @__PURE__ */ op({ acos_ });
    function acosh_(x) {
      const $x = convertToTensor(x, "x", "acosh");
      const inputs = { x: $x };
      return ENGINE.runKernel(Acosh, inputs);
    }
    var acosh = /* @__PURE__ */ op({ acosh_ });
    function all_(x, axis = null, keepDims = false) {
      const $x = convertToTensor(x, "x", "all", "bool");
      const inputs = { x: $x };
      const attrs = { axis, keepDims };
      return ENGINE.runKernel(All, inputs, attrs);
    }
    var all = /* @__PURE__ */ op({ all_ });
    function any_(x, axis = null, keepDims = false) {
      const $x = convertToTensor(x, "x", "any", "bool");
      const inputs = { x: $x };
      const attrs = { axis, keepDims };
      return ENGINE.runKernel(Any, inputs, attrs);
    }
    var any = /* @__PURE__ */ op({ any_ });
    function argMax_(x, axis = 0) {
      const $x = convertToTensor(x, "x", "argMax");
      const inputs = { x: $x };
      const attrs = { axis };
      return ENGINE.runKernel(ArgMax, inputs, attrs);
    }
    var argMax = /* @__PURE__ */ op({ argMax_ });
    function argMin_(x, axis = 0) {
      const $x = convertToTensor(x, "x", "argMin");
      const inputs = { x: $x };
      const attrs = { axis };
      return ENGINE.runKernel(ArgMin, inputs, attrs);
    }
    var argMin = /* @__PURE__ */ op({ argMin_ });
    function asin_(x) {
      const $x = convertToTensor(x, "x", "asin");
      const inputs = { x: $x };
      return ENGINE.runKernel(Asin, inputs);
    }
    var asin = /* @__PURE__ */ op({ asin_ });
    function asinh_(x) {
      const $x = convertToTensor(x, "x", "asinh");
      const inputs = { x: $x };
      return ENGINE.runKernel(Asinh, inputs);
    }
    var asinh = /* @__PURE__ */ op({ asinh_ });
    function atan_(x) {
      const $x = convertToTensor(x, "x", "atan");
      const inputs = { x: $x };
      return ENGINE.runKernel(Atan, inputs);
    }
    var atan = /* @__PURE__ */ op({ atan_ });
    function atan2_(a, b) {
      let $a = convertToTensor(a, "a", "atan2");
      let $b = convertToTensor(b, "b", "atan2");
      [$a, $b] = makeTypesMatch($a, $b);
      const inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Atan2, inputs);
    }
    var atan2 = /* @__PURE__ */ op({ atan2_ });
    function atanh_(x) {
      const $x = convertToTensor(x, "x", "atanh");
      const inputs = { x: $x };
      return ENGINE.runKernel(Atanh, inputs);
    }
    var atanh = /* @__PURE__ */ op({ atanh_ });
    function avgPool_(x, filterSize, strides, pad2, dimRoundingMode) {
      const $x = convertToTensor(x, "x", "avgPool", "float32");
      const dilations = 1;
      assert(eitherStridesOrDilationsAreOne(strides, dilations), () => `Error in avgPool: Either strides or dilations must be 1. Got strides ${strides} and dilations '${dilations}'`);
      let x4D = $x;
      let reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, () => `Error in avgPool: x must be rank 4 but got rank ${x4D.rank}.`);
      checkPadOnDimRoundingMode("avgPool", pad2, dimRoundingMode);
      const inputs = { x: x4D };
      const attrs = { filterSize, strides, pad: pad2, dimRoundingMode };
      let res = ENGINE.runKernel(AvgPool, inputs, attrs);
      res = cast(res, $x.dtype);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var avgPool = /* @__PURE__ */ op({ avgPool_ });
    function concat_(tensors, axis = 0) {
      assert(tensors.length >= 1, () => "Pass at least one tensor to concat");
      const $tensors = convertToTensorArray(tensors, "tensors", "concat", "string_or_numeric");
      if ($tensors[0].dtype === "complex64") {
        $tensors.forEach((tensor2) => {
          if (tensor2.dtype !== "complex64") {
            throw new Error(`Cannot concatenate complex64 tensors with a tensor
          with dtype ${tensor2.dtype}. `);
          }
        });
      }
      if ($tensors.length === 1) {
        return clone($tensors[0]);
      }
      const inputs = $tensors;
      const attr = { axis };
      return ENGINE.runKernel(Concat, inputs, attr);
    }
    var concat = /* @__PURE__ */ op({ concat_ });
    function sigmoid_(x) {
      const $x = convertToTensor(x, "x", "sigmoid", "float32");
      const inputs = { x: $x };
      return ENGINE.runKernel(Sigmoid, inputs);
    }
    var sigmoid = /* @__PURE__ */ op({ sigmoid_ });
    function tanh_(x) {
      const $x = convertToTensor(x, "x", "tanh", "float32");
      const inputs = { x: $x };
      return ENGINE.runKernel(Tanh, inputs);
    }
    var tanh = /* @__PURE__ */ op({ tanh_ });
    function batchToSpaceND_(x, blockShape, crops) {
      const $x = convertToTensor(x, "x", "batchToSpaceND");
      const prod2 = blockShape.reduce((a, b) => a * b);
      assert($x.rank >= 1 + blockShape.length, () => `input rank is ${$x.rank} but should be > than blockShape.length ${blockShape.length}`);
      assert(crops.length === blockShape.length, () => `crops.length is ${crops.length} but should be equal to blockShape.length  ${blockShape.length}`);
      assert($x.shape[0] % prod2 === 0, () => `input tensor batch is ${$x.shape[0]} but is not divisible by the product of the elements of blockShape ${blockShape.join(" * ")} === ${prod2}`);
      const inputs = { x: $x };
      const attrs = { blockShape, crops };
      return ENGINE.runKernel(BatchToSpaceND, inputs, attrs);
    }
    var batchToSpaceND = /* @__PURE__ */ op({ batchToSpaceND_ });
    function xAs4D(x) {
      let x4D;
      if (x.rank === 0 || x.rank === 1) {
        x4D = reshape(x, [1, 1, 1, x.size]);
      } else if (x.rank === 2) {
        x4D = reshape(x, [1, 1, x.shape[0], x.shape[1]]);
      } else if (x.rank === 3) {
        x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
      } else {
        x4D = x;
      }
      return x4D;
    }
    function batchNorm_(x, mean2, variance, offset, scale, varianceEpsilon) {
      if (varianceEpsilon == null) {
        varianceEpsilon = 1e-3;
      }
      const $x = convertToTensor(x, "x", "batchNorm");
      const $mean = convertToTensor(mean2, "mean", "batchNorm");
      const $variance = convertToTensor(variance, "variance", "batchNorm");
      let $scale;
      if (scale != null) {
        $scale = convertToTensor(scale, "scale", "batchNorm");
      }
      let $offset;
      if (offset != null) {
        $offset = convertToTensor(offset, "offset", "batchNorm");
      }
      assert($mean.rank === $variance.rank, () => "Batch normalization gradient requires mean and variance to have equal ranks.");
      assert($offset == null || $mean.rank === $offset.rank, () => "Batch normalization gradient requires mean and offset to have equal ranks.");
      assert($scale == null || $mean.rank === $scale.rank, () => "Batch normalization gradient requires mean and scale to have equal ranks.");
      const x4D = xAs4D($x);
      const inputs = {
        x: x4D,
        scale: $scale,
        offset: $offset,
        mean: $mean,
        variance: $variance
      };
      const attrs = { varianceEpsilon };
      const res = ENGINE.runKernel(FusedBatchNorm, inputs, attrs);
      return reshape(res, $x.shape);
    }
    var batchNorm = /* @__PURE__ */ op({ batchNorm_ });
    function ceil_(x) {
      const $x = convertToTensor(x, "x", "ceil", "float32");
      const inputs = { x: $x };
      return ENGINE.runKernel(Ceil, inputs);
    }
    var ceil = /* @__PURE__ */ op({ ceil_ });
    function fill(shape, value, dtype) {
      assertNonNegativeIntegerDimensions(shape);
      dtype = dtype || inferDtype(value);
      const attrs = { shape, value, dtype };
      return ENGINE.runKernel(Fill, {}, attrs);
    }
    function clipByValue_(x, clipValueMin, clipValueMax) {
      const $x = convertToTensor(x, "x", "clipByValue");
      assert(clipValueMin <= clipValueMax, () => `Error in clip: min (${clipValueMin}) must be less than or equal to max (${clipValueMax}).`);
      if (clipValueMin === clipValueMax) {
        return fill($x.shape, clipValueMin, $x.dtype);
      }
      const inputs = { x: $x };
      const attrs = { clipValueMin, clipValueMax };
      return ENGINE.runKernel(ClipByValue, inputs, attrs);
    }
    var clipByValue = /* @__PURE__ */ op({ clipByValue_ });
    function conv1d_(x, filter, stride, pad2, dataFormat = "NWC", dilation = 1, dimRoundingMode) {
      const $x = convertToTensor(x, "x", "conv1d");
      const $filter = convertToTensor(filter, "filter", "conv1d");
      let x3D = $x;
      let reshapedTo3D = false;
      if ($x.rank === 2) {
        reshapedTo3D = true;
        x3D = reshape($x, [1, $x.shape[0], $x.shape[1]]);
      }
      assert(x3D.rank === 3, () => `Error in conv1d: input must be rank 3, but got rank ${x3D.rank}.`);
      assert($filter.rank === 3, () => `Error in conv1d: filter must be rank 3, but got rank ${$filter.rank}.`);
      checkPadOnDimRoundingMode("conv1d", pad2, dimRoundingMode);
      assert(x3D.shape[2] === $filter.shape[1], () => `Error in conv1d: depth of input (${x3D.shape[2]}) must match input depth for filter ${$filter.shape[1]}.`);
      assert(eitherStridesOrDilationsAreOne(stride, dilation), () => `Error in conv1D: Either stride or dilation must be 1. Got stride ${stride} and dilation '${dilation}'`);
      assert(stridesOrDilationsArePositive(dilation), () => "Error in conv1D: Dilated rates should be larger than 0.");
      assert(stridesOrDilationsArePositive(stride), () => "Error in conv1D: Stride should be larger than 0.");
      assert(dataFormat === "NWC", () => `Error in conv1d: got dataFormat of ${dataFormat} but only NWC is currently supported.`);
      const filter4D = reshape($filter, [1, $filter.shape[0], $filter.shape[1], $filter.shape[2]]);
      const input4D = reshape(x3D, [x3D.shape[0], 1, x3D.shape[1], x3D.shape[2]]);
      const strides = [1, stride];
      const dilations = [1, dilation];
      const conv2dDataFormat = "NHWC";
      const res = conv2d$1(input4D, filter4D, strides, pad2, conv2dDataFormat, dilations, dimRoundingMode);
      if (reshapedTo3D) {
        return reshape(res, [res.shape[2], res.shape[3]]);
      }
      return reshape(res, [res.shape[0], res.shape[2], res.shape[3]]);
    }
    var conv1d = /* @__PURE__ */ op({ conv1d_ });
    function conv2dTranspose_(x, filter, outputShape, strides, pad2, dimRoundingMode) {
      const $x = convertToTensor(x, "x", "conv2dTranspose");
      const $filter = convertToTensor(filter, "filter", "conv2dTranspose");
      return conv2DBackpropInput(outputShape, $x, $filter, strides, pad2, "NHWC", dimRoundingMode);
    }
    var conv2dTranspose = /* @__PURE__ */ op({ conv2dTranspose_ });
    function cos_(x) {
      const $x = convertToTensor(x, "x", "cos", "float32");
      const inputs = { x: $x };
      return ENGINE.runKernel(Cos, inputs);
    }
    var cos = /* @__PURE__ */ op({ cos_ });
    function cosh_(x) {
      const $x = convertToTensor(x, "x", "cosh", "float32");
      const inputs = { x: $x };
      return ENGINE.runKernel(Cosh, inputs);
    }
    var cosh = /* @__PURE__ */ op({ cosh_ });
    function cumprod_(x, axis = 0, exclusive = false, reverse2 = false) {
      const $x = convertToTensor(x, "x", "cumprod");
      const inputs = { x: $x };
      const attrs = { axis, exclusive, reverse: reverse2 };
      return ENGINE.runKernel(Cumprod, inputs, attrs);
    }
    var cumprod = /* @__PURE__ */ op({ cumprod_ });
    function depthToSpace_(x, blockSize, dataFormat = "NHWC") {
      const $x = convertToTensor(x, "x", "depthToSpace", "float32");
      const inputHeight = dataFormat === "NHWC" ? $x.shape[1] : $x.shape[2];
      const inputWidth = dataFormat === "NHWC" ? $x.shape[2] : $x.shape[3];
      const inputDepth = dataFormat === "NHWC" ? $x.shape[3] : $x.shape[1];
      assert(blockSize > 1, () => `blockSize should be > 1 for depthToSpace, but was: ${blockSize}`);
      assert(inputHeight * blockSize >= 0, () => `Negative dimension size caused by overflow when multiplying
    ${inputHeight} and ${blockSize}  for depthToSpace with input shape
    ${$x.shape}`);
      assert(inputWidth * blockSize >= 0, () => `Negative dimension size caused by overflow when multiplying
    ${inputWidth} and ${blockSize} for depthToSpace with input shape
        ${$x.shape}`);
      assert(inputDepth % (blockSize * blockSize) === 0, () => `Dimension size must be evenly divisible by ${blockSize * blockSize} but is ${inputDepth} for depthToSpace with input shape ${$x.shape}`);
      const inputs = { x: $x };
      const attrs = { blockSize, dataFormat };
      return ENGINE.runKernel(DepthToSpace, inputs, attrs);
    }
    var depthToSpace = /* @__PURE__ */ op({ depthToSpace_ });
    function depthwiseConv2d_(x, filter, strides, pad2, dataFormat = "NHWC", dilations = [1, 1], dimRoundingMode) {
      const $x = convertToTensor(x, "x", "depthwiseConv2d", "float32");
      const $filter = convertToTensor(filter, "filter", "depthwiseConv2d", "float32");
      let x4D = $x;
      let reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, () => `Error in depthwiseConv2d: input must be rank 4, but got rank ${x4D.rank}.`);
      assert($filter.rank === 4, () => `Error in depthwiseConv2d: filter must be rank 4, but got rank ${$filter.rank}.`);
      const inChannels = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
      assert(inChannels === $filter.shape[2], () => `Error in depthwiseConv2d: number of input channels (${inChannels}) must match the inChannels dimension in filter ${$filter.shape[2]}.`);
      checkPadOnDimRoundingMode("depthwiseConv2d", pad2, dimRoundingMode);
      const inputs = { x: x4D, filter: $filter };
      const attrs = { strides, pad: pad2, dataFormat, dilations, dimRoundingMode };
      const res = ENGINE.runKernel(DepthwiseConv2dNative, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var depthwiseConv2d$1 = /* @__PURE__ */ op({ depthwiseConv2d_ });
    function dilation2d_(x, filter, strides, pad2, dilations = [1, 1], dataFormat = "NHWC") {
      const $x = convertToTensor(x, "x", "dilation2d");
      const $filter = convertToTensor(filter, "filter", "dilation2d");
      assert($x.rank === 3 || $x.rank === 4, () => `Error in dilation2d: input must be rank 3 or 4, but got rank ${$x.rank}.`);
      assert($filter.rank === 3, () => `Error in dilation2d: filter must be rank 3, but got rank ${$filter.rank}.`);
      assert(dataFormat === "NHWC", () => `Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${dataFormat}`);
      let x4D = $x;
      let reshapedTo4D = false;
      if ($x.rank === 3) {
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
        reshapedTo4D = true;
      }
      assert(x4D.shape[3] === $filter.shape[2], () => `Error in dilation2d:  input and filter must have the same depth: ${x4D.shape[3]} vs ${$filter.shape[2]}`);
      const inputs = { x: x4D, filter: $filter };
      const attrs = { strides, pad: pad2, dilations };
      const res = ENGINE.runKernel(Dilation2D, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var dilation2d = /* @__PURE__ */ op({ dilation2d_ });
    function divNoNan_(a, b) {
      let $a = convertToTensor(a, "a", "div");
      let $b = convertToTensor(b, "b", "div");
      [$a, $b] = makeTypesMatch($a, $b);
      const divResult = div($a, $b);
      const zeros2 = zerosLike(divResult);
      const bEqualsZero = equal($b, zeros2);
      return where(bEqualsZero, zeros2, divResult);
    }
    var divNoNan = /* @__PURE__ */ op({ divNoNan_ });
    function dot_(t1, t2) {
      const $t1 = convertToTensor(t1, "t1", "dot");
      const $t2 = convertToTensor(t2, "t2", "dot");
      assert(($t1.rank === 1 || $t1.rank === 2) && ($t2.rank === 1 || $t2.rank === 2), () => `Error in dot: inputs must all be rank 1 or 2, but got ranks ${$t1.rank} and ${$t2.rank}.`);
      const t1Inner = $t1.rank === 1 ? $t1.size : $t1.shape[1];
      const t2Inner = $t2.rank === 1 ? $t2.size : $t2.shape[0];
      assert(t1Inner === t2Inner, () => `Error in dot: inner dimensions of inputs must match, but got ${t1Inner} and ${t2Inner}.`);
      if ($t1.rank === 1 && $t2.rank === 1) {
        const t12D = reshape($t1, [1, -1]);
        const t22D = reshape($t2, [-1, 1]);
        const t1t2 = matMul$1(t12D, t22D);
        return reshape(t1t2, []);
      } else if ($t1.rank === 1 && $t2.rank === 2) {
        const t12D = reshape($t1, [1, -1]);
        const t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);
        const t1t2 = matMul$1(t12D, t22D);
        return reshape(t1t2, [t1t2.size]);
      } else if ($t1.rank === 2 && $t2.rank === 1) {
        const t22D = reshape($t2, [-1, 1]);
        const t1t2 = matMul$1($t1, t22D);
        return reshape(t1t2, [t1t2.size]);
      } else {
        const t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);
        const t1t2 = matMul$1($t1, t22D);
        return t1t2;
      }
    }
    var dot = /* @__PURE__ */ op({ dot_ });
    function elu_(x) {
      const $x = convertToTensor(x, "x", "elu", "float32");
      const inputs = { x: $x };
      return ENGINE.runKernel(Elu, inputs);
    }
    var elu = /* @__PURE__ */ op({ elu_ });
    function erf_(x) {
      let $x = convertToTensor(x, "x", "erf");
      assert($x.dtype === "int32" || $x.dtype === "float32", () => "Input dtype must be `int32` or `float32`.");
      if ($x.dtype === "int32") {
        $x = cast($x, "float32");
      }
      const inputs = { x: $x };
      return ENGINE.runKernel(Erf, inputs);
    }
    var erf = /* @__PURE__ */ op({ erf_ });
    function max_(x, axis = null, keepDims = false) {
      const $x = convertToTensor(x, "x", "max");
      const inputs = { x: $x };
      const attrs = { reductionIndices: axis, keepDims };
      return ENGINE.runKernel(Max, inputs, attrs);
    }
    var max = /* @__PURE__ */ op({ max_ });
    function min_(x, axis = null, keepDims = false) {
      const $x = convertToTensor(x, "x", "min");
      const inputs = { x: $x };
      const attrs = { axis, keepDims };
      return ENGINE.runKernel(Min, inputs, attrs);
    }
    var min = /* @__PURE__ */ op({ min_ });
    function norm_(x, ord = "euclidean", axis = null, keepDims = false) {
      x = convertToTensor(x, "x", "norm");
      const norm2 = normImpl(x, ord, axis);
      let keepDimsShape = norm2.shape;
      if (keepDims) {
        const axes = parseAxisParam(axis, x.shape);
        keepDimsShape = expandShapeToKeepDim(norm2.shape, axes);
      }
      return reshape(norm2, keepDimsShape);
    }
    function normImpl(x, p, axis = null) {
      if (x.rank === 0) {
        return abs(x);
      }
      if (x.rank !== 1 && axis === null) {
        return normImpl(reshape(x, [-1]), p, axis);
      }
      if (x.rank === 1 || typeof axis === "number" || Array.isArray(axis) && axis.length === 1) {
        if (p === 1) {
          return sum(abs(x), axis);
        }
        if (p === Infinity) {
          return max(abs(x), axis);
        }
        if (p === -Infinity) {
          return min(abs(x), axis);
        }
        if (p === "euclidean" || p === 2) {
          return sqrt(sum(pow(abs(x), scalar(2, "int32")), axis));
        }
        throw new Error(`Error in norm: invalid ord value: ${p}`);
      }
      if (Array.isArray(axis) && axis.length === 2) {
        if (p === 1) {
          return max(sum(abs(x), axis[0]), axis[1] - 1);
        }
        if (p === Infinity) {
          return max(sum(abs(x), axis[1]), axis[0]);
        }
        if (p === -Infinity) {
          return min(sum(abs(x), axis[1]), axis[0]);
        }
        if (p === "fro" || p === "euclidean") {
          return sqrt(sum(square(x), axis));
        }
        throw new Error(`Error in norm: invalid ord value: ${p}`);
      }
      throw new Error(`Error in norm: invalid axis: ${axis}`);
    }
    var norm = /* @__PURE__ */ op({ norm_ });
    function euclideanNorm_(x, axis = null, keepDims = false) {
      return norm(x, "euclidean", axis, keepDims);
    }
    var euclideanNorm = /* @__PURE__ */ op({ euclideanNorm_ });
    function expandDims_(x, axis = 0) {
      const $x = convertToTensor(x, "x", "expandDims", "string_or_numeric");
      assert(axis <= $x.rank, () => "Axis must be <= rank of the tensor");
      const inputs = { input: $x };
      const attrs = { dim: axis };
      return ENGINE.runKernel(ExpandDims, inputs, attrs);
    }
    var expandDims = /* @__PURE__ */ op({ expandDims_ });
    function expm1_(x) {
      const $x = convertToTensor(x, "x", "expm1");
      const inputs = { x: $x };
      return ENGINE.runKernel(Expm1, inputs);
    }
    var expm1 = /* @__PURE__ */ op({ expm1_ });
    function gather_(x, indices, axis = 0, batchDims = 0) {
      const $x = convertToTensor(x, "x", "gather");
      const $indices = convertToTensor(indices, "indices", "gather", "int32");
      const inputs = { x: $x, indices: $indices };
      const attrs = { axis, batchDims };
      return ENGINE.runKernel(GatherV2, inputs, attrs);
    }
    var gather = /* @__PURE__ */ op({ gather_ });
    function isFinite_(x) {
      const $x = convertToTensor(x, "x", "isFinite");
      const inputs = { x: $x };
      return ENGINE.runKernel(IsFinite, inputs);
    }
    var isFinite$1 = /* @__PURE__ */ op({ isFinite_ });
    function isInf_(x) {
      const $x = convertToTensor(x, "x", "isInf");
      const inputs = { x: $x };
      return ENGINE.runKernel(IsInf, inputs);
    }
    var isInf = /* @__PURE__ */ op({ isInf_ });
    function isNaN_(x) {
      const $x = convertToTensor(x, "x", "isNaN");
      const inputs = { x: $x };
      return ENGINE.runKernel(IsNan, inputs);
    }
    var isNaN$1 = /* @__PURE__ */ op({ isNaN_ });
    function leakyRelu_(x, alpha = 0.2) {
      const $x = convertToTensor(x, "x", "leakyRelu");
      const inputs = { x: $x };
      const attrs = { alpha };
      return ENGINE.runKernel(LeakyRelu, inputs, attrs);
    }
    var leakyRelu = /* @__PURE__ */ op({ leakyRelu_ });
    function localResponseNormalization_(x, depthRadius = 5, bias = 1, alpha = 1, beta = 0.5) {
      const $x = convertToTensor(x, "x", "localResponseNormalization");
      assert($x.rank === 4 || $x.rank === 3, () => `Error in localResponseNormalization: x must be rank 3 or 4 but got
               rank ${$x.rank}.`);
      assert(isInt(depthRadius), () => `Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${depthRadius}.`);
      let x4D = $x;
      let reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      const inputs = { x: x4D };
      const attrs = { depthRadius, bias, alpha, beta };
      const res = ENGINE.runKernel(LRN, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      } else {
        return res;
      }
    }
    var localResponseNormalization = /* @__PURE__ */ op({ localResponseNormalization_ });
    function log1p_(x) {
      const $x = convertToTensor(x, "x", "log1p");
      const inputs = { x: $x };
      return ENGINE.runKernel(Log1p, inputs);
    }
    var log1p = /* @__PURE__ */ op({ log1p_ });
    function variableGrads(f, varList) {
      assert(isFunction(f), () => "The f passed in variableGrads(f) must be a function");
      assert(varList == null || Array.isArray(varList) && varList.every((v) => v instanceof Variable), () => "The varList passed in variableGrads(f, varList) must be an array of variables");
      const specifiedVarList = varList != null;
      if (!specifiedVarList) {
        varList = [];
        for (const varName in ENGINE.registeredVariables) {
          varList.push(ENGINE.registeredVariables[varName]);
        }
      }
      const specifiedNonTrainable = specifiedVarList ? varList.filter((variable2) => !variable2.trainable) : null;
      const originalVarCount = varList.length;
      varList = varList.filter((variable2) => variable2.trainable);
      assert(varList.length > 0, () => `variableGrads() expects at least one of the input variables to be trainable, but none of the ${originalVarCount} variables is trainable.`);
      const allowNoGradients = true;
      const { value, grads: grads2 } = ENGINE.gradients(f, varList, null, allowNoGradients);
      assert(grads2.some((g) => g != null), () => "Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize().");
      assert(value.rank === 0, () => `The f passed in variableGrads(f) must return a scalar, but it returned a rank-${value.rank} tensor`);
      const namedGrads = {};
      varList.forEach((v, i) => {
        if (grads2[i] != null) {
          namedGrads[v.name] = grads2[i];
        }
      });
      if (specifiedNonTrainable != null) {
        specifiedNonTrainable.forEach((v) => namedGrads[v.name] = null);
      }
      return { value, grads: namedGrads };
    }
    function customGrad(f) {
      return ENGINE.customGrad(f);
    }
    function softplus_(x) {
      const $x = convertToTensor(x, "x", "softplus");
      const inputs = { x: $x };
      return ENGINE.runKernel(Softplus, inputs);
    }
    var softplus = /* @__PURE__ */ op({ softplus_ });
    function logSigmoid_(x) {
      const $x = convertToTensor(x, "x", "logSigmoid");
      const customOp = customGrad((x2) => {
        const value = neg(softplus(neg(x2)));
        const gradFunc = (dy) => {
          const derX = mul(dy, sigmoid(neg(x2)));
          return derX;
        };
        return { value, gradFunc };
      });
      return customOp($x);
    }
    var logSigmoid = /* @__PURE__ */ op({ logSigmoid_ });
    function logSoftmax_(logits, axis = -1) {
      const $logits = convertToTensor(logits, "logits", "logSoftmax");
      if (axis === -1) {
        axis = $logits.rank - 1;
      }
      if (axis !== $logits.rank - 1) {
        throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${$logits.rank} and axis was ${axis}`);
      }
      const customOp = customGrad((logits2, save) => {
        const keepDims = true;
        const xMax = max(logits2, axis, true);
        const shifted = sub(logits2, xMax);
        const value = sub(cast(shifted, "float32"), log(sum(exp(shifted), axis, keepDims)));
        save([value]);
        const gradFunc = (dy, saved) => {
          const [value2] = saved;
          const keepDims2 = true;
          const softmax2 = exp(value2);
          return sub(dy, mul(sum(dy, axis, keepDims2), softmax2));
        };
        return { value, gradFunc };
      });
      return customOp($logits);
    }
    var logSoftmax = /* @__PURE__ */ op({ logSoftmax_ });
    function logSumExp_(x, axis = null, keepDims = false) {
      const $x = convertToTensor(x, "x", "logSumExp");
      const axes = parseAxisParam(axis, $x.shape);
      const xMax = max(
        $x,
        axes,
        true
        /* keepDims */
      );
      const a = sub($x, xMax);
      const b = exp(a);
      const c = sum(b, axes);
      const d = log(c);
      const res = add(reshape(xMax, d.shape), d);
      if (keepDims) {
        const newShape = expandShapeToKeepDim(res.shape, axes);
        return reshape(res, newShape);
      }
      return res;
    }
    var logSumExp = /* @__PURE__ */ op({ logSumExp_ });
    function logicalNot_(x) {
      const $x = convertToTensor(x, "x", "logicalNot", "bool");
      const inputs = { x: $x };
      return ENGINE.runKernel(LogicalNot, inputs);
    }
    var logicalNot = /* @__PURE__ */ op({ logicalNot_ });
    function logicalOr_(a, b) {
      const $a = convertToTensor(a, "a", "logicalOr", "bool");
      const $b = convertToTensor(b, "b", "logicalOr", "bool");
      assertAndGetBroadcastShape($a.shape, $b.shape);
      const inputs = { a: $a, b: $b };
      return ENGINE.runKernel(LogicalOr, inputs);
    }
    var logicalOr = /* @__PURE__ */ op({ logicalOr_ });
    function logicalXor_(a, b) {
      const $a = convertToTensor(a, "a", "logicalXor", "bool");
      const $b = convertToTensor(b, "b", "logicalXor", "bool");
      assertAndGetBroadcastShape($a.shape, $b.shape);
      return logicalAnd(logicalOr(a, b), logicalNot(logicalAnd(a, b)));
    }
    var logicalXor = /* @__PURE__ */ op({ logicalXor_ });
    function maxPool_(x, filterSize, strides, pad2, dimRoundingMode) {
      const $x = convertToTensor(x, "x", "maxPool");
      const dilations = 1;
      let x4D = $x;
      let reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(x4D.rank === 4, () => `Error in maxPool: input must be rank 4 but got rank ${x4D.rank}.`);
      assert(eitherStridesOrDilationsAreOne(strides, dilations), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${strides} and dilations '${dilations}'`);
      checkPadOnDimRoundingMode("maxPool", pad2, dimRoundingMode);
      const inputs = { x: x4D };
      const attrs = { filterSize, strides, pad: pad2, dimRoundingMode };
      const res = ENGINE.runKernel(MaxPool, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var maxPool = /* @__PURE__ */ op({ maxPool_ });
    function maximum_(a, b) {
      let $a = convertToTensor(a, "a", "maximum");
      let $b = convertToTensor(b, "b", "maximum");
      [$a, $b] = makeTypesMatch($a, $b);
      if ($a.dtype === "bool") {
        $a = cast($a, "int32");
        $b = cast($b, "int32");
      }
      assertAndGetBroadcastShape($a.shape, $b.shape);
      const inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Maximum, inputs);
    }
    var maximum = /* @__PURE__ */ op({ maximum_ });
    function mean_(x, axis = null, keepDims = false) {
      const $x = convertToTensor(x, "x", "mean");
      const inputs = { x: $x };
      const attrs = { axis, keepDims };
      return ENGINE.runKernel(Mean, inputs, attrs);
    }
    var mean$1 = /* @__PURE__ */ op({ mean_ });
    function minimum_(a, b) {
      let $a = convertToTensor(a, "a", "minimum");
      let $b = convertToTensor(b, "b", "minimum");
      [$a, $b] = makeTypesMatch($a, $b);
      if ($a.dtype === "bool") {
        $a = cast($a, "int32");
        $b = cast($b, "int32");
      }
      assertAndGetBroadcastShape($a.shape, $b.shape);
      const inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Minimum, inputs);
    }
    var minimum = /* @__PURE__ */ op({ minimum_ });
    function mirrorPad_(x, paddings, mode) {
      assert(mode === "reflect" || mode === "symmetric", () => `Invalid mode. Mode must be either reflect or symmetric. Got ${mode}.`);
      const $x = convertToTensor(x, "x", "mirrorPad");
      if ($x.rank === 0) {
        throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");
      }
      assert(paddings.length === $x.rank, () => `Padding doesn't match input. Must be ${$x.rank}. Got ${paddings.length}.`);
      const shapeOffset = mode === "reflect" ? 1 : 0;
      for (let i = 0; i < $x.rank; i++) {
        assert(paddings[i].length === 2, () => `Invalid number of paddings. Must be length of 2 each.`);
        assert(paddings[i][0] >= 0 && paddings[i][0] <= $x.shape[i] - shapeOffset && paddings[i][1] >= 0 && paddings[i][1] <= $x.shape[i] - shapeOffset, () => `Padding in dimension ${i} cannot be greater than or equal to ${$x.shape[i] - shapeOffset} or less than 0 for input of shape ${$x.shape}`);
      }
      const attrs = { paddings, mode };
      const inputs = { x: $x };
      return ENGINE.runKernel(MirrorPad, inputs, attrs);
    }
    var mirrorPad = /* @__PURE__ */ op({ mirrorPad_ });
    function mod_(a, b) {
      let $a = convertToTensor(a, "a", "mod");
      let $b = convertToTensor(b, "b", "mod");
      [$a, $b] = makeTypesMatch($a, $b);
      const inputs = { a: $a, b: $b };
      return ENGINE.runKernel(Mod, inputs);
    }
    var mod = /* @__PURE__ */ op({ mod_ });
    function notEqual_(a, b) {
      let $a = convertToTensor(a, "a", "notEqual", "string_or_numeric");
      let $b = convertToTensor(b, "b", "notEqual", "string_or_numeric");
      [$a, $b] = makeTypesMatch($a, $b);
      assertAndGetBroadcastShape($a.shape, $b.shape);
      const inputs = { a: $a, b: $b };
      return ENGINE.runKernel(NotEqual, inputs);
    }
    var notEqual = /* @__PURE__ */ op({ notEqual_ });
    function onesLike_(x) {
      const $x = convertToTensor(x, "x", "onesLike");
      const inputs = { x: $x };
      return ENGINE.runKernel(OnesLike, inputs);
    }
    var onesLike = /* @__PURE__ */ op({ onesLike_ });
    function pad_(x, paddings, constantValue = 0) {
      const $x = convertToTensor(x, "x", "pad");
      if ($x.rank === 0) {
        throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");
      }
      const attrs = { paddings, constantValue };
      const inputs = { x: $x };
      return ENGINE.runKernel(PadV2, inputs, attrs);
    }
    var pad = /* @__PURE__ */ op({ pad_ });
    function pool_(input, windowShape, poolingType, pad2, dilations, strides, dimRoundingMode) {
      if (dilations == null) {
        dilations = [1, 1];
      }
      if (strides == null) {
        strides = 1;
      }
      if (pad2 === 0) {
        pad2 = "valid";
      }
      const $x = convertToTensor(input, "x", "maxPool");
      let x4D = $x;
      let reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      assert(eitherStridesOrDilationsAreOne(strides, dilations), () => `Error in pool: Either strides or dilations must be 1. Got strides ${strides} and dilations '${dilations}'`);
      const convInfo = computePool2DInfo(x4D.shape, windowShape, strides, dilations, pad2);
      const dilation = [convInfo.dilationHeight, convInfo.dilationWidth];
      let basePadding;
      if (pad2 === "same") {
        basePadding = withSpaceToBatchBasePaddings([convInfo.filterHeight, convInfo.filterWidth], dilation);
      } else {
        basePadding = [[0, 0], [0, 0]];
      }
      const isDilationOne = dilation[0] === 1 && dilation[1] === 1;
      const [adjustedPadding, adjustedCrops] = requiredSpaceToBatchPaddings([convInfo.inHeight, convInfo.inWidth], dilation, basePadding);
      const convertedPad = isDilationOne ? pad2 : "valid";
      const convertedX = isDilationOne ? x4D : spaceToBatchND(x4D, dilation, adjustedPadding);
      const forwardOp = poolingType === "avg" ? () => avgPool(convertedX, windowShape, strides, convertedPad, dimRoundingMode) : () => maxPool(convertedX, windowShape, strides, convertedPad, dimRoundingMode);
      const y = forwardOp();
      const res = isDilationOne ? y : batchToSpaceND(y, dilation, adjustedCrops);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    function requiredSpaceToBatchPaddings(inputShape, blockShape, basePadding) {
      const padStart = basePadding.map((b) => b[0]);
      const origPadEnd = basePadding.map((b) => b[1]);
      const fullInputShape = inputShape.concat(padStart, origPadEnd);
      const padEndExtra = blockShape.map((b, i) => (b - fullInputShape[i] % b) % b);
      const padEnd = origPadEnd.map((s, i) => s + padEndExtra[i]);
      const paddings = blockShape.map((_, i) => [padStart[i], padEnd[i]]);
      const crops = blockShape.map((_, i) => [0, padEndExtra[i]]);
      return [paddings, crops];
    }
    function withSpaceToBatchBasePaddings(filterShape, dilation) {
      const dilatedFilterShape = filterShape.map((s, i) => {
        return s + (s - 1) * (dilation[i] - 1);
      });
      const padExtraShape = dilatedFilterShape.map((s) => s - 1);
      const padExtraStart = padExtraShape.map((s) => Math.floor(s / 2));
      const padExtraEnd = padExtraShape.map((s, i) => s - padExtraStart[i]);
      return padExtraShape.map((_, i) => {
        return [padExtraStart[i], padExtraEnd[i]];
      });
    }
    var pool = /* @__PURE__ */ op({ pool_ });
    function prelu_(x, alpha) {
      const $x = convertToTensor(x, "x", "prelu");
      const $alpha = convertToTensor(alpha, "alpha", "prelu");
      const inputs = { x: $x, alpha: $alpha };
      return ENGINE.runKernel(Prelu, inputs);
    }
    var prelu = /* @__PURE__ */ op({ prelu_ });
    function prod_(x, axis = null, keepDims = false) {
      let $x = convertToTensor(x, "x", "prod");
      if ($x.dtype === "bool") {
        $x = cast($x, "int32");
      }
      const inputs = { x: $x };
      const attrs = { axis, keepDims };
      return ENGINE.runKernel(Prod, inputs, attrs);
    }
    var prod = /* @__PURE__ */ op({ prod_ });
    var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
    var alea$3 = { exports: {} };
    var alea$1 = alea$3.exports;
    (function(module3) {
      (function(global2, module4, define2) {
        function Alea(seed) {
          var me = this, mash = Mash();
          me.next = function() {
            var t = 2091639 * me.s0 + me.c * 23283064365386963e-26;
            me.s0 = me.s1;
            me.s1 = me.s2;
            return me.s2 = t - (me.c = t | 0);
          };
          me.c = 1;
          me.s0 = mash(" ");
          me.s1 = mash(" ");
          me.s2 = mash(" ");
          me.s0 -= mash(seed);
          if (me.s0 < 0) {
            me.s0 += 1;
          }
          me.s1 -= mash(seed);
          if (me.s1 < 0) {
            me.s1 += 1;
          }
          me.s2 -= mash(seed);
          if (me.s2 < 0) {
            me.s2 += 1;
          }
          mash = null;
        }
        function copy(f, t) {
          t.c = f.c;
          t.s0 = f.s0;
          t.s1 = f.s1;
          t.s2 = f.s2;
          return t;
        }
        function impl(seed, opts) {
          var xg = new Alea(seed), state = opts && opts.state, prng = xg.next;
          prng.int32 = function() {
            return xg.next() * 4294967296 | 0;
          };
          prng.double = function() {
            return prng() + (prng() * 2097152 | 0) * 11102230246251565e-32;
          };
          prng.quick = prng;
          if (state) {
            if (typeof state == "object") copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        function Mash() {
          var n = 4022871197;
          var mash = function(data) {
            data = String(data);
            for (var i = 0; i < data.length; i++) {
              n += data.charCodeAt(i);
              var h = 0.02519603282416938 * n;
              n = h >>> 0;
              h -= n;
              h *= n;
              n = h >>> 0;
              h -= n;
              n += h * 4294967296;
            }
            return (n >>> 0) * 23283064365386963e-26;
          };
          return mash;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.alea = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(alea$3);
    var aleaExports = alea$3.exports;
    var xor128$3 = { exports: {} };
    var xor128$1 = xor128$3.exports;
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this, strseed = "";
          me.x = 0;
          me.y = 0;
          me.z = 0;
          me.w = 0;
          me.next = function() {
            var t = me.x ^ me.x << 11;
            me.x = me.y;
            me.y = me.z;
            me.z = me.w;
            return me.w ^= me.w >>> 19 ^ t ^ t >>> 8;
          };
          if (seed === (seed | 0)) {
            me.x = seed;
          } else {
            strseed += seed;
          }
          for (var k = 0; k < strseed.length + 64; k++) {
            me.x ^= strseed.charCodeAt(k) | 0;
            me.next();
          }
        }
        function copy(f, t) {
          t.x = f.x;
          t.y = f.y;
          t.z = f.z;
          t.w = f.w;
          return t;
        }
        function impl(seed, opts) {
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (typeof state == "object") copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xor128 = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xor128$3);
    var xor128Exports = xor128$3.exports;
    var xorwow$3 = { exports: {} };
    var xorwow$1 = xorwow$3.exports;
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this, strseed = "";
          me.next = function() {
            var t = me.x ^ me.x >>> 2;
            me.x = me.y;
            me.y = me.z;
            me.z = me.w;
            me.w = me.v;
            return (me.d = me.d + 362437 | 0) + (me.v = me.v ^ me.v << 4 ^ (t ^ t << 1)) | 0;
          };
          me.x = 0;
          me.y = 0;
          me.z = 0;
          me.w = 0;
          me.v = 0;
          if (seed === (seed | 0)) {
            me.x = seed;
          } else {
            strseed += seed;
          }
          for (var k = 0; k < strseed.length + 64; k++) {
            me.x ^= strseed.charCodeAt(k) | 0;
            if (k == strseed.length) {
              me.d = me.x << 10 ^ me.x >>> 4;
            }
            me.next();
          }
        }
        function copy(f, t) {
          t.x = f.x;
          t.y = f.y;
          t.z = f.z;
          t.w = f.w;
          t.v = f.v;
          t.d = f.d;
          return t;
        }
        function impl(seed, opts) {
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (typeof state == "object") copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xorwow = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xorwow$3);
    var xorwowExports = xorwow$3.exports;
    var xorshift7$3 = { exports: {} };
    var xorshift7$1 = xorshift7$3.exports;
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this;
          me.next = function() {
            var X = me.x, i = me.i, t, v, w;
            t = X[i];
            t ^= t >>> 7;
            v = t ^ t << 24;
            t = X[i + 1 & 7];
            v ^= t ^ t >>> 10;
            t = X[i + 3 & 7];
            v ^= t ^ t >>> 3;
            t = X[i + 4 & 7];
            v ^= t ^ t << 7;
            t = X[i + 7 & 7];
            t = t ^ t << 13;
            v ^= t ^ t << 9;
            X[i] = v;
            me.i = i + 1 & 7;
            return v;
          };
          function init(me2, seed2) {
            var j, w, X = [];
            if (seed2 === (seed2 | 0)) {
              w = X[0] = seed2;
            } else {
              seed2 = "" + seed2;
              for (j = 0; j < seed2.length; ++j) {
                X[j & 7] = X[j & 7] << 15 ^ seed2.charCodeAt(j) + X[j + 1 & 7] << 13;
              }
            }
            while (X.length < 8) X.push(0);
            for (j = 0; j < 8 && X[j] === 0; ++j) ;
            if (j == 8) w = X[7] = -1;
            else w = X[j];
            me2.x = X;
            me2.i = 0;
            for (j = 256; j > 0; --j) {
              me2.next();
            }
          }
          init(me, seed);
        }
        function copy(f, t) {
          t.x = f.x.slice();
          t.i = f.i;
          return t;
        }
        function impl(seed, opts) {
          if (seed == null) seed = +/* @__PURE__ */ new Date();
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (state.x) copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xorshift7 = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xorshift7$3);
    var xorshift7Exports = xorshift7$3.exports;
    var xor4096$3 = { exports: {} };
    var xor4096$1 = xor4096$3.exports;
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this;
          me.next = function() {
            var w = me.w, X = me.X, i = me.i, t, v;
            me.w = w = w + 1640531527 | 0;
            v = X[i + 34 & 127];
            t = X[i = i + 1 & 127];
            v ^= v << 13;
            t ^= t << 17;
            v ^= v >>> 15;
            t ^= t >>> 12;
            v = X[i] = v ^ t;
            me.i = i;
            return v + (w ^ w >>> 16) | 0;
          };
          function init(me2, seed2) {
            var t, v, i, j, w, X = [], limit = 128;
            if (seed2 === (seed2 | 0)) {
              v = seed2;
              seed2 = null;
            } else {
              seed2 = seed2 + "\0";
              v = 0;
              limit = Math.max(limit, seed2.length);
            }
            for (i = 0, j = -32; j < limit; ++j) {
              if (seed2) v ^= seed2.charCodeAt((j + 32) % seed2.length);
              if (j === 0) w = v;
              v ^= v << 10;
              v ^= v >>> 15;
              v ^= v << 4;
              v ^= v >>> 13;
              if (j >= 0) {
                w = w + 1640531527 | 0;
                t = X[j & 127] ^= v + w;
                i = 0 == t ? i + 1 : 0;
              }
            }
            if (i >= 128) {
              X[(seed2 && seed2.length || 0) & 127] = -1;
            }
            i = 127;
            for (j = 4 * 128; j > 0; --j) {
              v = X[i + 34 & 127];
              t = X[i = i + 1 & 127];
              v ^= v << 13;
              t ^= t << 17;
              v ^= v >>> 15;
              t ^= t >>> 12;
              X[i] = v ^ t;
            }
            me2.w = w;
            me2.X = X;
            me2.i = i;
          }
          init(me, seed);
        }
        function copy(f, t) {
          t.i = f.i;
          t.w = f.w;
          t.X = f.X.slice();
          return t;
        }
        ;
        function impl(seed, opts) {
          if (seed == null) seed = +/* @__PURE__ */ new Date();
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (state.X) copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.xor4096 = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(xor4096$3);
    var xor4096Exports = xor4096$3.exports;
    var tychei$3 = { exports: {} };
    var tychei$1 = tychei$3.exports;
    (function(module3) {
      (function(global2, module4, define2) {
        function XorGen(seed) {
          var me = this, strseed = "";
          me.next = function() {
            var b = me.b, c = me.c, d = me.d, a = me.a;
            b = b << 25 ^ b >>> 7 ^ c;
            c = c - d | 0;
            d = d << 24 ^ d >>> 8 ^ a;
            a = a - b | 0;
            me.b = b = b << 20 ^ b >>> 12 ^ c;
            me.c = c = c - d | 0;
            me.d = d << 16 ^ c >>> 16 ^ a;
            return me.a = a - b | 0;
          };
          me.a = 0;
          me.b = 0;
          me.c = 2654435769 | 0;
          me.d = 1367130551;
          if (seed === Math.floor(seed)) {
            me.a = seed / 4294967296 | 0;
            me.b = seed | 0;
          } else {
            strseed += seed;
          }
          for (var k = 0; k < strseed.length + 20; k++) {
            me.b ^= strseed.charCodeAt(k) | 0;
            me.next();
          }
        }
        function copy(f, t) {
          t.a = f.a;
          t.b = f.b;
          t.c = f.c;
          t.d = f.d;
          return t;
        }
        ;
        function impl(seed, opts) {
          var xg = new XorGen(seed), state = opts && opts.state, prng = function() {
            return (xg.next() >>> 0) / 4294967296;
          };
          prng.double = function() {
            do {
              var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21);
            } while (result === 0);
            return result;
          };
          prng.int32 = xg.next;
          prng.quick = prng;
          if (state) {
            if (typeof state == "object") copy(state, xg);
            prng.state = function() {
              return copy(xg, {});
            };
          }
          return prng;
        }
        if (module4 && module4.exports) {
          module4.exports = impl;
        } else if (define2 && define2.amd) {
          define2(function() {
            return impl;
          });
        } else {
          this.tychei = impl;
        }
      })(
        commonjsGlobal,
        module3,
        // present in node.js
        false
        // present with an AMD loader
      );
    })(tychei$3);
    var tycheiExports = tychei$3.exports;
    var seedrandom$3 = { exports: {} };
    var seedrandom$1 = seedrandom$3.exports;
    (function(module3) {
      (function(global2, pool2, math2) {
        var width = 256, chunks = 6, digits = 52, rngname = "random", startdenom = math2.pow(width, chunks), significance = math2.pow(2, digits), overflow = significance * 2, mask = width - 1, nodecrypto;
        function seedrandom2(seed, options, callback) {
          var key = [];
          options = options == true ? { entropy: true } : options || {};
          var shortseed = mixkey(flatten2(
            options.entropy ? [seed, tostring(pool2)] : seed == null ? autoseed() : seed,
            3
          ), key);
          var arc4 = new ARC4(key);
          var prng = function() {
            var n = arc4.g(chunks), d = startdenom, x = 0;
            while (n < significance) {
              n = (n + x) * width;
              d *= width;
              x = arc4.g(1);
            }
            while (n >= overflow) {
              n /= 2;
              d /= 2;
              x >>>= 1;
            }
            return (n + x) / d;
          };
          prng.int32 = function() {
            return arc4.g(4) | 0;
          };
          prng.quick = function() {
            return arc4.g(4) / 4294967296;
          };
          prng.double = prng;
          mixkey(tostring(arc4.S), pool2);
          return (options.pass || callback || function(prng2, seed2, is_math_call, state) {
            if (state) {
              if (state.S) {
                copy(state, arc4);
              }
              prng2.state = function() {
                return copy(arc4, {});
              };
            }
            if (is_math_call) {
              math2[rngname] = prng2;
              return seed2;
            } else return prng2;
          })(
            prng,
            shortseed,
            "global" in options ? options.global : this == math2,
            options.state
          );
        }
        function ARC4(key) {
          var t, keylen = key.length, me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
          if (!keylen) {
            key = [keylen++];
          }
          while (i < width) {
            s[i] = i++;
          }
          for (i = 0; i < width; i++) {
            s[i] = s[j = mask & j + key[i % keylen] + (t = s[i])];
            s[j] = t;
          }
          (me.g = function(count) {
            var t2, r = 0, i2 = me.i, j2 = me.j, s2 = me.S;
            while (count--) {
              t2 = s2[i2 = mask & i2 + 1];
              r = r * width + s2[mask & (s2[i2] = s2[j2 = mask & j2 + t2]) + (s2[j2] = t2)];
            }
            me.i = i2;
            me.j = j2;
            return r;
          })(width);
        }
        function copy(f, t) {
          t.i = f.i;
          t.j = f.j;
          t.S = f.S.slice();
          return t;
        }
        ;
        function flatten2(obj, depth) {
          var result = [], typ = typeof obj, prop;
          if (depth && typ == "object") {
            for (prop in obj) {
              try {
                result.push(flatten2(obj[prop], depth - 1));
              } catch (e) {
              }
            }
          }
          return result.length ? result : typ == "string" ? obj : obj + "\0";
        }
        function mixkey(seed, key) {
          var stringseed = seed + "", smear, j = 0;
          while (j < stringseed.length) {
            key[mask & j] = mask & (smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++);
          }
          return tostring(key);
        }
        function autoseed() {
          try {
            var out;
            if (nodecrypto && (out = nodecrypto.randomBytes)) {
              out = out(width);
            } else {
              out = new Uint8Array(width);
              (global2.crypto || global2.msCrypto).getRandomValues(out);
            }
            return tostring(out);
          } catch (e) {
            var browser2 = global2.navigator, plugins = browser2 && browser2.plugins;
            return [+/* @__PURE__ */ new Date(), global2, plugins, global2.screen, tostring(pool2)];
          }
        }
        function tostring(a) {
          return String.fromCharCode.apply(0, a);
        }
        mixkey(math2.random(), pool2);
        if (module3.exports) {
          module3.exports = seedrandom2;
          try {
            nodecrypto = require("crypto");
          } catch (ex) {
          }
        } else if (false) {
          (void 0)(function() {
            return seedrandom2;
          });
        } else {
          math2["seed" + rngname] = seedrandom2;
        }
      })(
        // global: `self` in browsers (including strict mode and web workers),
        // otherwise `this` in Node and other environments
        typeof self !== "undefined" ? self : commonjsGlobal,
        [],
        // pool: entropy pool starts empty
        Math
        // math: package containing random, pow, and seedrandom
      );
    })(seedrandom$3);
    var seedrandomExports = seedrandom$3.exports;
    var alea = aleaExports;
    var xor128 = xor128Exports;
    var xorwow = xorwowExports;
    var xorshift7 = xorshift7Exports;
    var xor4096 = xor4096Exports;
    var tychei = tycheiExports;
    var sr = seedrandomExports;
    sr.alea = alea;
    sr.xor128 = xor128;
    sr.xorwow = xorwow;
    sr.xorshift7 = xorshift7;
    sr.xor4096 = xor4096;
    sr.tychei = tychei;
    function reciprocal_(x) {
      const $x = convertToTensor(x, "x", "reciprocal");
      const inputs = { x: $x };
      return ENGINE.runKernel(Reciprocal, inputs);
    }
    var reciprocal = /* @__PURE__ */ op({ reciprocal_ });
    function relu_(x) {
      const $x = convertToTensor(x, "x", "relu");
      const inputs = { x: $x };
      return ENGINE.runKernel(Relu, inputs);
    }
    var relu = /* @__PURE__ */ op({ relu_ });
    function relu6_(x) {
      const $x = convertToTensor(x, "x", "relu6");
      const inputs = { x: $x };
      return ENGINE.runKernel(Relu6, inputs);
    }
    var relu6 = /* @__PURE__ */ op({ relu6_ });
    function reverse_(x, axis) {
      const $x = convertToTensor(x, "x", "reverse");
      const inputs = { x: $x };
      const attrs = { dims: axis };
      return ENGINE.runKernel(Reverse, inputs, attrs);
    }
    var reverse = /* @__PURE__ */ op({ reverse_ });
    function round_(x) {
      const $x = convertToTensor(x, "x", "round");
      const inputs = { x: $x };
      return ENGINE.runKernel(Round, inputs);
    }
    var round = /* @__PURE__ */ op({ round_ });
    function selu_(x) {
      const $x = convertToTensor(x, "x", "selu");
      const inputs = { x: $x };
      return ENGINE.runKernel(Selu, inputs);
    }
    var selu = /* @__PURE__ */ op({ selu_ });
    function separableConv2d_(x, depthwiseFilter, pointwiseFilter, strides, pad2, dilation = [1, 1], dataFormat = "NHWC") {
      const $x = convertToTensor(x, "x", "separableConv2d");
      const $depthwiseFilter = convertToTensor(depthwiseFilter, "depthwiseFilter", "separableConv2d");
      const $pointwiseFilter = convertToTensor(pointwiseFilter, "pointwiseFilter", "separableConv2d");
      let x4D = $x;
      let reshapedTo4D = false;
      if ($x.rank === 3) {
        reshapedTo4D = true;
        x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
      }
      if (dataFormat === "NCHW") {
        throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");
      }
      assert(x4D.rank === 4, () => `Error in separableConv2d: input must be rank 4, but got rank ${x4D.rank}.`);
      assert($depthwiseFilter.rank === 4, () => `Error in separableConv2d: depthwise filter must be rank 4, but got rank ${$depthwiseFilter.rank}.`);
      assert($pointwiseFilter.rank === 4, () => `Error in separableConv2d: pointwise filter must be rank 4, but got rank ${$depthwiseFilter.rank}.`);
      assert($pointwiseFilter.shape[0] === 1, () => `Error in separableConv2d: the first dimension of pointwise filter  must be 1, but got ${$pointwiseFilter.shape[0]}.`);
      assert($pointwiseFilter.shape[1] === 1, () => `Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${$pointwiseFilter.shape[1]}.`);
      const inChannels = $depthwiseFilter.shape[2];
      const channelMultiplier = $depthwiseFilter.shape[3];
      assert($pointwiseFilter.shape[2] === inChannels * channelMultiplier, () => `Error in separableConv2d: the third dimension of pointwise filter must be ${inChannels * channelMultiplier}, but got ${$pointwiseFilter.shape[2]}.`);
      const depthwise = depthwiseConv2d$1(x4D, $depthwiseFilter, strides, pad2, dataFormat, dilation);
      const pointwiseStride = 1;
      const res = conv2d$1(depthwise, $pointwiseFilter, pointwiseStride, "valid", dataFormat);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var separableConv2d = /* @__PURE__ */ op({ separableConv2d_ });
    function sign_(x) {
      const $x = convertToTensor(x, "x", "sign");
      const inputs = { x: $x };
      return ENGINE.runKernel(Sign, inputs);
    }
    var sign = /* @__PURE__ */ op({ sign_ });
    function softmax_(logits, dim = -1) {
      const $logits = convertToTensor(logits, "logits", "softmax", "float32");
      if (dim === -1) {
        dim = $logits.rank - 1;
      }
      if (dim !== $logits.rank - 1) {
        throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${$logits.rank} and dim was ${dim}`);
      }
      const inputs = { logits: $logits };
      const attrs = { dim };
      return ENGINE.runKernel(Softmax, inputs, attrs);
    }
    var softmax = /* @__PURE__ */ op({ softmax_ });
    function fft_(input) {
      assert(input.dtype === "complex64", () => `The dtype for tf.spectral.fft() must be complex64 but got ${input.dtype}.`);
      const inputs = { input };
      return ENGINE.runKernel(FFT, inputs);
    }
    var fft = /* @__PURE__ */ op({ fft_ });
    function ifft_(input) {
      assert(input.dtype === "complex64", () => `The dtype for tf.spectral.ifft() must be complex64 but got ${input.dtype}.`);
      const inputs = { input };
      return ENGINE.runKernel(IFFT, inputs);
    }
    var ifft = /* @__PURE__ */ op({ ifft_ });
    function irfft_(input) {
      const innerDimensionSize = input.shape[input.shape.length - 1];
      const batch = input.size / innerDimensionSize;
      let ret;
      if (innerDimensionSize <= 2) {
        const complexInput = reshape(input, [batch, innerDimensionSize]);
        ret = ifft(complexInput);
      } else {
        const outputShape = [batch, 2 * (innerDimensionSize - 1)];
        const realInput = reshape(real(input), [batch, innerDimensionSize]);
        const imagInput = reshape(imag(input), [batch, innerDimensionSize]);
        const realConjugate = reverse(slice(realInput, [0, 1], [batch, innerDimensionSize - 2]), 1);
        const imagConjugate = mul(reverse(slice(imagInput, [0, 1], [batch, innerDimensionSize - 2]), 1), scalar(-1));
        const r = concat([realInput, realConjugate], 1);
        const i = concat([imagInput, imagConjugate], 1);
        const complexInput = reshape(complex(r, i), [outputShape[0], outputShape[1]]);
        ret = ifft(complexInput);
      }
      ret = real(ret);
      if (input.rank === 3 && input.shape[0] !== 0) {
        const temp = ret;
        const batch2 = input.shape[0];
        ret = reshape(ret, [batch2, ret.shape[0] / batch2, ret.shape[1]]);
        temp.dispose();
      }
      return ret;
    }
    var irfft = /* @__PURE__ */ op({ irfft_ });
    function rfft_(input, fftLength) {
      assert(input.dtype === "float32", () => `The dtype for rfft() must be real value but got ${input.dtype}`);
      let innerDimensionSize = input.shape[input.shape.length - 1];
      const batch = input.size / innerDimensionSize;
      let adjustedInput;
      if (fftLength != null && fftLength < innerDimensionSize) {
        const begin = input.shape.map((v) => 0);
        const size = input.shape.map((v) => v);
        size[input.shape.length - 1] = fftLength;
        adjustedInput = slice(input, begin, size);
        innerDimensionSize = fftLength;
      } else if (fftLength != null && fftLength > innerDimensionSize) {
        const zerosShape = input.shape.map((v) => v);
        zerosShape[input.shape.length - 1] = fftLength - innerDimensionSize;
        adjustedInput = concat([input, zeros(zerosShape)], input.shape.length - 1);
        innerDimensionSize = fftLength;
      } else {
        adjustedInput = input;
      }
      const zerosInput = zerosLike(adjustedInput);
      const complexInput = reshape(complex(adjustedInput, zerosInput), [batch, innerDimensionSize]);
      const ret = fft(complexInput);
      const half = Math.floor(innerDimensionSize / 2) + 1;
      const realValues = real(ret);
      const imagValues = imag(ret);
      const realComplexConjugate = split(realValues, [half, innerDimensionSize - half], realValues.shape.length - 1);
      const imagComplexConjugate = split(imagValues, [half, innerDimensionSize - half], imagValues.shape.length - 1);
      const outputShape = adjustedInput.shape.slice();
      outputShape[adjustedInput.shape.length - 1] = half;
      return reshape(complex(realComplexConjugate[0], imagComplexConjugate[0]), outputShape);
    }
    var rfft = /* @__PURE__ */ op({ rfft_ });
    function squaredDifference_(a, b) {
      let $a = convertToTensor(a, "a", "squaredDifference");
      let $b = convertToTensor(b, "b", "squaredDifference");
      [$a, $b] = makeTypesMatch($a, $b);
      assertAndGetBroadcastShape($a.shape, $b.shape);
      const inputs = { a: $a, b: $b };
      const attrs = {};
      return ENGINE.runKernel(SquaredDifference, inputs, attrs);
    }
    var squaredDifference = /* @__PURE__ */ op({ squaredDifference_ });
    function squeeze_(x, axis) {
      const $x = convertToTensor(x, "x", "squeeze", "string_or_numeric");
      return reshape($x, squeezeShape($x.shape, axis).newShape);
    }
    var squeeze = /* @__PURE__ */ op({ squeeze_ });
    function stridedSlice_(x, begin, end, strides, beginMask = 0, endMask = 0, ellipsisMask = 0, newAxisMask = 0, shrinkAxisMask = 0) {
      const $x = convertToTensor(x, "x", "stridedSlice", "string_or_numeric");
      const inputs = { x: $x };
      const attrs = {
        begin,
        end,
        strides,
        beginMask,
        endMask,
        ellipsisMask,
        newAxisMask,
        shrinkAxisMask
      };
      return ENGINE.runKernel(StridedSlice, inputs, attrs);
    }
    var stridedSlice = /* @__PURE__ */ op({ stridedSlice_ });
    function tan_(x) {
      const $x = convertToTensor(x, "x", "tan", "float32");
      const inputs = { x: $x };
      return ENGINE.runKernel(Tan, inputs);
    }
    var tan = /* @__PURE__ */ op({ tan_ });
    function tensorScatterUpdate_(tensor2, indices, updates) {
      const $tensor = convertToTensor(tensor2, "tensor", "tensorScatterupdate");
      const $indices = convertToTensor(indices, "indices", "tensorScatterupdate", "int32");
      const $updates = convertToTensor(updates, "updates", "tensorScatterupdate");
      validateInput$1($updates, $indices, $tensor.shape);
      if ($tensor.dtype !== $updates.dtype) {
        throw new Error(`tensor and updates must have the same dtype, instead they are ${$tensor.dtype} and ${$updates.dtype}.`);
      }
      const inputs = {
        tensor: $tensor,
        indices: $indices,
        updates: $updates
      };
      const attrs = {};
      return ENGINE.runKernel(TensorScatterUpdate, inputs, attrs);
    }
    var tensorScatterUpdate = op({ tensorScatterUpdate_ });
    function topk_(x, k = 1, sorted = true) {
      const $x = convertToTensor(x, "x", "topk");
      if ($x.rank === 0) {
        throw new Error("topk() expects the input to be of rank 1 or higher");
      }
      const lastDim = $x.shape[$x.shape.length - 1];
      if (k < 0) {
        throw new Error(`'k' passed to topk() must be >= 0 but got ${k}`);
      }
      if (k > lastDim) {
        throw new Error(`'k' passed to topk() must be <= the last dimension (${lastDim}) but got ${k}`);
      }
      const inputs = { x: $x };
      const attrs = { k, sorted };
      const [values, indices] = ENGINE.runKernel(TopK, inputs, attrs);
      return { values, indices };
    }
    var topk = /* @__PURE__ */ op({ topk_ });
    function unique_(x, axis = 0) {
      const $x = convertToTensor(x, "x", "unique", "string_or_numeric");
      assert($x.rank > 0, () => "The input tensor must be at least 1D");
      const inputs = { x: $x };
      const attrs = { axis };
      const [values, indices] = ENGINE.runKernel(Unique, inputs, attrs);
      return { values, indices };
    }
    var unique = /* @__PURE__ */ op({ unique_ });
    function resizeBilinear_(images, size, alignCorners = false, halfPixelCenters = false) {
      const $images = convertToTensor(images, "images", "resizeBilinear");
      assert($images.rank === 3 || $images.rank === 4, () => `Error in resizeBilinear: x must be rank 3 or 4, but got rank ${$images.rank}.`);
      assert(size.length === 2, () => `Error in resizeBilinear: new shape must 2D, but got shape ${size}.`);
      assert(halfPixelCenters === false || alignCorners === false, () => `Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.`);
      let batchImages = $images;
      let reshapedTo4D = false;
      if ($images.rank === 3) {
        reshapedTo4D = true;
        batchImages = reshape($images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);
      }
      const [] = size;
      const inputs = { images: batchImages };
      const attrs = { alignCorners, halfPixelCenters, size };
      const res = ENGINE.runKernel(ResizeBilinear, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var resizeBilinear = /* @__PURE__ */ op({ resizeBilinear_ });
    function resizeNearestNeighbor_(images, size, alignCorners = false, halfPixelCenters = false) {
      const $images = convertToTensor(images, "images", "resizeNearestNeighbor");
      assert($images.rank === 3 || $images.rank === 4, () => `Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${$images.rank}.`);
      assert(size.length === 2, () => `Error in resizeNearestNeighbor: new shape must 2D, but got shape ${size}.`);
      assert($images.dtype === "float32" || $images.dtype === "int32", () => "`images` must have `int32` or `float32` as dtype");
      assert(halfPixelCenters === false || alignCorners === false, () => `Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.`);
      let batchImages = $images;
      let reshapedTo4D = false;
      if ($images.rank === 3) {
        reshapedTo4D = true;
        batchImages = reshape($images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);
      }
      const [] = size;
      const inputs = { images: batchImages };
      const attrs = { alignCorners, halfPixelCenters, size };
      const res = ENGINE.runKernel(ResizeNearestNeighbor, inputs, attrs);
      if (reshapedTo4D) {
        return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
      }
      return res;
    }
    var resizeNearestNeighbor = /* @__PURE__ */ op({ resizeNearestNeighbor_ });
    var Reduction;
    (function(Reduction2) {
      Reduction2[Reduction2["NONE"] = 0] = "NONE";
      Reduction2[Reduction2["MEAN"] = 1] = "MEAN";
      Reduction2[Reduction2["SUM"] = 2] = "SUM";
      Reduction2[Reduction2["SUM_BY_NONZERO_WEIGHTS"] = 3] = "SUM_BY_NONZERO_WEIGHTS";
    })(Reduction || (Reduction = {}));
    var Optimizer = class extends Serializable {
      /**
       * Executes `f()` and minimizes the scalar output of `f()` by computing
       * gradients of y with respect to the list of trainable variables provided by
       * `varList`. If no list is provided, it defaults to all trainable variables.
       *
       * @param f The function to execute and whose output to minimize.
       * @param returnCost Whether to return the scalar cost value produced by
       * executing `f()`.
       * @param varList An optional list of variables to update. If specified, only
       * the trainable variables in varList will be updated by minimize. Defaults to
       * all trainable variables.
       *
       * @doc {heading: 'Training', subheading: 'Optimizers'}
       */
      minimize(f, returnCost = false, varList) {
        const { value, grads: grads2 } = this.computeGradients(f, varList);
        if (varList != null) {
          const gradArray = varList.map((v) => ({ name: v.name, tensor: grads2[v.name] }));
          this.applyGradients(gradArray);
        } else {
          this.applyGradients(grads2);
        }
        dispose(grads2);
        if (returnCost) {
          return value;
        } else {
          value.dispose();
          return null;
        }
      }
      /**
       * The number of iterations that this optimizer instance has been invoked for.
       */
      get iterations() {
        if (this.iterations_ == null) {
          this.iterations_ = 0;
        }
        return this.iterations_;
      }
      incrementIterations() {
        this.iterations_ = this.iterations + 1;
      }
      /**
       * Executes f() and computes the gradient of the scalar output of f() with
       * respect to the list of trainable variables provided by `varList`. If no
       * list is provided, it defaults to all trainable variables.
       *
       * @param f The function to execute and whose output to use for computing
       * gradients with respect to variables.
       * @param varList An optional list of variables to compute gradients with
       * respect to. If specified, only the trainable variables in varList will have
       * gradients computed with respect to. Defaults to all trainable variables.
       *
       * @doc {heading: 'Training', subheading: 'Optimizers'}
       */
      computeGradients(f, varList) {
        return variableGrads(f, varList);
      }
      /**
       * Dispose the variables (if any) owned by this optimizer instance.
       */
      dispose() {
        if (this.iterations_ != null) {
          dispose(this.iterations_);
        }
      }
      async saveIterations() {
        if (this.iterations_ == null) {
          this.iterations_ = 0;
        }
        return {
          name: "iter",
          // TODO(cais): Use 'int64' type when available.
          tensor: scalar(this.iterations_, "int32")
        };
      }
      async getWeights() {
        throw new Error("getWeights() is not implemented for this optimizer yet.");
      }
      async setWeights(weightValues) {
        throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`);
      }
      /**
       * Extract the first element of the weight values and set it
       * as the iterations counter variable of this instance of optimizer.
       *
       * @param weightValues
       * @returns Weight values with the first element consumed and excluded.
       */
      async extractIterations(weightValues) {
        this.iterations_ = (await weightValues[0].tensor.data())[0];
        return weightValues.slice(1);
      }
    };
    Object.defineProperty(Optimizer, Symbol.hasInstance, {
      value: (instance) => {
        return instance.minimize != null && instance.computeGradients != null && instance.applyGradients != null;
      }
    });
    var delayCallback = (() => {
      if (typeof requestAnimationFrame !== "undefined") {
        return requestAnimationFrame;
      } else if (typeof setImmediate !== "undefined") {
        return setImmediate;
      }
      return (f) => f();
    })();
    var RowPartitionType;
    (function(RowPartitionType2) {
      RowPartitionType2[RowPartitionType2["FIRST_DIM_SIZE"] = 0] = "FIRST_DIM_SIZE";
      RowPartitionType2[RowPartitionType2["VALUE_ROWIDS"] = 1] = "VALUE_ROWIDS";
      RowPartitionType2[RowPartitionType2["ROW_LENGTHS"] = 2] = "ROW_LENGTHS";
      RowPartitionType2[RowPartitionType2["ROW_SPLITS"] = 3] = "ROW_SPLITS";
      RowPartitionType2[RowPartitionType2["ROW_LIMITS"] = 4] = "ROW_LIMITS";
      RowPartitionType2[RowPartitionType2["ROW_STARTS"] = 5] = "ROW_STARTS";
    })(RowPartitionType || (RowPartitionType = {}));
    var SELU_SCALEALPHA = 1.7580993408473768;
    var SELU_SCALE = 1.0507009873554805;
    function prodGradFn_(x, dy, axis) {
      const expandedYShape = x.shape.slice();
      expandedYShape[axis] = 1;
      const expandedDy = reshape(dy, expandedYShape);
      const xCumProd = cumprod(x, axis, true, false);
      const xCumRevProd = cumprod(x, axis, true, true);
      const dx = mul(xCumProd, xCumRevProd);
      return mul(expandedDy, dx);
    }
    function prodsGradFn_(x, dy, axis) {
      const xRank = x.shape.length;
      const finalProdAxis = xRank - axis.length;
      const xPermutation = getAxesPermutation(axis, xRank);
      let permutedX = x;
      if (xPermutation != null) {
        permutedX = transpose(x, xPermutation);
      }
      const newShape = permutedX.shape.slice();
      const removedShape = newShape.splice(xRank - axis.length, axis.length);
      const endPartShape = removedShape.reduce((p, c) => p * c, 1);
      newShape.push(endPartShape);
      const reshapedPermutedX = permutedX.reshape(newShape);
      let prodGrad = prodGradFn_(reshapedPermutedX, dy, finalProdAxis);
      prodGrad = prodGrad.reshape(permutedX.shape);
      if (xPermutation != null) {
        const undoPermutation = getUndoAxesPermutation(xPermutation);
        prodGrad = transpose(prodGrad, undoPermutation);
      }
      return prodGrad;
    }
    var prodGradConfig = {
      kernelName: Prod,
      inputsToSave: ["x"],
      gradFunc: (dy, saved, attrs) => {
        const [x] = saved;
        const { axis } = attrs;
        let axisArr = [];
        if (axis === void 0 || axis === null) {
          axisArr = x.shape.map((_, i) => i);
        } else if (typeof axis === "number") {
          axisArr = [axis];
        } else {
          axisArr = axis;
        }
        return { x: () => prodsGradFn_(x, dy, axisArr) };
      }
    };
    var divGradConfig = {
      kernelName: RealDiv,
      inputsToSave: ["a", "b"],
      gradFunc: (dy, saved) => {
        const [a, b] = saved;
        const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
        const derA = () => {
          const res = div(dy, cast(b, "float32"));
          const reduceAxes = getReductionAxes(a.shape, outShape);
          if (reduceAxes.length > 0) {
            return reshape(sum(res, reduceAxes), a.shape);
          }
          return res;
        };
        const derB = () => {
          let res = mul(dy, cast(a, "float32"));
          const reduceAxes = getReductionAxes(b.shape, outShape);
          if (reduceAxes.length > 0) {
            res = reshape(sum(res, reduceAxes), b.shape);
          }
          const tmp = square(b);
          return neg(div(res, cast(tmp, "float32")));
        };
        return { a: derA, b: derB };
      }
    };
    var reciprocalGradConfig = {
      kernelName: Reciprocal,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => div(dy, neg(square(x))) };
      }
    };
    var relu6GradConfig = {
      kernelName: Relu6,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        const mask = mul(lessEqual(x, 6), step(x));
        return { x: () => mul(dy, cast(mask, "float32")) };
      }
    };
    var reluGradConfig = {
      kernelName: Relu,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => mul(dy, cast(step(x), "float32")) };
      }
    };
    var reshapeGradConfig = {
      kernelName: Reshape,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => reshape(dy, x.shape) };
      }
    };
    var resizeBilinearGradConfig = {
      kernelName: ResizeBilinear,
      inputsToSave: ["images"],
      gradFunc: (dy, saved, attrs) => {
        const [images] = saved;
        const inputs = { dy, images };
        const imagesDer = () => (
          // tslint:disable-next-line: no-unnecessary-type-assertion
          ENGINE.runKernel(ResizeBilinearGrad, inputs, attrs)
        );
        return { images: imagesDer };
      }
    };
    var resizeNearestNeighborGradConfig = {
      kernelName: ResizeNearestNeighbor,
      inputsToSave: ["images"],
      gradFunc: (dy, saved, attrs) => {
        const [images] = saved;
        const inputs = { dy, images };
        const imagesDer = () => (
          // tslint:disable-next-line: no-unnecessary-type-assertion
          ENGINE.runKernel(ResizeNearestNeighborGrad, inputs, attrs)
        );
        return { images: imagesDer };
      }
    };
    var reverseGradConfig = {
      kernelName: Reverse,
      gradFunc: (dy, saved, attrs) => {
        const { dims } = attrs;
        const axes = parseAxisParam(dims, dy.shape);
        return { x: () => reverse(dy, axes) };
      }
    };
    var roundGradConfig = {
      kernelName: Round,
      gradFunc: (dy) => {
        return { x: () => zerosLike(dy) };
      }
    };
    var rsqrtGradConfig = {
      kernelName: Rsqrt,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => neg(div(dy, mul(pow(x, 1.5), 2))) };
      }
    };
    var selectGradConfig = {
      kernelName: Select,
      inputsToSave: ["condition"],
      gradFunc: (dy, saved) => {
        const [condition] = saved;
        return {
          // TODO(julianoks): Return null for condition gradient
          // when backprop supports it.
          condition: () => cast(zerosLike(condition), "float32"),
          t: () => mul(dy, cast(condition, dy.dtype)),
          e: () => mul(dy, cast(logicalNot(condition), dy.dtype))
        };
      }
    };
    var seluGradConfig = {
      kernelName: Selu,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return {
          x: () => {
            const mask = greater(x, scalar(0));
            const scaleAlpha = scalar(SELU_SCALEALPHA);
            const scale = scalar(SELU_SCALE);
            const greaterThanZeroDer = mul(dy, scale);
            const lessEqualZeroDer = mul(mul(dy, scaleAlpha), exp(cast(x, "float32")));
            return where(mask, greaterThanZeroDer, lessEqualZeroDer);
          }
        };
      }
    };
    var sigmoidGradConfig = {
      kernelName: Sigmoid,
      outputsToSave: [true],
      gradFunc: (dy, saved) => {
        const [y] = saved;
        return { x: () => mul(dy, mul(y, sub(scalar(1), y))) };
      }
    };
    var signGradConfig = {
      kernelName: Sign,
      gradFunc: (dy) => {
        return { x: () => zerosLike(dy) };
      }
    };
    var sinGradConfig = {
      kernelName: Sin,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => mul(cos(cast(x, "float32")), dy) };
      }
    };
    var sinhGradConfig = {
      kernelName: Sinh,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => mul(cosh(cast(x, "float32")), dy) };
      }
    };
    var sliceGradConfig = {
      kernelName: Slice,
      inputsToSave: ["x"],
      gradFunc: (dy, saved, attrs) => {
        const [x] = saved;
        const { begin, size } = attrs;
        const inputShape = x.shape;
        const [begin_, size_] = parseSliceParams(x, begin, size);
        const paddings = [];
        for (let i = 0; i < dy.rank; i++) {
          paddings.push([begin_[i], inputShape[i] - begin_[i] - size_[i]]);
        }
        return { x: () => pad(dy, paddings) };
      }
    };
    var softmaxGradConfig = {
      kernelName: Softmax,
      outputsToSave: [true],
      gradFunc: (dy, saved, attrs) => {
        const [y] = saved;
        const { dim } = attrs;
        const keepDims = true;
        const dyTimesY = mul(dy, y);
        return {
          logits: () => sub(dyTimesY, mul(sum(dyTimesY, [dim], keepDims), y))
        };
      }
    };
    var softplusGradConfig = {
      kernelName: Softplus,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => mul(dy, sigmoid(x)) };
      }
    };
    var spaceToBatchNDGradConfig = {
      kernelName: SpaceToBatchND,
      gradFunc: (dy, saved, attrs) => {
        const { blockShape, paddings } = attrs;
        return { x: () => batchToSpaceND(dy, blockShape, paddings) };
      }
    };
    var splitVGradConfig = {
      kernelName: SplitV,
      gradFunc: (dy, saved, attrs) => {
        const { axis } = attrs;
        return { x: () => concat(dy, axis) };
      }
    };
    var sqrtGradConfig = {
      kernelName: Sqrt,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => div(dy, mul(sqrt(cast(x, "float32")), 2)) };
      }
    };
    var squareGradConfig = {
      kernelName: Square,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => mul(dy, mul(cast(x, "float32"), 2)) };
      }
    };
    var squaredDifferenceGradConfig = {
      kernelName: SquaredDifference,
      inputsToSave: ["a", "b"],
      gradFunc: (dy, saved) => {
        const [a, b] = saved;
        const two = scalar(2);
        const derA = () => mul(dy, mul(two, sub(a, b)));
        const derB = () => mul(dy, mul(two, sub(b, a)));
        return { a: derA, b: derB };
      }
    };
    var stepGradConfig = {
      kernelName: Step,
      gradFunc: (dy) => {
        return { x: () => zerosLike(dy) };
      }
    };
    var subGradConfig = {
      kernelName: Sub,
      inputsToSave: ["a", "b"],
      gradFunc: (dy, saved) => {
        const [a, b] = saved;
        const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
        const derA = () => {
          let res = dy;
          const reduceAxes = getReductionAxes(a.shape, outShape);
          if (reduceAxes.length > 0) {
            res = sum(res, reduceAxes);
          }
          return reshape(res, a.shape);
        };
        const derB = () => {
          let res = dy;
          const reduceAxes = getReductionAxes(b.shape, outShape);
          if (reduceAxes.length > 0) {
            res = sum(res, reduceAxes);
          }
          return reshape(neg(res), b.shape);
        };
        return { a: derA, b: derB };
      }
    };
    var sumGradConfig = {
      kernelName: Sum,
      inputsToSave: ["x"],
      gradFunc: (dy, saved, attrs) => {
        const [x] = saved;
        const expandedDyShape = x.shape.slice();
        const { axis } = attrs;
        const axes = parseAxisParam(axis, x.shape);
        axes.forEach((axis2) => {
          expandedDyShape[axis2] = 1;
        });
        const expandedDy = reshape(dy, expandedDyShape);
        const derX = mul(expandedDy, ones(x.shape, "float32"));
        return { x: () => derX };
      }
    };
    var tanGradConfig = {
      kernelName: Tan,
      inputsToSave: ["x"],
      gradFunc: (dy, saved) => {
        const [x] = saved;
        return { x: () => div(dy, square(cos(x))) };
      }
    };
    var tanhGradConfig = {
      kernelName: Tanh,
      outputsToSave: [true],
      gradFunc: (dy, saved) => {
        const [y] = saved;
        return { x: () => mul(sub(scalar(1), square(y)), dy) };
      }
    };
    var tileGradConfig = {
      kernelName: Tile,
      inputsToSave: ["x"],
      gradFunc: (dy, saved, attrs) => {
        const [x] = saved;
        const { reps } = attrs;
        const derX = () => {
          let xGrad = zerosLike(x);
          if (x.rank === 1) {
            for (let i = 0; i < reps[0]; ++i) {
              xGrad = add(xGrad, slice(dy, [i * x.shape[0]], [x.shape[0]]));
            }
          } else if (x.rank === 2) {
            for (let i = 0; i < reps[0]; ++i) {
              for (let j = 0; j < reps[1]; ++j) {
                xGrad = add(xGrad, slice(dy, [i * x.shape[0], j * x.shape[1]], [
                  x.shape[0],
                  x.shape[1]
                ]));
              }
            }
          } else if (x.rank === 3) {
            for (let i = 0; i < reps[0]; ++i) {
              for (let j = 0; j < reps[1]; ++j) {
                for (let k = 0; k < reps[2]; ++k) {
                  xGrad = add(xGrad, slice(dy, [i * x.shape[0], j * x.shape[1], k * x.shape[2]], [x.shape[0], x.shape[1], x.shape[2]]));
                }
              }
            }
          } else if (x.rank === 4) {
            for (let i = 0; i < reps[0]; ++i) {
              for (let j = 0; j < reps[1]; ++j) {
                for (let k = 0; k < reps[2]; ++k) {
                  for (let l = 0; l < reps[3]; ++l) {
                    xGrad = add(xGrad, slice(dy, [
                      i * x.shape[0],
                      j * x.shape[1],
                      k * x.shape[2],
                      l * x.shape[3]
                    ], [x.shape[0], x.shape[1], x.shape[2], x.shape[3]]));
                  }
                }
              }
            }
          } else {
            throw new Error(`Gradient for tile operation is not implemented for rank-${x.rank} tensors yet.`);
          }
          return xGrad;
        };
        return { x: derX };
      }
    };
    var transposeGradConfig = {
      kernelName: Transpose,
      gradFunc: (dy, saved, attrs) => {
        const transposeAttrs = attrs;
        const { perm } = transposeAttrs;
        const undoPerm = getUndoAxesPermutation(perm);
        return { x: () => transpose(dy, undoPerm) };
      }
    };
    var unpackGradConfig = {
      kernelName: Unpack,
      gradFunc: (dy, saved, attrs) => {
        const unpackAttrs = attrs;
        const { axis } = unpackAttrs;
        return { value: () => stack(dy, axis) };
      }
    };
    var unsortedSegmentSumGradConfig = {
      kernelName: UnsortedSegmentSum,
      inputsToSave: ["segmentIds"],
      gradFunc: (dy, saved) => {
        const [segmentIds] = saved;
        const derX = () => {
          return gatherDropNegatives(dy, segmentIds);
        };
        return { x: derX };
      }
    };
    function gatherDropNegatives(x, indices) {
      const zeroClippedIndices = maximum(indices, zerosLike(indices));
      const gathered = gather(x, zeroClippedIndices);
      let isPositive = greaterEqual(indices, scalar(0, "int32"));
      const numIters = gathered.rank - isPositive.rank;
      for (let i = 0; i < numIters; ++i) {
        isPositive = expandDims(isPositive, i + 1);
      }
      isPositive = logicalAnd(isPositive, ones(gathered.shape, "bool"));
      const zeroSlice = zerosLike(gathered);
      return where(isPositive, gathered, zeroSlice);
    }
    var zerosLikeGradConfig = {
      kernelName: ZerosLike,
      gradFunc: (dy) => {
        return { x: () => zerosLike(dy) };
      }
    };
    var gradConfigs = [
      absGradConfig,
      acosGradConfig,
      acoshGradConfig,
      addGradConfig,
      addNGradConfig,
      argMaxGradConfig,
      argMinGradConfig,
      asinGradConfig,
      asinhGradConfig,
      atan2GradConfig,
      atanGradConfig,
      atanhGradConfig,
      avgPool3DGradConfig,
      avgPoolGradConfig,
      batchMatMulGradConfig,
      batchToSpaceNDGradConfig,
      broadcastToGradConfig,
      castGradConfig,
      ceilGradConfig,
      clipByValueGradConfig,
      complexAbsGradConfig,
      concatGradConfig,
      conv2DBackpropInputGradConfig,
      conv2DGradConfig,
      conv3DGradConfig,
      cosGradConfig,
      coshGradConfig,
      cumsumGradConfig,
      depthwiseConv2dNativeGradConfig,
      dilation2dGradConfig,
      divGradConfig,
      eluGradConfig,
      erfGradConfig,
      expGradConfig,
      expandDimsGradConfig,
      expm1GradConfig,
      floorDivGradConfig,
      floorGradConfig,
      fusedBatchNormGradConfig,
      gatherGradConfig,
      greaterEqualGradConfig,
      identityGradConfig,
      isFiniteGradConfig,
      isInfGradConfig,
      isNanGradConfig,
      leakyReluGradConfig,
      log1pGradConfig,
      logGradConfig,
      logSoftmaxGradConfig,
      lrnGradConfig,
      maxGradConfig,
      maxGradConfig,
      maximumGradConfig,
      maxPool3DGradConfig,
      maxPoolGradConfig,
      meanGradConfig,
      minGradConfig,
      minimumGradConfig,
      mirrorPadGradConfig,
      modGradConfig,
      multiplyGradConfig,
      negGradConfig,
      oneHotGradConfig,
      onesLikeGradConfig,
      packGradConfig,
      padV2GradConfig,
      padV2GradConfig,
      powGradConfig,
      preluGradConfig,
      prodGradConfig,
      reciprocalGradConfig,
      relu6GradConfig,
      reluGradConfig,
      reshapeGradConfig,
      resizeBilinearGradConfig,
      resizeNearestNeighborGradConfig,
      reverseGradConfig,
      roundGradConfig,
      rsqrtGradConfig,
      selectGradConfig,
      seluGradConfig,
      sigmoidGradConfig,
      signGradConfig,
      sinGradConfig,
      sinhGradConfig,
      sliceGradConfig,
      softmaxGradConfig,
      softplusGradConfig,
      spaceToBatchNDGradConfig,
      spaceToBatchNDGradConfig,
      splitVGradConfig,
      splitVGradConfig,
      sqrtGradConfig,
      squaredDifferenceGradConfig,
      squareGradConfig,
      stepGradConfig,
      subGradConfig,
      sumGradConfig,
      tanGradConfig,
      tanhGradConfig,
      tileGradConfig,
      transposeGradConfig,
      unpackGradConfig,
      unsortedSegmentSumGradConfig,
      zerosLikeGradConfig
    ];
    for (const gradientConfig of gradConfigs) {
      registerGradient(gradientConfig);
    }
    getGlobalTensorClass().prototype.abs = function() {
      this.throwIfDisposed();
      return abs(this);
    };
    getGlobalTensorClass().prototype.acos = function() {
      this.throwIfDisposed();
      return acos(this);
    };
    getGlobalTensorClass().prototype.acosh = function() {
      this.throwIfDisposed();
      return acosh(this);
    };
    getGlobalTensorClass().prototype.add = function(b) {
      this.throwIfDisposed();
      return add(this, b);
    };
    getGlobalTensorClass().prototype.all = function(axis, keepDims) {
      this.throwIfDisposed();
      return all(this, axis, keepDims);
    };
    getGlobalTensorClass().prototype.any = function(axis, keepDims) {
      this.throwIfDisposed();
      return any(this, axis, keepDims);
    };
    getGlobalTensorClass().prototype.argMax = function(axis) {
      this.throwIfDisposed();
      return argMax(this, axis);
    };
    getGlobalTensorClass().prototype.argMin = function(axis) {
      this.throwIfDisposed();
      return argMin(this, axis);
    };
    getGlobalTensorClass().prototype.asScalar = function() {
      this.throwIfDisposed();
      assert(this.size === 1, () => "The array must have only 1 element.");
      return reshape(this, []);
    };
    getGlobalTensorClass().prototype.asType = function(dtype) {
      this.throwIfDisposed();
      return cast(this, dtype);
    };
    getGlobalTensorClass().prototype.as1D = function() {
      this.throwIfDisposed();
      return reshape(this, [this.size]);
    };
    getGlobalTensorClass().prototype.as2D = function(rows, columns) {
      this.throwIfDisposed();
      return reshape(this, [rows, columns]);
    };
    getGlobalTensorClass().prototype.as3D = function(rows, columns, depth) {
      this.throwIfDisposed();
      return reshape(this, [rows, columns, depth]);
    };
    getGlobalTensorClass().prototype.as4D = function(rows, columns, depth, depth2) {
      this.throwIfDisposed();
      return reshape(this, [rows, columns, depth, depth2]);
    };
    getGlobalTensorClass().prototype.as5D = function(rows, columns, depth, depth2, depth3) {
      this.throwIfDisposed();
      return reshape(this, [rows, columns, depth, depth2, depth3]);
    };
    getGlobalTensorClass().prototype.asin = function() {
      this.throwIfDisposed();
      return asin(this);
    };
    getGlobalTensorClass().prototype.asinh = function() {
      this.throwIfDisposed();
      return asinh(this);
    };
    getGlobalTensorClass().prototype.atan = function() {
      this.throwIfDisposed();
      return atan(this);
    };
    getGlobalTensorClass().prototype.atan2 = function(b) {
      this.throwIfDisposed();
      return atan2(this, b);
    };
    getGlobalTensorClass().prototype.atanh = function() {
      this.throwIfDisposed();
      return atanh(this);
    };
    getGlobalTensorClass().prototype.avgPool = function(filterSize, strides, pad2, dimRoundingMode) {
      this.throwIfDisposed();
      return avgPool(this, filterSize, strides, pad2, dimRoundingMode);
    };
    getGlobalTensorClass().prototype.batchToSpaceND = function(blockShape, crops) {
      this.throwIfDisposed();
      return batchToSpaceND(this, blockShape, crops);
    };
    getGlobalTensorClass().prototype.batchNorm = function(mean2, variance, offset, scale, varianceEpsilon) {
      this.throwIfDisposed();
      return batchNorm(this, mean2, variance, offset, scale, varianceEpsilon);
    };
    getGlobalTensorClass().prototype.broadcastTo = function(shape) {
      this.throwIfDisposed();
      return broadcastTo(this, shape);
    };
    getGlobalTensorClass().prototype.cast = function(dtype) {
      this.throwIfDisposed();
      return cast(this, dtype);
    };
    getGlobalTensorClass().prototype.ceil = function() {
      this.throwIfDisposed();
      return ceil(this);
    };
    getGlobalTensorClass().prototype.clipByValue = function(min2, max2) {
      this.throwIfDisposed();
      return clipByValue(this, min2, max2);
    };
    getGlobalTensorClass().prototype.concat = function(x, axis) {
      this.throwIfDisposed();
      if (x instanceof Tensor) {
        x = [x];
      }
      return concat([this, ...x], axis);
    };
    getGlobalTensorClass().prototype.conv1d = function(filter, stride, pad2, dataFormat, dilation, dimRoundingMode) {
      this.throwIfDisposed();
      return conv1d(this, filter, stride, pad2, dataFormat, dilation, dimRoundingMode);
    };
    getGlobalTensorClass().prototype.conv2dTranspose = function(filter, outputShape, strides, pad2, dimRoundingMode) {
      this.throwIfDisposed();
      return conv2dTranspose(this, filter, outputShape, strides, pad2, dimRoundingMode);
    };
    getGlobalTensorClass().prototype.conv2d = function(filter, strides, pad2, dataFormat, dilations, dimRoundingMode) {
      this.throwIfDisposed();
      return conv2d$1(this, filter, strides, pad2, dataFormat, dilations, dimRoundingMode);
    };
    getGlobalTensorClass().prototype.cos = function() {
      this.throwIfDisposed();
      return cos(this);
    };
    getGlobalTensorClass().prototype.cosh = function() {
      this.throwIfDisposed();
      return cosh(this);
    };
    getGlobalTensorClass().prototype.cumprod = function(axis, exclusive, reverse2) {
      this.throwIfDisposed();
      return cumprod(this, axis, exclusive, reverse2);
    };
    getGlobalTensorClass().prototype.cumsum = function(axis, exclusive, reverse2) {
      this.throwIfDisposed();
      return cumsum(this, axis, exclusive, reverse2);
    };
    getGlobalTensorClass().prototype.depthToSpace = function(blockSize, dataFormat) {
      this.throwIfDisposed();
      return depthToSpace(this, blockSize, dataFormat);
    };
    getGlobalTensorClass().prototype.depthwiseConv2d = function(filter, strides, pad2, dataFormat, dilations, dimRoundingMode) {
      this.throwIfDisposed();
      return depthwiseConv2d$1(this, filter, strides, pad2, dataFormat, dilations, dimRoundingMode);
    };
    getGlobalTensorClass().prototype.dilation2d = function(filter, strides, pad2, dilations, dataFormat) {
      this.throwIfDisposed();
      return dilation2d(this, filter, strides, pad2, dilations, dataFormat);
    };
    getGlobalTensorClass().prototype.divNoNan = function(b) {
      this.throwIfDisposed();
      return divNoNan(this, b);
    };
    getGlobalTensorClass().prototype.div = function(b) {
      this.throwIfDisposed();
      return div(this, b);
    };
    getGlobalTensorClass().prototype.dot = function(b) {
      this.throwIfDisposed();
      return dot(this, b);
    };
    getGlobalTensorClass().prototype.elu = function() {
      this.throwIfDisposed();
      return elu(this);
    };
    getGlobalTensorClass().prototype.equal = function(b) {
      this.throwIfDisposed();
      return equal(this, b);
    };
    getGlobalTensorClass().prototype.erf = function() {
      this.throwIfDisposed();
      return erf(this);
    };
    getGlobalTensorClass().prototype.euclideanNorm = function(axis, keepDims) {
      this.throwIfDisposed();
      return euclideanNorm(this, axis, keepDims);
    };
    getGlobalTensorClass().prototype.exp = function() {
      this.throwIfDisposed();
      return exp(this);
    };
    getGlobalTensorClass().prototype.expandDims = function(axis) {
      this.throwIfDisposed();
      return expandDims(this, axis);
    };
    getGlobalTensorClass().prototype.expm1 = function() {
      this.throwIfDisposed();
      return expm1(this);
    };
    getGlobalTensorClass().prototype.fft = function() {
      this.throwIfDisposed();
      return fft(this);
    };
    getGlobalTensorClass().prototype.flatten = function() {
      this.throwIfDisposed();
      return reshape(this, [this.size]);
    };
    getGlobalTensorClass().prototype.floor = function() {
      this.throwIfDisposed();
      return floor(this);
    };
    getGlobalTensorClass().prototype.floorDiv = function(b) {
      this.throwIfDisposed();
      return floorDiv(this, b);
    };
    getGlobalTensorClass().prototype.gather = function(indices, axis, batchDims) {
      this.throwIfDisposed();
      return gather(this, indices, axis, batchDims);
    };
    getGlobalTensorClass().prototype.greaterEqual = function(b) {
      this.throwIfDisposed();
      return greaterEqual(this, b);
    };
    getGlobalTensorClass().prototype.greater = function(b) {
      this.throwIfDisposed();
      return greater(this, b);
    };
    getGlobalTensorClass().prototype.ifft = function() {
      this.throwIfDisposed();
      return ifft(this);
    };
    getGlobalTensorClass().prototype.irfft = function() {
      this.throwIfDisposed();
      return irfft(this);
    };
    getGlobalTensorClass().prototype.isFinite = function() {
      this.throwIfDisposed();
      return isFinite$1(this);
    };
    getGlobalTensorClass().prototype.isInf = function() {
      this.throwIfDisposed();
      return isInf(this);
    };
    getGlobalTensorClass().prototype.isNaN = function() {
      this.throwIfDisposed();
      return isNaN$1(this);
    };
    getGlobalTensorClass().prototype.leakyRelu = function(alpha) {
      this.throwIfDisposed();
      return leakyRelu(this, alpha);
    };
    getGlobalTensorClass().prototype.lessEqual = function(b) {
      this.throwIfDisposed();
      return lessEqual(this, b);
    };
    getGlobalTensorClass().prototype.less = function(b) {
      this.throwIfDisposed();
      return less(this, b);
    };
    getGlobalTensorClass().prototype.localResponseNormalization = function(depthRadius, bias, alpha, beta) {
      this.throwIfDisposed();
      return localResponseNormalization(this, depthRadius, bias, alpha, beta);
    };
    getGlobalTensorClass().prototype.logSigmoid = function() {
      this.throwIfDisposed();
      return logSigmoid(this);
    };
    getGlobalTensorClass().prototype.logSoftmax = function(axis) {
      this.throwIfDisposed();
      return logSoftmax(this, axis);
    };
    getGlobalTensorClass().prototype.logSumExp = function(axis, keepDims) {
      this.throwIfDisposed();
      return logSumExp(this, axis, keepDims);
    };
    getGlobalTensorClass().prototype.log = function() {
      this.throwIfDisposed();
      return log(this);
    };
    getGlobalTensorClass().prototype.log1p = function() {
      this.throwIfDisposed();
      return log1p(this);
    };
    getGlobalTensorClass().prototype.logicalAnd = function(b) {
      this.throwIfDisposed();
      return logicalAnd(this, b);
    };
    getGlobalTensorClass().prototype.logicalNot = function() {
      this.throwIfDisposed();
      return logicalNot(this);
    };
    getGlobalTensorClass().prototype.logicalOr = function(b) {
      this.throwIfDisposed();
      return logicalOr(this, b);
    };
    getGlobalTensorClass().prototype.logicalXor = function(b) {
      this.throwIfDisposed();
      return logicalXor(this, b);
    };
    getGlobalTensorClass().prototype.matMul = function(b, transposeA, transposeB) {
      this.throwIfDisposed();
      return matMul$1(this, b, transposeA, transposeB);
    };
    getGlobalTensorClass().prototype.maxPool = function(filterSize, strides, pad2, dimRoundingMode) {
      this.throwIfDisposed();
      return maxPool(this, filterSize, strides, pad2, dimRoundingMode);
    };
    getGlobalTensorClass().prototype.max = function(axis, keepDims) {
      this.throwIfDisposed();
      return max(this, axis, keepDims);
    };
    getGlobalTensorClass().prototype.maximum = function(b) {
      this.throwIfDisposed();
      return maximum(this, b);
    };
    getGlobalTensorClass().prototype.mean = function(axis, keepDims) {
      this.throwIfDisposed();
      return mean$1(this, axis, keepDims);
    };
    getGlobalTensorClass().prototype.min = function(axis, keepDims) {
      this.throwIfDisposed();
      return min(this, axis, keepDims);
    };
    getGlobalTensorClass().prototype.minimum = function(b) {
      this.throwIfDisposed();
      return minimum(this, b);
    };
    getGlobalTensorClass().prototype.mirrorPad = function(paddings, mode) {
      this.throwIfDisposed();
      return mirrorPad(this, paddings, mode);
    };
    getGlobalTensorClass().prototype.mod = function(b) {
      this.throwIfDisposed();
      return mod(this, b);
    };
    getGlobalTensorClass().prototype.mul = function(b) {
      this.throwIfDisposed();
      return mul(this, b);
    };
    getGlobalTensorClass().prototype.neg = function() {
      this.throwIfDisposed();
      return neg(this);
    };
    getGlobalTensorClass().prototype.norm = function(ord, axis, keepDims) {
      this.throwIfDisposed();
      return norm(this, ord, axis, keepDims);
    };
    getGlobalTensorClass().prototype.notEqual = function(b) {
      this.throwIfDisposed();
      return notEqual(this, b);
    };
    getGlobalTensorClass().prototype.oneHot = function(depth, onValue = 1, offValue = 0) {
      this.throwIfDisposed();
      return oneHot(this, depth, onValue, offValue);
    };
    getGlobalTensorClass().prototype.onesLike = function() {
      this.throwIfDisposed();
      return onesLike(this);
    };
    getGlobalTensorClass().prototype.pad = function(paddings, constantValue) {
      this.throwIfDisposed();
      return pad(this, paddings, constantValue);
    };
    getGlobalTensorClass().prototype.pool = function(windowShape, poolingType, padding, dilationRate, strides, dimRoundingMode) {
      this.throwIfDisposed();
      return pool(this, windowShape, poolingType, padding, dilationRate, strides, dimRoundingMode);
    };
    getGlobalTensorClass().prototype.pow = function(exp2) {
      this.throwIfDisposed();
      return pow(this, exp2);
    };
    getGlobalTensorClass().prototype.prelu = function(alpha) {
      this.throwIfDisposed();
      return prelu(this, alpha);
    };
    getGlobalTensorClass().prototype.prod = function(axis, keepDims) {
      this.throwIfDisposed();
      return prod(this, axis, keepDims);
    };
    getGlobalTensorClass().prototype.reciprocal = function() {
      this.throwIfDisposed();
      return reciprocal(this);
    };
    getGlobalTensorClass().prototype.relu = function() {
      this.throwIfDisposed();
      return relu(this);
    };
    getGlobalTensorClass().prototype.relu6 = function() {
      this.throwIfDisposed();
      return relu6(this);
    };
    getGlobalTensorClass().prototype.reshapeAs = function(x) {
      this.throwIfDisposed();
      return reshape(this, x.shape);
    };
    getGlobalTensorClass().prototype.reshape = function(shape) {
      this.throwIfDisposed();
      return reshape(this, shape);
    };
    getGlobalTensorClass().prototype.resizeBilinear = function(newShape2D, alignCorners, halfPixelCenters) {
      this.throwIfDisposed();
      return resizeBilinear(this, newShape2D, alignCorners, halfPixelCenters);
    };
    getGlobalTensorClass().prototype.resizeNearestNeighbor = function(newShape2D, alignCorners, halfFloatCenters) {
      this.throwIfDisposed();
      return resizeNearestNeighbor(this, newShape2D, alignCorners, halfFloatCenters);
    };
    getGlobalTensorClass().prototype.reverse = function(axis) {
      this.throwIfDisposed();
      return reverse(this, axis);
    };
    getGlobalTensorClass().prototype.rfft = function() {
      this.throwIfDisposed();
      return rfft(this);
    };
    getGlobalTensorClass().prototype.round = function() {
      this.throwIfDisposed();
      return round(this);
    };
    getGlobalTensorClass().prototype.rsqrt = function() {
      this.throwIfDisposed();
      return rsqrt(this);
    };
    getGlobalTensorClass().prototype.selu = function() {
      this.throwIfDisposed();
      return selu(this);
    };
    getGlobalTensorClass().prototype.separableConv2d = function(depthwiseFilter, pointwiseFilter, strides, pad2, dilation, dataFormat) {
      this.throwIfDisposed();
      return separableConv2d(this, depthwiseFilter, pointwiseFilter, strides, pad2, dilation, dataFormat);
    };
    getGlobalTensorClass().prototype.sigmoid = function() {
      this.throwIfDisposed();
      return sigmoid(this);
    };
    getGlobalTensorClass().prototype.sign = function() {
      this.throwIfDisposed();
      return sign(this);
    };
    getGlobalTensorClass().prototype.sin = function() {
      this.throwIfDisposed();
      return sin(this);
    };
    getGlobalTensorClass().prototype.sinh = function() {
      this.throwIfDisposed();
      return sinh(this);
    };
    getGlobalTensorClass().prototype.slice = function(begin, size) {
      this.throwIfDisposed();
      return slice(this, begin, size);
    };
    getGlobalTensorClass().prototype.softmax = function(dim) {
      this.throwIfDisposed();
      return softmax(this, dim);
    };
    getGlobalTensorClass().prototype.softplus = function() {
      this.throwIfDisposed();
      return softplus(this);
    };
    getGlobalTensorClass().prototype.spaceToBatchND = function(blockShape, paddings) {
      this.throwIfDisposed();
      return spaceToBatchND(this, blockShape, paddings);
    };
    getGlobalTensorClass().prototype.split = function(numOrSizeSplits, axis) {
      this.throwIfDisposed();
      return split(this, numOrSizeSplits, axis);
    };
    getGlobalTensorClass().prototype.sqrt = function() {
      this.throwIfDisposed();
      return sqrt(this);
    };
    getGlobalTensorClass().prototype.square = function() {
      this.throwIfDisposed();
      return square(this);
    };
    getGlobalTensorClass().prototype.squaredDifference = function(b) {
      this.throwIfDisposed();
      return squaredDifference(this, b);
    };
    getGlobalTensorClass().prototype.squeeze = function(axis) {
      this.throwIfDisposed();
      return squeeze(this, axis);
    };
    getGlobalTensorClass().prototype.stack = function(x, axis) {
      this.throwIfDisposed();
      const tensorsToBeStacked = x instanceof Tensor ? [this, x] : [this, ...x];
      return stack(tensorsToBeStacked, axis);
    };
    getGlobalTensorClass().prototype.step = function(alpha) {
      this.throwIfDisposed();
      return step(this, alpha);
    };
    getGlobalTensorClass().prototype.stridedSlice = function(begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask) {
      this.throwIfDisposed();
      return stridedSlice(this, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask);
    };
    getGlobalTensorClass().prototype.sub = function(b) {
      this.throwIfDisposed();
      return sub(this, b);
    };
    getGlobalTensorClass().prototype.sum = function(axis, keepDims) {
      this.throwIfDisposed();
      return sum(this, axis, keepDims);
    };
    getGlobalTensorClass().prototype.tan = function() {
      this.throwIfDisposed();
      return tan(this);
    };
    getGlobalTensorClass().prototype.tanh = function() {
      this.throwIfDisposed();
      return tanh(this);
    };
    getGlobalTensorClass().prototype.tile = function(reps) {
      this.throwIfDisposed();
      return tile(this, reps);
    };
    getGlobalTensorClass().prototype.toBool = function() {
      this.throwIfDisposed();
      return cast(this, "bool");
    };
    getGlobalTensorClass().prototype.toFloat = function() {
      this.throwIfDisposed();
      return cast(this, "float32");
    };
    getGlobalTensorClass().prototype.toInt = function() {
      this.throwIfDisposed();
      return cast(this, "int32");
    };
    getGlobalTensorClass().prototype.topk = function(k, sorted) {
      this.throwIfDisposed();
      return topk(this, k, sorted);
    };
    getGlobalTensorClass().prototype.transpose = function(perm) {
      this.throwIfDisposed();
      return transpose(this, perm);
    };
    getGlobalTensorClass().prototype.unique = function(axis) {
      this.throwIfDisposed();
      return unique(this, axis);
    };
    getGlobalTensorClass().prototype.unsortedSegmentSum = function(segmentIds, numSegments) {
      this.throwIfDisposed();
      return unsortedSegmentSum(this, segmentIds, numSegments);
    };
    getGlobalTensorClass().prototype.unstack = function(axis) {
      this.throwIfDisposed();
      return unstack(this, axis);
    };
    getGlobalTensorClass().prototype.where = function(condition, x) {
      this.throwIfDisposed();
      return where(condition, this, x);
    };
    getGlobalTensorClass().prototype.zerosLike = function() {
      this.throwIfDisposed();
      return zerosLike(this);
    };
    var version$1 = "4.22.0";
    var version = {
      "tfjs-core": tfjsCore.version_core,
      "tfjs-backend-cpu": tfjsBackendCpu.version_cpu,
      "tfjs-backend-webgl": tfjsBackendWebgl.version_webgl,
      "tfjs-data": tfjsData.version_data,
      "tfjs-layers": tfjsLayers.version_layers,
      "tfjs-converter": tfjsConverter.version_converter,
      "tfjs": version$1
    };
    exports2.data = tfjsData__namespace;
    exports2.version = version;
    Object.keys(tfjsCore).forEach(function(k) {
      if (k !== "default" && !exports2.hasOwnProperty(k)) Object.defineProperty(exports2, k, {
        enumerable: true,
        get: function() {
          return tfjsCore[k];
        }
      });
    });
    Object.keys(tfjsLayers).forEach(function(k) {
      if (k !== "default" && !exports2.hasOwnProperty(k)) Object.defineProperty(exports2, k, {
        enumerable: true,
        get: function() {
          return tfjsLayers[k];
        }
      });
    });
    Object.keys(tfjsConverter).forEach(function(k) {
      if (k !== "default" && !exports2.hasOwnProperty(k)) Object.defineProperty(exports2, k, {
        enumerable: true,
        get: function() {
          return tfjsConverter[k];
        }
      });
    });
    Object.keys(tfjsBackendCpu).forEach(function(k) {
      if (k !== "default" && !exports2.hasOwnProperty(k)) Object.defineProperty(exports2, k, {
        enumerable: true,
        get: function() {
          return tfjsBackendCpu[k];
        }
      });
    });
    Object.keys(tfjsBackendWebgl).forEach(function(k) {
      if (k !== "default" && !exports2.hasOwnProperty(k)) Object.defineProperty(exports2, k, {
        enumerable: true,
        get: function() {
          return tfjsBackendWebgl[k];
        }
      });
    });
  }
});

// node_modules/shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/cache/incorrect-predictions.json.js
var require_incorrect_predictions_json = __commonJS({
  "node_modules/shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/cache/incorrect-predictions.json.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var incorrectPredictionsCache = {
      "\u0448\u0442\u0438\u0445": "noun",
      "\u043F\u044F\u043D\u0438\u0445": "noun",
      "\u0431\u0435\u043B\u0438\u0445": "adjective",
      "\u0431\u043E\u0440\u0437\u0438\u0445": "adjective",
      "\u043C\u0430\u043B\u0438\u0445": "adjective",
      "\u0441\u0442\u0430\u0440\u0438\u0445": "adjective",
      "\u0434\u0430\u0440\u043D\u043E\u043F\u0438\u0445": "noun",
      "\u0441\u0443\u0445\u0438\u0445": "adjective",
      "\u0447\u0435\u0440\u0435\u043C\u043D\u0438\u0445": "noun",
      "\u0441\u0438\u0440\u0438\u0445": "adjective",
      "\u043F\u043B\u043E\u0445\u0438\u0445": "adjective",
      "\u0446\u0435\u043B\u0438\u0445": "adjective",
      "\u0436\u0438\u0445": "noun",
      "\u0432\u043E\u0439\u0446\u0438\u0445": "noun",
      "\u0441\u043A\u043E\u0440\u0438\u0445": "adjective",
      "\u0431\u0443\u0440\u0438\u0445": "adjective",
      "\u0447\u0430\u043B\u0438\u0445": "adjective",
      "\u0441\u0435\u0440\u0438\u0445": "adjective",
      "\u0443\u0434\u0430\u043B\u0438\u0445": "adjective",
      "\u043A\u0430\u0440\u0438\u0445": "adjective",
      "\u0433\u0435\u043D\u0438\u0445": "noun",
      "\u043B\u0438\u0442\u0432\u0438\u0445": "noun",
      "\u043C\u0430\u0440\u0446\u0438\u0445": "noun",
      "\u0441\u0456\u0437\u0438\u0445": "adjective",
      "\u044F\u043D\u0438\u0445": "noun",
      "\u043C\u0436\u0430\u0447\u0438\u0445": "adjective",
      "\u0441\u0456\u0440\u0438\u0445": "adjective",
      "\u044F\u043D\u0431\u0438\u0445": "noun",
      "\u0431\u043E\u0434\u0440\u0438\u0445": "adjective",
      "\u0441\u0442\u0440\u0438\u0439": "noun",
      "\u0447\u043E\u0440\u0442\u043E\u0440\u0438\u0439": "noun",
      "\u044E\u0440\u0438\u0439": "adjective",
      "\u0446\u0438\u0431\u0440\u0438\u0439": "noun",
      "\u0446\u0456\u0431\u0440\u0438\u0439": "noun",
      "\u043A\u0430\u0440\u0438\u0439": "adjective",
      "\u043A\u0443\u043F\u0440\u0438\u0439": "noun",
      "\u043A\u0438\u0440\u0438\u0439": "noun",
      "\u043D\u0435\u0433\u0440\u0438\u0439": "noun",
      "\u0433\u0443\u0431\u0440\u0438\u0439": "noun",
      "\u0448\u043A\u0430\u0431\u0440\u0438\u0439": "noun",
      "\u0437\u0430\u043C\u0440\u0438\u0439": "noun",
      "\u043F\u0435\u0440\u0435\u0434\u0440\u0438\u0439": "noun",
      "\u043E\u0434\u0435\u0440\u0438\u0439": "noun",
      "\u0436\u0435\u0433\u0440\u0438\u0439": "noun",
      "\u0436\u0430\u0440\u0438\u0439": "adjective",
      "\u0437\u044E\u0431\u0440\u0438\u0439": "noun",
      "\u0441\u0435\u043C\u0435\u0440\u0438\u0439": "noun",
      "\u043B\u0438\u0439": "noun",
      "\u0431\u0438\u0439": "noun",
      "\u0440\u0438\u0439": "noun",
      "\u0432\u0438\u0439": "noun",
      "\u0448\u0438\u0439": "noun",
      "\u0432\u0430\u043B\u0438\u0439": "noun",
      "\u043A\u0440\u0430\u0439\u043D\u0456\u0439": "adjective",
      "\u043E\u0441\u0456\u043D\u043D\u0456\u0439": "adjective",
      "\u043A\u0443\u0442\u043D\u0456\u0439": "adjective",
      "\u0441\u0435\u0440\u0435\u0434\u043D\u0456\u0439": "adjective",
      "\u0433\u043E\u0440\u0456\u0448\u043D\u0456\u0439": "adjective",
      "\u0431\u0435\u0437\u0440\u043E\u0434\u043D\u0456\u0439": "adjective",
      "\u043E\u0441\u0430\u0434\u0447\u0456\u0439": "adjective",
      "\u043A\u0438\u0439": "noun",
      "\u043D\u043E\u0432\u043E\u0445\u0430\u0442\u043D\u0456\u0439": "adjective",
      "\u043E\u0447\u0435\u0440\u0435\u0442\u043D\u0456\u0439": "adjective",
      "\u0440\u0431\u0438\u0439": "noun",
      "\u0437\u0430\u043A\u0443\u0442\u043D\u0456\u0439": "adjective",
      "\u043D\u0435\u0434\u0430\u0432\u043D\u0456\u0439": "adjective",
      "\u043F\u043E\u0440\u043E\u0436\u043D\u0456\u0439": "adjective",
      "\u0431\u043E\u043A\u0438\u0439": "noun",
      "\u0432\u0447\u0435\u0440\u0430\u0448\u043D\u0456\u0439": "adjective",
      "\u043E\u0433\u043E\u0440\u043E\u0434\u043D\u0456\u0439": "adjective",
      "\u0442\u0440\u043E\u0449\u0438\u0439": "noun",
      "\u0432\u0447\u043E\u0440\u0430\u0448\u043D\u0456\u0439": "adjective",
      "\u0436\u0438\u0442\u043D\u0456\u0439": "adjective",
      "\u043D\u0438\u0436\u043D\u0456\u0439": "adjective",
      "\u0441\u0438\u043D\u0456\u0439": "adjective",
      "\u0445\u043E\u0440\u0438\u0439": "noun",
      "\u043A\u0440\u0430\u0441\u043D\u043E\u0431\u043E\u043A\u0456\u0439": "adjective",
      "\u0445\u0438\u0436\u043D\u0456\u0439": "adjective",
      "\u0437\u0430\u0431\u0440\u043E\u0434\u043D\u0456\u0439": "adjective",
      "\u043A\u0430\u043B\u044E\u0436\u043D\u0456\u0439": "adjective",
      "\u0432\u0438\u043D\u043E\u0433\u0440\u0430\u0434\u043D\u0456\u0439": "adjective",
      "\u043A\u043E\u043B\u043E\u043C\u0438\u0439": "noun",
      "\u043B\u0435\u0442\u0443\u0447\u0456\u0439": "adjective",
      "\u043F\u043E\u0437\u0434\u043D\u0456\u0439": "adjective",
      "\u0441\u0435\u0440\u0438\u0439": "noun",
      "\u043D\u0430\u0433\u043E\u0440\u043D\u0456\u0439": "adjective",
      "\u0444\u0430\u0440\u0442\u0443\u0448\u043D\u0456\u0439": "adjective",
      "\u0445\u043E\u043B\u043E\u0448\u0432\u0456\u0439": "noun",
      "\u0431\u0430\u0442\u0438\u0439": "noun",
      "\u0432\u043E\u043B\u043E\u0448\u0438\u043D\u0456\u0439": "adjective",
      "\u0436\u0438\u0440\u0438\u0439": "noun",
      "\u0437\u0430\u043C\u043E\u0436\u043D\u0456\u0439": "adjective",
      "\u043A\u043E\u0440\u043E\u0442\u043A\u0456\u0439": "adjective",
      "\u043E\u0441\u0442\u0430\u043D\u043D\u0456\u0439": "adjective",
      "\u043F\u0435\u0440\u0435\u0434\u043D\u0456\u0439": "adjective",
      "\u043F\u0456\u0434\u0434\u0443\u0431\u043D\u0456\u0439": "adjective",
      "\u043F\u0456\u0437\u043D\u0456\u0439": "adjective",
      "\u043F\u043E\u0433\u043E\u0440\u043E\u0434\u043D\u0456\u0439": "adjective",
      "\u0431\u043E\u044F\u0436\u043D\u0456\u0439": "adjective",
      "\u0441\u043C\u0438\u0439": "noun",
      "\u0437\u0430\u0434\u0432\u0456\u0440\u043D\u0456\u0439": "adjective",
      "\u043E\u0441\u0442\u0430\u0442\u043D\u0456\u0439": "adjective",
      "\u043F\u0456\u0434\u0441\u0430\u0434\u043D\u0456\u0439": "adjective",
      "\u0434\u043E\u0441\u0442\u0430\u0442\u043D\u0456\u0439": "adjective",
      "\u0437\u0438\u043C\u043D\u0456\u0439": "adjective",
      "\u0440\u044F\u0431\u043E\u0439": "adjective",
      "\u0440\u0443\u0434\u043E\u0439": "adjective",
      "\u043A\u043E\u0437\u043E\u0434\u043E\u0439": "noun",
      "\u044F\u0440\u043E\u0432\u043E\u0439": "adjective",
      "\u043A\u0440\u0438\u0432\u043E\u0439": "adjective",
      "\u0441\u0430\u0434\u043E\u0432\u043E\u0439": "adjective",
      "\u043F\u043E\u043B\u0435\u0432\u043E\u0439": "adjective",
      "\u0441\u0438\u0441\u043E\u0439": "noun",
      "\u043F\u043B\u043E\u0445\u043E\u0439": "adjective",
      "\u0441\u0443\u0445\u043E\u0439": "adjective",
      "\u0433\u0430\u0454\u0432\u043E\u0439": "adjective",
      "\u0433\u043B\u0443\u0445\u043E\u0439": "adjective",
      "\u0433\u043E\u0440\u0435\u0432\u043E\u0439": "adjective",
      "\u043A\u0443\u0442\u043E\u0432\u043E\u0439": "adjective",
      "\u043A\u043E\u043F\u0430\u043D\u043E\u0439": "adjective",
      "\u0437\u043B\u043E\u0439": "adjective",
      "\u0441\u0454\u0434\u043E\u0439": "adjective",
      "\u0431\u043B\u0430\u0433\u043E\u0439": "adjective",
      "\u0432\u043E\u0434\u043E\u0441\u0442\u043E\u0439": "noun",
      "\u043A\u043E\u0441\u043E\u0439": "adjective",
      "\u043B\u0456\u0436\u0434\u0432\u043E\u0439": "noun",
      "\u0431\u043E\u043B\u044C\u0448\u043E\u0439": "adjective",
      "\u043F\u043E\u043B\u043E\u0432\u043E\u0439": "adjective",
      "\u0447\u043E\u0440\u043D\u043E\u0439": "adjective",
      "\u043A\u043E\u0441\u043E\u0433\u043E\u0439": "adjective",
      "\u0437\u043E\u043B\u043E\u0442\u043E\u0439": "adjective",
      "\u043B\u0430\u043D\u043E\u0432\u043E\u0439": "adjective",
      "\u044F\u043B\u043E\u0432\u043E\u0439": "adjective",
      "\u0434\u043E\u0440\u043E\u0433\u043E\u0439": "adjective",
      "\u043D\u0456\u043C\u043E\u0439": "adjective",
      "\u043F\u0435\u0440\u0432\u043E\u0439": "adjective",
      "\u0440\u0443\u0441\u043E\u0439": "adjective",
      "\u0445\u0443\u0434\u043E\u0439": "adjective",
      "\u0446\u0430\u043F\u043E\u0434\u043E\u0439": "noun",
      "\u0430\u0432\u0430\u0441\u0456\u043B\u043E\u0439": "noun",
      "\u0432\u0430\u043B\u043E\u0432\u043E\u0439": "adjective",
      "\u0433\u043D\u0456\u0434\u043E\u0439": "adjective",
      "\u043C\u043E\u043B\u043E\u043A\u043E\u043F\u043E\u0439": "noun",
      "\u0437\u043E\u043B\u043E\u0442\u043E\u0431\u043E\u0439": "noun",
      "\u044F\u0440\u043A\u043E\u0432\u043E\u0439": "noun",
      "\u0430\u043C\u0456\u0445\u0430\u043B\u0430\u043A\u0456\u043E\u0439": "noun",
      "\u0441\u0435\u0434\u043E\u0439": "adjective",
      "\u043A\u0440\u0443\u0442\u043E\u0439": "adjective",
      "\u043A\u0443\u0447\u043D\u043E\u0439": "adjective",
      "\u0441\u043B\u0435\u043F\u043E\u0439": "adjective",
      "\u0434\u0443\u0440\u043D\u043E\u0439": "adjective",
      "\u043C\u043E\u043B\u043E\u0434\u043E\u0439": "adjective",
      "\u0431\u0443\u0445\u043E\u0439": "adjective",
      "\u0441\u0430\u043C\u043E\u0442\u043D\u0456\u0439": "adjective",
      "\u0431\u0456\u043B\u0430": "adjective",
      "\u0431\u0443\u0440\u0430": "adjective",
      "\u0432\u0435\u043B\u0438\u043A\u0430": "adjective",
      "\u0434\u043E\u043C\u043E\u0432\u0438\u043D\u0430": "noun",
      "\u0440\u043E\u0441\u043B\u0438\u043D\u0430": "noun",
      "\u0432\u0440\u0435\u0446\u044C\u043E\u043D\u0430": "noun",
      "\u0433\u043B\u0438\u0431\u043E\u043A\u0430": "adjective",
      "\u0432\u0438\u0441\u043E\u043A\u0430": "adjective",
      "\u0433\u043B\u0430\u0434\u043A\u0430": "adjective",
      "\u0433\u0440\u0438\u0446\u0438\u043D\u0430": "noun",
      "\u0433\u0443\u0436\u0432\u0430": "noun",
      "\u043A\u043E\u0432\u0456\u043D\u044C\u043A\u0430": "noun",
      "\u0434\u0438\u043A\u0430": "adjective",
      "\u0434\u0456\u0431\u0440\u043E\u0432\u0430": "noun",
      "\u043A\u0438\u0446\u044C\u043A\u0430": "noun",
      "\u043A\u0456\u0432\u0430": "noun",
      "\u043B\u0435\u043F\u043A\u0430": "adjective",
      "\u043E\u0441\u0442\u0440\u043E\u0432\u0435\u0440\u0445\u0430": "adjective",
      "\u043F\u0435\u0442\u0440\u0438\u043D\u0430": "noun",
      "\u043F\u0440\u0443\u0434\u043A\u0430": "adjective",
      "\u0441\u0435\u043C\u0435\u043D\u0438\u043D\u0430": "noun",
      "\u0442\u0443\u0440\u0447\u0438\u043D\u0430": "noun",
      "\u0447\u0443\u043F\u0440\u0438\u043D\u0430": "noun",
      "\u0448\u0432\u0438\u0434\u043A\u0430": "adjective",
      "\u0449\u0435\u0440\u0431\u0438\u043D\u0430": "noun",
      "\u044F\u043A\u043E\u0432\u0438\u043D\u0430": "noun",
      "\u0441\u0438\u043D\u044C\u043E\u043E\u043A\u0430": "adjective",
      "\u043A\u0440\u0438\u0432\u0430": "adjective",
      "\u0441\u043B\u0456\u043F\u0430": "adjective",
      "\u0433\u043B\u0443\u0445\u0430": "adjective",
      "\u0436\u043E\u0432\u0442\u0430": "adjective",
      "\u0434\u043E\u0431\u0440\u0430": "adjective",
      "\u0445\u043E\u0440\u043E\u0431\u0440\u0430": "adjective",
      "\u0441\u0443\u0445\u043E\u0440\u0435\u0431\u0440\u0430": "adjective",
      "\u0433\u0430\u0440\u043D\u0430": "adjective",
      "\u043C\u0430\u043B\u0430": "adjective",
      "\u0432\u0435\u0441\u043D\u0430": "noun",
      "\u0437\u043B\u0430": "adjective",
      "\u0436\u0438\u0432\u0430": "adjective",
      "\u043D\u0456\u044F\u043A\u0430": "adjective",
      "\u0446\u0456\u043B\u0430": "adjective",
      "\u043C\u043E\u043B\u043E\u0434\u0430": "adjective",
      "\u0434\u0430\u043B\u0435\u043A\u0430": "adjective",
      "\u0437\u043E\u043B\u043E\u0442\u0430": "adjective",
      "\u0436\u0432\u0430\u0432\u0430": "adjective",
      "\u0434\u043E\u0440\u043E\u0433\u0430": "adjective",
      "\u043A\u043E\u0441\u0430": "adjective",
      "\u043B\u0438\u0442\u0432\u0430": "noun",
      "\u0447\u0443\u0436\u0430": "adjective",
      "\u0442\u0435\u043F\u043B\u0430": "adjective",
      "\u0433\u0440\u0443\u0431\u0430": "adjective",
      "\u0441\u043B\u0430\u0432\u0430": "noun",
      "\u0431\u0440\u043E\u0432\u0430": "noun",
      "\u0441\u0442\u0430\u0440\u0430": "adjective",
      "\u043A\u0430\u0442\u0435\u0440\u0438\u043D\u0430": "noun",
      "\u0432\u0430\u0441\u0438\u043B\u0438\u043D\u0430": "noun",
      "\u043D\u0438\u0436\u043D\u044F": "adjective",
      "\u0445\u0443\u0434\u0430": "adjective",
      "\u043F\u0440\u043E\u0441\u0442\u0430": "adjective",
      "\u0434\u0456\u0432\u043E\u0447\u0430": "adjective",
      "\u043A\u0440\u0443\u0442\u0430": "adjective",
      "\u043C\u0435\u0442\u043A\u0430": "adjective",
      "\u0447\u043E\u0440\u043D\u0430": "adjective",
      "\u0441\u0442\u043E\u0440\u043E\u043D\u0430": "noun",
      "\u043D\u0435\u0432\u043A\u0440\u0438\u0442\u0430": "adjective",
      "\u0440\u0443\u0434\u0430": "adjective",
      "\u0442\u0435\u043C\u043D\u0430": "adjective",
      "\u043F\u0440\u043E\u044F\u0432\u0430": "noun",
      "\u0442\u0438\u0445\u0430": "adjective",
      "\u0431\u043E\u0436\u0430": "adjective",
      "\u0432\u0435\u0441\u0435\u043B\u0430": "adjective",
      "\u0431\u0430\u0431\u0438\u043D\u0430": "adjective",
      "\u0441\u0443\u0445\u0430": "adjective",
      "\u043B\u044E\u0442\u0430": "adjective",
      "\u0441\u0442\u0456\u043D\u0430": "noun",
      "\u0432\u0440\u0430\u0436\u0430": "adjective",
      "\u0445\u043E\u0440\u043E\u0448\u0430": "adjective",
      "\u043B\u0435\u0433\u043A\u0430": "adjective",
      "\u043A\u043E\u0437\u0430\u0447\u0430": "adjective",
      "\u043F\u043E\u043B\u044C\u0449\u0430": "noun",
      "\u043D\u0435\u0434\u0443\u0436\u0430": "adjective",
      "\u0440\u043E\u0437\u043B\u043E\u0433\u0430": "adjective",
      "\u0433\u0430\u0440\u044F\u0447\u0430": "adjective",
      "\u0441\u0435\u0440\u0435\u0434\u043D\u044F": "adjective",
      "\u0442\u043E\u0440\u0456\u0448\u043D\u044F": "adjective",
      "\u0441\u0438\u0442\u0430": "adjective",
      "\u0433\u043E\u0441\u0442\u0440\u0430": "adjective",
      "\u043E\u0441\u0456\u043D\u043D\u044F": "adjective",
      "\u043D\u0435\u0432\u0435\u0441\u0435\u043B\u0430": "adjective",
      "\u043C\u043E\u0441\u043A\u0432\u0430": "noun",
      "\u0448\u0438\u0440\u043E\u043A\u0430": "adjective",
      "\u043F\u043E\u043B\u043E\u0432\u0438\u043D\u0430": "noun",
      "\u0441\u0438\u043D\u044F": "adjective",
      "\u0441\u0438\u0440\u0430": "adjective",
      "\u0434\u043E\u0432\u0433\u0430": "adjective",
      "\u043A\u043E\u0440\u043E\u0442\u043A\u0430": "adjective",
      "\u043B\u0443\u043A\u0430\u0432\u0430": "adjective",
      "\u0430\u0431\u0438\u044F\u043A\u0430": "adjective",
      "\u043A\u043E\u0440\u043E\u043B\u0435\u0432\u0430": "noun",
      "\u0447\u0430\u0439\u043D\u0430": "adjective",
      "\u0441\u0456\u0440\u0430": "adjective",
      "\u0441\u0443\u0442\u0443\u043B\u0430": "adjective",
      "\u0441\u0430\u0432\u0430": "noun",
      "\u0434\u0435\u0431\u0435\u043B\u0430": "adjective",
      "\u043C\u043E\u043A\u0440\u0430": "adjective",
      "\u0443\u0431\u043E\u0433\u0430": "adjective",
      "\u0431\u0435\u0437\u0440\u0443\u043A\u0430": "adjective",
      "\u0434\u0438\u043C\u043D\u0430": "adjective",
      "\u043C\u0438\u043B\u0430": "adjective",
      "\u0431\u043E\u0441\u0430": "adjective",
      "\u0433\u043E\u043B\u0430": "adjective",
      "\u043A\u0440\u0430\u0441\u043D\u043E\u043E\u043A\u0430": "adjective",
      "\u043E\u0441\u0442\u0430\u043D\u043D\u044F": "adjective",
      "\u0434\u0435\u0441\u043D\u0430": "noun",
      "\u0436\u0438\u0442\u043D\u044F": "adjective",
      "\u0442\u0440\u0438\u0437\u043D\u0430": "noun",
      "\u0446\u0443\u043F\u043A\u0430": "adjective",
      "\u043F\u043E\u0440\u043E\u0436\u043D\u044F": "adjective",
      "\u043B\u0456\u0432\u0430": "adjective",
      "\u0441\u044C\u043E\u043C\u0430": "adjective",
      "\u0432\u043E\u0432\u043D\u0430": "noun",
      "\u0441\u043E\u0432\u0430": "noun",
      "\u0431\u0435\u043B\u0430": "adjective",
      "\u0440\u044F\u0431\u0430": "adjective",
      "\u0433\u043D\u0456\u0434\u0430": "adjective",
      "\u0433\u043E\u0436\u0430": "adjective",
      "\u043A\u0438\u0441\u043B\u0430": "adjective",
      "\u043A\u0443\u0442\u043D\u044F": "adjective",
      "\u043E\u0433\u043D\u0438\u0441\u0442\u0430": "adjective",
      "\u043C\u0443\u0434\u0440\u0430": "adjective",
      "\u0434\u0443\u0436\u0430": "adjective",
      "\u043F\u0456\u0434\u0441\u0442\u0430\u0432\u0430": "noun",
      "\u0431\u043E\u0434\u0440\u0430": "adjective",
      "\u0431\u0430\u0434\u044C\u043E\u0440\u0430": "adjective",
      "\u043A\u0440\u0438\u0432\u043E\u0445\u0438\u0436\u0430": "adjective",
      "\u043F\u0440\u0438\u0445\u043E\u0436\u0430": "adjective",
      "\u043F\u043E\u0431\u043E\u0436\u0430": "adjective",
      "\u043F\u0440\u0438\u0433\u043E\u0436\u0430": "adjective",
      "\u043F\u0435\u0442\u0440\u0443\u043D\u044C\u043A\u0430": "noun",
      "\u043A\u043E\u0432\u0438\u043D\u044C\u043A\u0430": "noun",
      "\u043A\u0438\u0448\u0438\u043D\u044C\u043A\u0430": "noun",
      "\u043A\u0440\u043E\u043F\u0438\u0432\u044F\u043D\u044C\u043A\u0430": "noun",
      "\u0437\u0435\u043B\u0435\u043D\u044C\u043A\u0430": "noun",
      "\u043B\u0430\u0431\u0443\u043D\u044C\u043A\u0430": "noun",
      "\u043C'\u044F\u043A\u0435\u043D\u044C\u043A\u0430": "adjective",
      "\u0431\u0443\u0445\u043E\u043D\u044C\u043A\u0430": "noun",
      "\u0441\u0438\u0437\u0430": "adjective",
      "\u043C\u0430\u0437\u0430": "adjective",
      "\u0431\u043B\u0430\u0437\u0430": "adjective",
      "\u0443\u043B\u0438\u043D\u0430": "adjective",
      "\u0435\u0439\u0432\u0435\u043D\u0430": "adjective",
      "\u0435\u0440\u0435\u043C\u0438\u043D\u0430": "adjective",
      "\u0435\u043D\u0430": "adjective",
      "\u043A\u043B\u044F\u0442\u0430": "adjective",
      "\u043F\u0435\u0440\u0438\u0441\u0442\u0430": "adjective",
      "\u043F\u0440\u0430\u0446\u0435\u0432\u0438\u0442\u0430": "adjective",
      "\u0441\u0432\u0456\u0436\u0430": "adjective",
      "\u0440\u0438\u0436\u0430": "adjective",
      "\u043A\u043E\u043F\u0438\u0441\u0442\u0438\u0440\u0430": "noun",
      "\u0441\u043A\u043E\u0440\u0438\u043D\u0430": "noun",
      "\u0431\u0456\u043B\u044C\u0447\u0435\u043D\u044F": "noun",
      "\u043A\u0440\u0438\u0432\u043E\u0448\u0435\u043D\u044F": "noun",
      "\u043D\u0435\u0441\u0442\u0435\u0440\u0435\u043D\u044F": "noun",
      "\u0437\u0430\u0445\u0430\u0440\u0447\u0435\u043D\u044F": "noun",
      "\u0432\u043E\u0439\u0446\u0435\u043D\u044F": "noun",
      "\u043F\u0440\u043E\u0442\u0430\u0441\u0435\u043D\u044F": "noun",
      "\u043E\u043B\u0435\u0449\u0435\u043D\u044F": "noun",
      "\u0434\u0435\u043D\u0438\u0441\u0435\u043D\u044F": "noun",
      "\u0441\u0442\u0440\u0435\u043B\u044C\u0447\u0435\u043D\u044F": "noun",
      "\u043C\u043E\u043B\u043E\u0434\u043E\u0436\u0435\u043D\u044F": "noun",
      "\u0437\u0430\u0433\u0440\u0430\u0432\u0430": "noun",
      "\u043D\u0435\u043C\u0435\u043D\u0448\u0430": "adjective",
      "\u043D\u0435\u043C\u0435\u043D\u044C\u0448\u0430": "adjective",
      "\u043C\u0435\u043D\u044C\u0448\u0430": "adjective",
      "\u043F\u0430\u0448\u0438\u0439": "noun",
      "\u043F\u0454\u0448\u0430": "adjective",
      "\u0434\u0437\u0432\u0456\u043D\u043A\u0430": "adjective",
      "\u043F\u0443\u0445\u043A\u0430": "adjective",
      "\u0431\u0435\u0437\u043F\u0430\u043B\u0430": "adjective",
      "\u0432\u043E\u0431\u043B\u0430": "adjective",
      "\u0433\u043E\u0440\u0436\u0430": "adjective",
      "\u0433\u043E\u0440\u0456\u043B\u0430": "adjective",
      "\u043A\u0438\u0442\u0430\u0441\u0442\u0430": "adjective",
      "\u043B\u0438\u0441\u0430": "adjective",
      "\u043E\u0441\u0430\u0434\u0447\u0430": "adjective",
      "\u043F\u0435\u043B\u0435\u0445\u0430\u0442\u0430": "adjective",
      "\u043F\u0456\u0434\u043F\u0430\u043B\u0430": "adjective",
      "\u0441\u0442\u0430\u0432\u043D\u0438\u0447\u0430": "adjective",
      "\u0447\u0430\u043B\u0430": "adjective",
      "\u0447\u0443\u0431\u0430\u0442\u0430": "adjective",
      "\u0446\u0435\u043B\u043E\u043C\u0443\u0434\u0440\u0430": "adjective",
      "\u043A\u0430\u0440\u0430": "adjective",
      "\u043A\u043E\u0446\u0443\u043F\u0430\u0442\u0440\u0430": "adjective",
      "\u043D\u0435\u043C\u0443\u0434\u0440\u0430": "adjective",
      "\u0448\u0430\u0440\u0430": "adjective",
      "\u0448\u0438\u043D\u0433\u0438\u0440\u0430": "adjective",
      "\u043F\u0435\u0440\u0435\u0434\u0435\u0440\u0430": "adjective",
      "\u0434\u0430\u043B\u0435\u043A\u043E\u0440\u0430": "adjective",
      "\u0436\u0430\u0440\u0430": "adjective",
      "\u044F\u0440\u0430": "adjective",
      "\u0437\u043E\u043B\u043E\u0442\u043E\u043F\u0435\u0440\u0430": "adjective",
      "\u043E\u0441\u0442\u0440\u0430": "adjective",
      "\u0445\u0438\u0442\u0440\u0430": "adjective",
      "\u043F\u0440\u043E\u0437\u043E\u0440\u0430": "adjective",
      "\u043A\u0430\u0440\u0447\u0438\u043D\u0441\u043A\u0430": "adjective",
      "\u0433\u043D\u0438\u043B\u0430": "adjective",
      "\u0445\u0438\u0436\u0430": "adjective",
      "\u043A\u0440\u0438\u0436\u0430": "adjective",
      "\u043F\u043E\u0433\u043E\u0440\u0456\u043B\u0430": "adjective",
      "\u043A\u0443\u0446\u0430": "adjective",
      "\u0441\u043E\u043B\u043E\u0434\u043A\u0430": "adjective",
      "\u0431\u0435\u0437\u0432\u0435\u0440\u0445\u0430": "adjective",
      "\u0443\u0441\u0430\u0442\u0430": "adjective",
      "\u0434\u043E\u0432\u0433\u043E\u043F\u043E\u043B\u0430": "adjective",
      "\u0449\u0435\u0440\u0431\u0430\u0442\u0430": "adjective",
      "\u043F\u0438\u0448\u043D\u0430": "adjective",
      "\u0445\u043E\u0440\u0443\u0436\u0430": "adjective",
      "\u043C\u0438\u0440\u043D\u0430": "adjective",
      "\u0434\u043E\u043B\u0433\u0430": "adjective",
      "\u0431\u0454\u043B\u0430": "adjective",
      "\u043D\u0430\u0434\u0442\u043E\u0447\u0430": "adjective",
      "\u0433\u0430\u0440\u043A\u0430\u0432\u0430": "adjective",
      "\u043C\u044F\u0433\u043A\u0430": "adjective",
      "\u0442\u043E\u043F\u0447\u0430": "adjective",
      "\u0442\u043E\u0432\u0441\u0442\u0430": "adjective",
      "\u0431\u043B\u0430\u0433\u0430": "adjective",
      "\u0437\u0430\u0445\u043E\u0436\u0430": "adjective",
      "\u0431\u043E\u043B\u0456\u043B\u0430": "adjective",
      "\u0431\u0430\u0441\u0438\u0441\u0442\u0430": "adjective",
      "\u0431\u0430\u0441\u0456\u0441\u0442\u0430": "adjective",
      "\u043B\u044E\u0431\u0430": "adjective",
      "\u0433\u043E\u0440\u0431\u0430\u0442\u0430": "adjective",
      "\u0434\u0440\u0430\u043D\u0430": "adjective",
      "\u043A\u0443\u0440\u044F\u0447\u0430": "adjective",
      "\u043A\u0443\u0441\u0430": "adjective",
      "\u0437\u0430\u0439\u0432\u0430": "adjective",
      "\u043A\u0440\u0443\u0433\u043B\u0430": "adjective",
      "\u0431\u0440\u0438\u0436\u0430\u0442\u0430": "adjective",
      "\u0441\u043A\u043E\u0440\u0430": "adjective",
      "\u043F\u043B\u043E\u0445\u0430": "adjective",
      "\u0433\u043E\u0440\u044F\u0447\u0430": "adjective",
      "\u0442\u0432\u0435\u0440\u0434\u0430": "adjective",
      "\u043D\u0435\u0432\u0456\u0434\u043E\u043C\u0430": "adjective",
      "\u043A\u0430\u0440\u0442\u0430\u0432\u0430": "adjective",
      "\u0433\u043E\u0440\u043D\u0430": "adjective",
      "\u0447\u0435\u0440\u043D\u0430": "adjective",
      "\u0433\u0443\u0440\u0436\u0430": "adjective",
      "\u0433\u0438\u043A\u0430\u0432\u0430": "adjective",
      "\u0448\u0438\u0442\u0430": "adjective",
      "\u0441\u0454\u0440\u0430": "adjective",
      "\u0441\u0456\u0434\u0430": "adjective",
      "\u0433\u043D\u0443\u0447\u0430": "adjective",
      "\u0441\u043B\u0438\u0437\u044C\u043A\u0430": "adjective",
      "\u0431\u0438\u0441\u0442\u0440\u0430": "adjective",
      "\u043F\u043E\u043B\u0435\u0432\u0430": "adjective",
      "\u043F\u0430\u0440\u0443\u0431\u043E\u0447\u0430": "adjective",
      "\u0432\u0456\u0431\u043B\u0430": "adjective",
      "\u043C\u0430\u0437\u043D\u0430": "adjective",
      "\u0432\u043E\u043B\u043E\u0445\u0430\u0442\u0430": "adjective",
      "\u0448\u0430\u043B\u0435\u043D\u0430": "adjective",
      "\u0449\u0438\u0440\u0430": "adjective",
      "\u0441\u043B\u0430\u0431\u0430": "adjective",
      "\u0441\u0443\u043A\u043E\u0432\u0430\u0442\u0430": "adjective",
      "\u043D\u0438\u0449\u0430": "adjective",
      "\u043E\u0434\u0438\u043D\u043E\u043A\u0430": "adjective",
      "\u0441\u044F\u0434\u0440\u0438\u0441\u0442\u0430": "adjective",
      "\u044F\u0448\u043D\u0430": "adjective",
      "\u0440\u0430\u043A\u043E\u0447\u0430": "adjective",
      "\u0433\u0443\u0431\u0430\u0442\u0430": "adjective",
      "\u043B\u0435\u0442\u0443\u0447\u0430": "adjective",
      "\u043F\u0430\u0442\u043B\u0430\u0442\u0430": "adjective",
      "\u0432\u044F\u043B\u0430": "adjective",
      "\u0433\u0456\u0440\u043D\u0430": "adjective",
      "\u043A\u0456\u043F\u0442\u0456\u043B\u0430": "adjective",
      "\u043A\u0440\u0438\u0432\u043E\u0432\u044F\u0437\u0430": "adjective",
      "\u043B\u0438\u0445\u0430": "adjective",
      "\u043F\u043E\u0434\u0443\u0444\u0430\u043B\u0430": "adjective",
      "\u0431\u0443\u0439\u043D\u0430": "adjective",
      "\u0437\u0430\u0439\u0448\u043B\u0430": "adjective",
      "\u043A\u0443\u043F\u0440\u0430\u0442\u0430": "adjective",
      "\u043C\u0435\u0440\u0437\u043B\u0430": "adjective",
      "\u0432\u0430\u0440\u0433\u0430\u0442\u0430": "adjective",
      "\u0433\u043E\u0440\u0434\u0430": "adjective",
      "\u0434\u0440\u0430\u043F\u0430\u0442\u0430": "adjective",
      "\u0437\u0430\u0433\u0440\u0438\u0437\u043B\u0430": "adjective",
      "\u043A\u0438\u0447\u0430\u0442\u0430": "adjective",
      "\u043E\u043A\u043E\u0432\u0438\u0442\u0430": "adjective",
      "\u0442\u043B\u0443\u0441\u0442\u0430": "adjective",
      "\u0442\u043E\u043D\u043A\u0430": "adjective",
      "\u043A\u043E\u043F\u0442\u0456\u043B\u0430": "adjective",
      "\u043F\u043E\u0433\u043E\u0436\u0430": "adjective",
      "\u0442\u043E\u0432\u0441\u0442\u043E\u043A\u043E\u0440\u0430": "adjective",
      "\u0433\u043B\u0430\u0434\u0435\u043D\u044C\u043A\u0430": "adjective",
      "\u0433\u043B\u0443\u0431\u043E\u043A\u0430": "adjective",
      "\u043F\u0435\u0440\u0456\u0441\u0442\u0430": "adjective",
      "\u0432\u0438\u043A\u043E\u043D\u0430\u0432\u0447\u0430": "adjective",
      "\u043A\u043E\u0445\u0430\u043D\u0430": "adjective",
      "\u043A\u0440\u0438\u0437\u044C\u043A\u0430": "adjective",
      "\u043D\u0456\u043C\u0430": "adjective",
      "\u0440\u043E\u0441\u043B\u0430": "adjective",
      "\u043D\u0435\u043A\u0438\u043F\u0456\u043B\u0430": "adjective",
      "\u043F\u043B\u0430\u043A\u0443\u0449\u0430": "adjective",
      "\u043F\u043E\u0445\u0438\u043B\u0430": "adjective",
      "\u0441\u0442\u0440\u043E\u0433\u0430": "adjective",
      "\u0431\u043E\u0433\u0430\u0442\u0430": "adjective",
      "\u0437\u0430\u043B\u0438\u0432\u0447\u0430": "adjective",
      "\u043A\u0440\u0430\u043C\u043D\u0430": "adjective",
      "\u043F\u043E\u0441\u0442\u0430\u0432\u043D\u0438\u0447\u0430": "adjective",
      "\u0431\u0435\u0437\u0443\u0441\u0430": "adjective",
      "\u043F\u043B\u043E\u0441\u043A\u0430": "adjective",
      "\u0441\u0435\u0440\u0433\u0430\u0442\u0430": "adjective",
      "\u0441\u0443\u0445\u043E\u0442\u0435\u043F\u043B\u0430": "adjective",
      "\u0442\u043E\u043B\u0441\u0442\u0430": "adjective",
      "\u0448\u0430\u0440\u043F\u0430\u0442\u0430": "adjective",
      "\u0431\u0435\u0437\u0440\u0435\u0431\u0440\u0430": "adjective",
      "\u0434\u0443\u0448\u043D\u0430": "adjective",
      "\u0437\u043C\u0435\u0440\u0437\u043B\u0430": "adjective",
      "\u0437\u043E\u043B\u043E\u0442\u043E\u0432\u0435\u0440\u0445\u0430": "adjective",
      "\u043D\u0430\u0442\u043E\u0447\u0430": "adjective",
      "\u043F\u043E\u043B\u043E\u0436\u0430": "adjective",
      "\u0440\u043E\u043A\u043E\u0447\u0430": "adjective",
      "\u0433\u043E\u0440\u043B\u0430\u0442\u0430": "adjective",
      "\u0441\u043A\u0443\u043F\u0430": "adjective",
      "\u0431\u0456\u0431\u043B\u0430": "adjective",
      "\u0456\u043B\u044C\u043D\u0456\u0446\u043A\u0430": "adjective",
      "\u0440\u043E\u0433\u043E\u0447\u0430": "adjective",
      "\u0441\u043C\u0456\u043B\u0430": "adjective",
      "\u0449\u0435\u0434\u0440\u0430": "adjective",
      "\u0431\u0435\u0437\u043A\u043B\u0443\u0431\u0430": "adjective",
      "\u0431\u0456\u043B\u043E\u043E\u043A\u0430": "adjective",
      "\u0448\u0435\u0440\u0441\u0442\u043A\u0430": "adjective",
      "\u0431\u0435\u0437\u043A\u0438\u0448\u043A\u0430": "adjective",
      "\u043B\u0435\u0442\u044E\u0447\u0430": "adjective",
      "\u043B\u043E\u0432\u0447\u0430": "adjective",
      "\u043F\u0456\u0448\u0430": "adjective",
      "\u0440\u0430\u0431\u0430": "adjective",
      "\u0441\u0443\u0445\u043E\u0432\u0435\u0440\u0445\u0430": "adjective",
      "\u0442\u044F\u0433\u043B\u0430": "adjective",
      "\u0448\u0430\u0431\u043B\u0438\u0441\u0442\u0430": "adjective",
      "\u0448\u0443\u0431\u0430\u043B\u0430": "adjective",
      "\u0431\u0435\u0434\u0440\u0430\u0442\u0430": "adjective",
      "\u0432\u0435\u0440\u043B\u0430\u0442\u0430": "adjective",
      "\u0433\u0430\u043B\u0438\u0447\u0430": "adjective",
      "\u0437\u0430\u043F\u0443\u0445\u043B\u0430": "adjective",
      "\u0437\u0443\u0431\u0430\u0442\u0430": "adjective",
      "\u043A\u0443\u043D\u0442\u0430": "adjective",
      "\u043D\u0435\u043A\u0440\u0438\u0442\u0430": "adjective",
      "\u043F\u0430\u0445\u0443\u0447\u0430": "adjective",
      "\u0442\u0435\u043B\u044F\u0447\u0430": "adjective",
      "\u0448\u043F\u0430\u0440\u043A\u0430": "adjective",
      "\u0433\u043B\u0438\u0432\u0430": "adjective",
      "\u043A\u043E\u0441\u0430\u0442\u0430": "adjective",
      "\u043B\u044E\u0431\u0438\u043C\u0430": "adjective",
      "\u043D\u0438\u0437\u044C\u043A\u0430": "adjective",
      "\u043E\u043A\u0440\u0435\u043F\u043A\u0430": "adjective",
      "\u0440\u043E\u0431\u043E\u0447\u0430": "adjective",
      "\u0441\u043B\u0438\u0437\u044C\u043A\u043E\u0443\u0445\u0430": "adjective",
      "\u0445\u0440\u043E\u043F\u0430\u0442\u0430": "adjective",
      "\u0446\u0456\u0432\u0430\u0442\u0430": "adjective",
      "\u0448\u0438\u044F\u0442\u0430": "adjective",
      "\u0431\u0435\u0437\u0431\u043E\u0440\u043E\u0434\u0430": "adjective",
      "\u0433\u043E\u043B\u043E\u0431\u043E\u0440\u043E\u0434\u0430": "adjective",
      "\u0433\u043E\u043B\u043E\u043C\u043E\u0437\u0430": "adjective",
      "\u0433\u043E\u0440\u0454\u043B\u0430": "adjective",
      "\u0454\u0436\u0435\u043B\u0430": "adjective",
      "\u043A\u0430\u043B\u0438\u0441\u0442\u0430": "adjective",
      "\u043A\u043E\u0440\u0447\u0438\u0441\u0442\u0430": "adjective",
      "\u043A\u0443\u0440\u043D\u0430": "adjective",
      "\u043D\u0430\u0434\u0443\u0442\u0430": "adjective",
      "\u043F\u0456\u043A\u0443\u0449\u0430": "adjective",
      "\u043F\u043E\u0433\u043E\u0440\u0435\u043B\u0430": "adjective",
      "\u0441\u0430\u0432\u0456\u0446\u043A\u0430": "adjective",
      "\u0442\u0443\u043F\u0430": "adjective",
      "\u0434\u0437\u044F\u043D\u0430": "adjective",
      "\u0436\u043E\u0432\u043A\u043B\u0430": "adjective",
      "\u043A\u043E\u043B\u044E\u0447\u0430": "adjective",
      "\u043C\u0430\u0437\u0430\u043D\u0430": "adjective",
      "\u0441\u0430\u043F\u0430\u0442\u0430": "adjective",
      "\u0441\u0432\u0456\u0442\u0430": "adjective",
      "\u0441\u0443\u0445\u043E\u043B\u0438\u0442\u043A\u0430": "adjective",
      "\u0446\u0430\u0431\u0435\u0440\u044F\u0431\u0430": "adjective",
      "\u0446\u0432\u0456\u043B\u0430": "adjective",
      "\u0447\u0443\u043F\u043B\u0430": "adjective",
      "\u0430\u0441\u0430\u0434\u0447\u0430": "adjective",
      "\u0433\u0430\u0440\u0430\u0433\u0430\u0442\u0430": "adjective",
      "\u0434\u0437\u044E\u0431\u0430\u0442\u0430": "adjective",
      "\u0434\u043E\u043B\u0433\u043E\u043F\u043E\u043B\u0430": "adjective",
      "\u0436\u0438\u043B\u0430\u0432\u0430": "adjective",
      "\u043A\u043E\u0437\u0438\u043D\u0430": "adjective",
      "\u043A\u0440\u0435\u043F\u043A\u0430": "adjective",
      "\u043B\u0430\u0441\u0430": "adjective",
      "\u043B\u0438\u0447\u043A\u0430\u0442\u0430": "adjective",
      "\u043B\u043E\u0431\u0430\u0442\u0430": "adjective",
      "\u043B\u044C\u043E\u0433\u043A\u0430": "adjective",
      "\u043C\u0438\u0448\u0430\u0441\u0442\u0430": "adjective",
      "\u043D\u0435\u0432\u043C\u0438\u0442\u0430": "adjective",
      "\u043F\u0435\u0440\u043A\u0430\u0442\u0430": "adjective",
      "\u0440\u0456\u0434\u043A\u0430": "adjective",
      "\u0441\u0430\u043F\u043B\u0438\u0432\u0430": "adjective",
      "\u0442\u043E\u043D\u043A\u043E\u0448\u043A\u0443\u0440\u0430": "adjective",
      "\u0446\u0435\u043F\u043B\u0430": "adjective",
      "\u0431\u0435\u0437\u0437\u0443\u0431\u0430": "adjective",
      "\u0431\u0443\u0448\u043D\u0430": "adjective",
      "\u0431\u044F\u043B\u0430": "adjective",
      "\u043A\u0440\u0456\u043F\u043A\u0430": "adjective",
      "\u043B\u0430\u043A\u043E\u043C\u0430": "adjective",
      "\u043C\u0430\u0439\u043D\u0430": "adjective",
      "\u043D\u0430\u0433\u043B\u0430": "adjective",
      "\u043E\u0433\u043D\u0456\u0441\u0442\u0430": "adjective",
      "\u043E\u0441\u044F\u0434\u043B\u0430": "adjective",
      "\u0440\u0430\u0431\u043E\u0447\u0430": "adjective",
      "\u0440\u0430\u043F\u0430\u0432\u0430": "adjective",
      "\u0440\u043E\u0437\u043C\u0430\u0457\u0442\u0430": "adjective",
      "\u0442\u0443\u043F\u0447\u0430": "adjective",
      "\u0443\u0448\u0430\u0442\u0430": "adjective",
      "\u0447\u043E\u0440\u043D\u043E\u043E\u043A\u0430": "adjective",
      "\u0433\u0430\u043B\u044F\u043D\u0442\u0430": "adjective",
      "\u0433\u043E\u043B\u043E\u043C\u043E\u0432\u0437\u0430": "adjective",
      "\u043E\u0434\u0430\u0436\u0430": "adjective",
      "\u043E\u0440\u043B\u0430\u0442\u0430": "adjective",
      "\u043F\u0430\u0448\u0438\u0441\u0442\u0430": "adjective",
      "\u043F\u0440\u043E\u0431\u0438\u0442\u0430": "adjective",
      "\u0441\u0435\u043F\u0456\u0442\u0430": "adjective",
      "\u0441\u043B\u0430\u0431\u043A\u0430": "adjective",
      "\u0446\u0456\u043A\u0430\u0432\u0430": "adjective",
      "\u0448\u0430\u043C\u043A\u0430": "adjective",
      "\u0448\u0438\u0431\u0438\u0441\u0442\u0430": "adjective",
      "\u0431\u0430\u043B\u0456\u0446\u043A\u0430": "adjective",
      "\u0431\u0438\u0442\u0430": "adjective",
      "\u0431\u043E\u043B\u044F\u0447\u0430": "adjective",
      "\u0433\u043B\u0430\u0431\u0447\u0430\u0441\u0442\u0430": "adjective",
      "\u0433\u0443\u0441\u043B\u0456\u0441\u0442\u0430": "adjective",
      "\u0434\u0435\u043D\u044C\u0434\u043E\u0431\u0440\u0430": "adjective",
      "\u0437\u0430\u043C\u043B\u0456\u043B\u0430": "adjective",
      "\u043B\u0430\u0431\u0430\u0442\u0430": "adjective",
      "\u043C\u044F\u043A\u0430": "adjective",
      "\u043D\u0435\u0441\u043C\u0456\u043B\u0430": "adjective",
      "\u043D\u0454\u043C\u0430": "adjective",
      "\u043E\u0431\u0449\u0430": "adjective",
      "\u043E\u0434\u0430\u0439\u043D\u0430": "adjective",
      "\u043E\u043A\u0430\u0442\u0430": "adjective",
      "\u043E\u0441\u0442\u0438\u0441\u0442\u0430": "adjective",
      "\u043F\u0430\u0445\u0443\u0449\u0430": "adjective",
      "\u043F\u0441\u0442\u0440\u0430": "adjective",
      "\u0441\u043B\u0430\u0434\u043A\u0430": "adjective",
      "\u0445\u0440\u0430\u043F\u0430\u0442\u0430": "adjective",
      "\u0447\u0435\u0441\u043D\u0456\u0448\u0430": "adjective",
      "\u0447\u0443\u043B\u0430": "adjective",
      "\u0431\u0456\u0434\u043D\u043E\u0448\u0430": "adjective",
      "\u0434\u043E\u0432\u0433\u043E\u0440\u0443\u043A\u0430": "adjective",
      "\u0434\u043E\u0432\u0433\u043E\u0448\u0430": "adjective",
      "\u0456\u0432\u0430\u043D\u0456\u0446\u043A\u0430": "adjective",
      "\u043A\u043E\u0440\u043D\u0430\u0442\u0430": "adjective",
      "\u043A\u0443\u043B\u044F\u0432\u0430": "adjective",
      "\u043B\u0456\u0442\u0443\u0447\u0430": "adjective",
      "\u043C\u0430\u0440\u043D\u0430": "adjective",
      "\u043C\u0435\u0434\u0437\u0430\u0442\u0430": "adjective",
      "\u043E\u0431\u043C\u043E\u043A\u043B\u0430": "adjective",
      "\u043F\u0456\u0434\u0436\u0430\u0440\u0430": "adjective",
      "\u043F\u043E\u0431\u043E\u0447\u0430": "adjective",
      "\u0441\u0430\u0433\u0430\u0442\u0430": "adjective",
      "\u0443\u0434\u0430\u043B\u0430": "adjective",
      "\u0443\u0441\u044F\u043A\u0430": "adjective",
      "\u0431\u0430\u0439\u0434\u0443\u0436\u0430": "adjective",
      "\u0431\u0435\u0441\u043A\u043E\u0440\u0441\u0430": "adjective",
      "\u0433\u0456\u0440\u043A\u0430": "adjective",
      "\u0433\u043B\u0430\u0432\u0430\u0442\u0430": "adjective",
      "\u0433\u043E\u0440\u0447\u0430": "adjective",
      "\u0433\u043E\u0440\u044C\u043A\u0430": "adjective",
      "\u0434\u043E\u0431\u0440\u043E\u0432\u043E\u043B\u044C\u0441\u043A\u0430": "adjective",
      "\u0434\u043E\u0432\u0433\u043E\u043F\u0442\u0430": "adjective",
      "\u0434\u043E\u0441\u0443\u0436\u0430": "adjective",
      "\u0434\u0440\u0430\u043F\u044F\u0442\u0430": "adjective",
      "\u043A\u0430\u043C\u044F\u043D\u0430": "adjective",
      "\u043A\u0430\u043F\u0440\u0430\u0432\u0430": "adjective",
      "\u043A\u0438\u0440\u0438\u0447\u0430\u0442\u0430": "adjective",
      "\u043A\u043E\u043B\u043E\u0442\u0430": "adjective",
      "\u043A\u043E\u043C\u0430\u0440\u043D\u0456\u0446\u043A\u0430": "adjective",
      "\u043B\u044E\u0437\u043D\u0430": "adjective",
      "\u043C\u043E\u043B\u043E\u0434\u0448\u0430": "adjective",
      "\u043D\u0435\u0443\u043C\u0438\u0442\u0430": "adjective",
      "\u043F\u0435\u0440\u0435\u0441\u0456\u0434\u043B\u0430": "adjective",
      "\u043F\u0456\u0434\u043B\u0430": "adjective",
      "\u043F\u0443\u0445\u043B\u0430": "adjective",
      "\u0441\u0435\u043C\u044F\u043D\u0438\u0441\u0442\u0430": "adjective",
      "\u0441\u0456\u0440\u043E\u043E\u043A\u0430": "adjective",
      "\u0441\u0442\u0440\u044F\u043F\u0447\u0430": "adjective",
      "\u0442\u0432\u0435\u0440\u0435\u0437\u0430": "adjective",
      "\u0446\u0438\u0431\u0443\u043B\u044C\u0441\u043A\u0430": "adjective",
      "\u0447\u0430\u0440\u043D\u0430": "adjective",
      "\u044F\u0440\u043A\u0430": "adjective",
      "\u0431\u0435\u0437\u0433\u0443\u0431\u0430": "adjective",
      "\u0431\u0456\u043B\u043E\u0431\u043E\u0440\u043E\u0434\u0430": "adjective",
      "\u0431\u043E\u043B\u0454\u043B\u0430": "adjective",
      "\u0431\u0440\u043E\u0432\u0430\u0442\u0430": "adjective",
      "\u0433\u0456\u043A\u0430\u0432\u0430": "adjective",
      "\u0433\u043E\u043B\u043E\u0431\u043E\u043A\u0430": "adjective",
      "\u0434\u0440\u0430\u0431\u0430\u0442\u0430": "adjective",
      "\u0436\u0430\u0440\u043A\u0430": "adjective",
      "\u043A\u0430\u043F\u043B\u0430\u0442\u0430": "adjective",
      "\u043A\u0456\u0441\u043B\u0430": "adjective",
      "\u043A\u043E\u0432\u0430\u043B\u0435\u0432\u0441\u043A\u0430": "adjective",
      "\u043A\u043E\u0432\u0430\u043B\u044C\u0441\u043A\u0430": "adjective",
      "\u043A\u043E\u0437\u043B\u043E\u0432\u0441\u043A\u0430": "adjective",
      "\u043A\u0440\u0438\u043B\u0430\u0442\u0430": "adjective",
      "\u043A\u0443\u0446\u043A\u0430": "adjective",
      "\u043C\u0430\u043B\u043E\u043E\u043A\u0430": "adjective",
      "\u043C\u0433\u043A\u0430": "adjective",
      "\u043D\u0435\u043C\u044F\u0442\u0430": "adjective",
      "\u043D\u0435\u043F\u0440\u043E\u0441\u0442\u0430": "adjective",
      "\u043D\u0435\u0445\u043E\u0440\u043E\u0448\u0430": "adjective",
      "\u043F\u0435\u043B\u0438\u0445\u0430\u0442\u0430": "adjective",
      "\u043F\u0456\u0434\u043B\u0430\u0441\u0430": "adjective",
      "\u043F\u043E\u0434\u043F\u0430\u043B\u0430": "adjective",
      "\u0440\u0443\u0446\u043A\u0430": "adjective",
      "\u0441\u0435\u043C\u0435\u043D\u0438\u0441\u0442\u0430": "adjective",
      "\u0443\u0441\u043B\u0438\u0441\u0442\u0430": "adjective",
      "\u0448\u043E\u0440\u0441\u0442\u043A\u0430": "adjective",
      "\u0445\u0438\u043B\u0430": "adjective",
      "\u0431\u0443\u043A\u0430\u0442\u0430": "adjective",
      "\u0432\u0430\u0441\u0430\u043B\u0430\u0442\u0430": "adjective",
      "\u0432\u0438\u0431\u043B\u0430": "adjective",
      "\u0432\u0438\u0434\u043E\u0439\u043D\u0430": "adjective",
      "\u0432\u0438\u043B\u043E\u0432\u0430\u0442\u0430": "adjective",
      "\u0433\u0430\u0440\u0447\u0430": "adjective",
      "\u0433\u043E\u0440\u0435\u043B\u0430": "adjective",
      "\u0434\u0443\u0442\u0430": "adjective",
      "\u0437\u0438\u0431\u043B\u0430": "adjective",
      "\u0456\u043D\u0434\u0438\u0447\u0430": "adjective",
      "\u043A\u0430\u043B\u044C\u043D\u043E\u043E\u043A\u0430": "adjective",
      "\u043A\u0430\u0440\u043D\u0430\u0443\u0445\u0430": "adjective",
      "\u043A\u0440\u0438\u0432\u043E\u0431\u0435\u0434\u0440\u0430": "adjective",
      "\u043A\u0440\u0438\u0447\u0444\u0430\u043B\u0443\u0448\u0430": "adjective",
      "\u043A\u0443\u0431\u0430\u0442\u0430": "adjective",
      "\u043A\u0443\u0436\u0434\u0430": "adjective",
      "\u043B\u043E\u043C\u0430\u043D\u0430": "adjective",
      "\u043C\u0430\u0446\u0435\u0432\u0438\u0442\u0430": "adjective",
      "\u0456\u0432\u0430\u0448\u0438\u043D\u0430": "noun",
      "\u0441\u043E\u043B\u043E\u0445\u0430": "adjective",
      "\u043F\u0435\u0440\u0435\u0440\u0432\u0430": "noun",
      "\u043F\u0440\u043E\u0441\u043A\u0443\u0440\u0430": "adjective",
      "\u0431\u043E\u0432\u0430": "noun",
      "\u0441\u043C\u0435\u0442\u0430\u043D\u0430": "noun",
      "\u0434\u0443\u0431\u0440\u043E\u0432\u0430": "noun",
      "\u043F\u0440\u043E\u0441\u043A\u0443\u0440\u043D\u044F": "noun",
      "\u0440\u043E\u0434\u0456\u043D\u0430": "noun",
      "\u0454\u043D\u0430": "noun",
      "\u0441\u043E\u043B\u043E\u043D\u0438\u043D\u0430": "noun",
      "\u043B\u0456\u0449\u0438\u043D\u0430": "noun",
      "\u043B\u0443\u0433\u0438\u043D\u0430": "adjective",
      "\u0441\u043E\u0441\u043D\u0430": "noun",
      "\u0433\u0430\u0432\u0432\u0430": "noun",
      "\u0443\u0436\u0432\u0430": "noun",
      "\u043A\u0443\u043B\u0438\u043D\u0430": "adjective",
      "\u0445\u0430\u043B\u044F\u0432\u0430": "noun",
      "\u0445\u043E\u043B\u044F\u0432\u0430": "noun",
      "\u043F\u0456\u0434\u043A\u043E\u0432\u0430": "noun",
      "\u043A\u0440\u0430\u0439\u043D\u044F": "adjective",
      "\u0445\u043E\u0445\u043E\u0442\u0432\u0430": "noun",
      "\u0446\u0438\u0431\u0443\u043B\u044C\u043A\u0430": "noun",
      "\u043D\u0456\u043A\u0443\u043B\u044C\u0447\u0430": "noun",
      "\u043A\u0440\u0430\u0432\u0447\u0438\u043D\u0430": "noun",
      "\u043B\u0443\u043F\u0438\u043D\u0430": "adjective",
      "\u043B\u0438\u0445\u043E\u0448\u0432\u0430": "noun",
      "\u0434\u0443\u043C\u0431\u0440\u0430\u0432\u0430": "noun",
      "\u043F\u043B\u0430\u0445\u043E\u0442\u043D\u044F": "adjective",
      "\u043F\u043E\u043A\u0443\u0442\u043D\u044F": "adjective",
      "\u043F\u043E\u043D\u0430": "noun",
      "\u0441\u0435\u043C\u0435\u043D\u0430": "noun",
      "\u0433\u0440\u043E\u043D\u0430": "noun",
      "\u0454\u0432\u0430": "noun",
      "\u043F\u0430\u0440\u0430\u0441\u043A\u0456\u0432\u0430": "noun",
      "\u0448\u043E\u0432\u0430": "noun",
      "\u0431\u0443\u0440\u0434\u0443\u0436\u0430": "adjective",
      "\u043A\u043E\u0437\u044E\u0431\u0435\u0440\u0434\u0430": "adjective",
      "\u0433\u043E\u0432\u0442\u0432\u0430": "noun",
      "\u043F\u0440\u0438\u043A\u043E\u043B\u043E\u0442\u0430": "adjective",
      "\u0432\u0430\u0440\u043D\u0430\u0432\u0430": "noun",
      "\u0433\u0443\u0440\u0438\u043D\u0430": "adjective",
      "\u0440\u044F\u0431\u043E\u043A\u043E\u0431\u0438\u043B\u0430": "noun",
      "\u043A\u0443\u0447\u0438\u043D\u0430": "adjective",
      "\u0441\u0430\u0432\u0432\u0430": "noun",
      "\u043A\u0440\u0435\u043C\u0435\u043D\u0430": "noun",
      "\u043C\u0430\u043B\u0430\u044F": "adjective",
      "\u0433\u043E\u0440\u0456\u0448\u043D\u044F": "adjective",
      "\u0431\u0443\u0440\u0434\u044E\u0436\u0430": "adjective",
      "\u0441\u043B\u0430\u043A\u0432\u0430": "noun",
      "\u0433\u043E\u0440\u043E\u0434\u043D\u044F": "adjective",
      "\u043B\u0438\u0448\u0442\u0432\u0430": "noun",
      "\u0446\u044F\u0446\u044C\u043A\u0430": "noun",
      "\u043F\u043E\u0445\u043E\u0434\u043D\u044F": "noun",
      "\u043D\u0435\u0434\u0430\u0432\u043D\u044F": "adjective",
      "\u0434\u043E\u043B\u0456\u0448\u043D\u044F": "adjective",
      "\u043C\u0430\u0440\u044E\u0445\u043D\u0430": "noun",
      "\u0431\u043E\u0440\u043E\u043D\u0430": "noun",
      "\u043A\u043E\u043B\u043E\u0448\u0432\u0430": "noun",
      "\u0441\u0435\u043C\u0435\u043D\u0447\u0430": "noun",
      "\u0437\u0430\u0442\u043E\u043D\u0430": "noun",
      "\u0437\u0430\u043F\u043B\u0430\u0432\u0430": "noun",
      "\u043A\u0440\u0430\u0441\u043D\u043E\u043F\u0435\u0440\u0430": "adjective",
      "\u0440\u0438\u0431\u0438\u0442\u0432\u0430": "noun",
      "\u0441\u0438\u0434\u043E\u0440\u0430": "adjective",
      "\u043A\u0440\u0430\u043F\u043B\u0438\u043D\u0430": "noun",
      "\u043A\u0440\u0443\u0442\u0438\u0433\u043E\u043B\u043E\u0432\u0430": "noun",
      "\u0431\u0430\u043A\u0430\u043B\u0438\u043D\u0430": "adjective",
      "\u043D\u0435\u043C\u043D\u0430": "noun",
      "\u043E\u0447\u0435\u0440\u0435\u0442\u043D\u044F": "adjective",
      "\u043F\u0440\u043E\u0431\u0438\u0439\u0433\u043E\u043B\u043E\u0432\u0430": "noun",
      "\u043C\u0430\u043B\u044C\u043E\u043D\u0430": "noun",
      "\u0441\u0430\u0436\u0438\u043D\u0430": "adjective",
      "\u0432\u0447\u0435\u0440\u0430\u0448\u043D\u044F": "adjective",
      "\u0431\u0443\u0437\u0438\u043D\u0430": "noun",
      "\u0437\u0430\u0431\u0438\u0439\u0432\u043E\u0440\u043E\u0442\u0430": "noun",
      "\u043C\u0430\u0433\u043B\u044C\u043E\u043D\u0430": "noun",
      "\u043D\u0435\u0439\u0447\u0435\u0432\u0430": "noun",
      "\u043F\u043E\u0442\u043E\u0440\u043E\u0447\u0430": "noun",
      "\u0440\u0435\u0432\u0456\u043D\u0430": "noun",
      "\u043C\u0430\u0442\u044C\u043E\u0440\u0430": "adjective",
      "\u0441\u0432\u044F\u0442\u0438\u043D\u0430": "noun",
      "\u0445\u0456\u043D\u0430": "noun",
      "\u043A\u043E\u0436\u0438\u043D\u0430": "adjective",
      "\u043D\u0430\u0440\u0456\u0436\u043D\u044F": "noun",
      "\u043B\u0435\u043E\u043D\u0430": "noun",
      "\u043F\u0435\u0440\u0435\u0434\u043D\u044F": "adjective",
      "\u0441\u0430\u0432\u0438\u043D\u0430": "adjective",
      "\u0441\u0456\u043A\u0430\u0447\u0438\u043D\u0430": "noun",
      "\u043A\u043B\u044C\u043E\u0432\u0430": "noun",
      "\u043D\u0435\u0434\u043E\u043B\u0443\u0433\u0430": "adjective",
      "\u0448\u043A\u043E\u0440\u043E\u043F\u0430\u0442\u0430": "noun",
      "\u043A\u0430\u0440\u0430\u0441\u0430\u0432\u0430": "noun",
      "\u043C\u043E\u0440\u0435\u0432\u0430": "adjective",
      "\u043C\u0443\u0441\u0442\u0430\u0444\u0456\u043D\u0430": "noun",
      "\u0446\u044C\u043E\u0432\u0430": "noun",
      "\u0431\u0443\u0431\u043D\u0430": "noun",
      "\u043A\u0430\u0442\u043E\u043D\u0430": "noun",
      "\u043C\u0456\u043D\u0430": "noun",
      "\u043F\u043E\u0445\u0432\u0430\u043B\u0430": "noun",
      "\u0441\u043B\u043E\u043A\u0432\u0430": "noun",
      "\u0441\u0442\u0430\u0442\u0456\u0432\u0430": "noun",
      "\u0441\u0442\u0440\u043E\u043D\u0430": "noun",
      "\u0432\u043E\u0432\u0430": "noun",
      "\u043A\u0430\u0440\u0435\u0432\u0430": "adjective",
      "\u043C\u0456\u0441\u044E\u043D\u0430": "noun",
      "\u0448\u0432\u0430\u044F": "noun",
      "\u0431\u0430\u043B\u044C\u0432\u0430": "noun",
      "\u0432\u0435\u0440\u0448\u0438\u043D\u0430": "noun",
      "\u0432\u0440\u043E\u043D\u0430": "noun",
      "\u0431\u0456\u043B\u043E\u043A\u043E\u0431\u0438\u043B\u0430": "noun",
      "\u0433\u043E\u0440\u0434\u0438\u043D\u0430": "noun",
      "\u043A\u043E\u043B\u044C\u0432\u0430": "noun",
      "\u043B\u044C\u043E\u0432\u0430": "noun",
      "\u043F\u0435\u0440\u0435\u043A\u043B\u0456\u0442\u0430": "noun",
      "\u043E\u0441\u043D\u043E\u0432\u0430": "noun",
      "\u0445\u0430\u0440\u0435\u043D\u0430": "noun",
      "\u0431\u043E\u0440\u043E\u0437\u043D\u0430": "noun",
      "\u0431\u0443\u0434\u0430\u043A\u0432\u0430": "noun",
      "\u043A\u0430\u0440\u0430\u043D\u0456\u043A\u043E\u043B\u0430": "noun",
      "\u043F\u0430\u043B\u0435\u0441\u0456\u043A\u0430": "noun",
      "\u0440\u043E\u0436\u0438\u043D\u0430": "noun",
      "\u0448\u0442\u0430\u043D\u0430": "noun",
      "\u0432\u0438\u0446\u0438\u043D\u0430": "noun",
      "\u0434\u0443\u0431\u043D\u0430": "noun",
      "\u0436\u043E\u0432\u043D\u0430": "noun",
      "\u0437\u0456\u0432\u0430": "noun",
      "\u043A\u0430\u0442\u0430\u0440\u0438\u043D\u0430": "noun",
      "\u043F\u043E\u0445\u043C\u0443\u0440\u0430": "adjective",
      "\u0444\u0435\u0441\u0438\u043D\u0430": "noun",
      "\u0448\u0435\u043C\u0435\u043D\u0430": "noun",
      "\u0433\u0430\u043B\u0443\u0442\u0432\u0430": "noun",
      "\u0437\u0430\u0440\u0435\u0432\u0430": "noun",
      "\u043A\u043E\u0432\u0430\u043B\u044C\u0432\u0430": "noun",
      "\u043C\u0438\u0440\u043E\u043D\u0430": "noun",
      "\u043D\u043E\u0432\u043E\u0441\u0435\u043B\u0430": "noun",
      "\u043F\u0430\u0447\u0438\u043D\u0430": "adjective",
      "\u0441\u043E\u0432\u0432\u0430": "noun",
      "\u0433\u0456\u043D\u0430": "noun",
      "\u043A\u043E\u0440\u043E\u043D\u0430": "noun",
      "\u043D\u043E\u0432\u043E\u0436\u0435\u043D\u044F": "noun",
      "\u043F\u0456\u0434\u0431\u0435\u0440\u0435\u0437\u043D\u044F": "adjective",
      "\u0440\u044F\u0434\u043D\u0438\u043D\u0430": "noun",
      "\u0441\u0430\u043A\u0441\u044C\u043A\u0430": "noun",
      "\u043A\u0430\u043D\u043D\u0430": "noun",
      "\u043B\u0443\u043A\u0430\u0447\u0438\u043D\u0430": "noun",
      "\u043F\u043B\u0430\u0447\u0456\u043D\u0442\u0430": "noun",
      "\u0440\u0435\u0434\u044C\u043A\u0432\u0430": "noun",
      "\u0441\u043E\u0444\u0438\u043D\u0430": "adjective",
      "\u0448\u0430\u0442\u043D\u044F": "adjective",
      "\u0431\u043B\u043E\u0437\u0432\u0430": "noun",
      "\u0432\u0447\u043E\u0440\u0430\u0448\u043D\u044F": "adjective",
      "\u0433\u0440\u0438\u0446\u0435\u043D\u044F": "noun",
      "\u043A\u0443\u0440\u043E\u043F\u0430\u0442\u0432\u0430": "noun",
      "\u043B\u044E\u0434\u0432\u0430": "noun",
      "\u0441\u0442\u0435\u0445\u043D\u0430": "noun",
      "\u043F\u0430\u0440\u0430\u0445\u043E\u043D\u044F": "noun",
      "\u043F\u043B\u0454\u0432\u0430": "noun",
      "\u044F\u0432\u043E\u0440\u0438\u043D\u0430": "noun",
      "\u0431\u0435\u043D\u0434\u0438\u043D\u0430": "noun",
      "\u0436\u043E\u0432\u0442\u043E\u043D\u043E\u0433\u0430": "adjective",
      "\u043A\u043E\u043D\u0435\u0432\u0430": "adjective",
      "\u043C\u0430\u043D\u0434\u0430\u043B\u0438\u043D\u0430": "noun",
      "\u043C\u0430\u0446\u0438\u043D\u0430": "noun",
      "\u043F\u0435\u0440\u0435\u0437\u0432\u0430": "noun",
      "\u043F\u043E\u0445\u0432\u0430\u0442\u0430": "noun",
      "\u0442\u043E\u043A\u043C\u0438\u043D\u0430": "noun",
      "\u0442\u044E\u0440\u0438\u043D\u0430": "adjective",
      "\u0433\u0438\u0446\u0438\u043D\u0430": "noun",
      "\u0434\u0437\u0456\u043D\u0430": "noun",
      "\u043A\u0443\u044F\u0432\u0430": "noun",
      "\u043C\u0430\u043B\u043E\u043D\u043E\u0433\u0430": "adjective",
      "\u0441\u0442\u043E\u043A\u043E\u043B\u043E\u0441\u0430": "adjective",
      "\u0442\u0438\u043C\u0438\u043D\u0430": "adjective",
      "\u0431\u0456\u0434\u043D\u0438\u043D\u0430": "noun",
      "\u0432\u0434\u043E\u0432\u0438\u043D\u0430": "adjective",
      "\u043B\u0438\u0441\u043E\u0445\u043C\u0430\u0440\u0430": "noun",
      "\u043C\u0438\u043A\u0438\u0442\u0438\u043D\u0430": "adjective",
      "\u043F\u043E\u043B\u0456\u0432\u0430\u0440\u0430": "noun",
      "\u0440\u0438\u0431\u043E\u043D\u044C\u043A\u0430": "noun",
      "\u0440\u0443\u0436\u0438\u043D\u0430": "noun",
      "\u0442\u0438\u0448\u0438\u043D\u0430": "noun",
      "\u0446\u044E\u0440\u043C\u0430\u0441\u0442\u0430": "noun",
      "\u0447\u0430\u043B\u0430\u044F": "adjective",
      "\u0432\u0430\u0441\u0438\u043D\u0430": "noun",
      "\u0432\u043E\u0457\u043D\u0430": "noun",
      "\u0433\u0443\u043B\u0430\u044F": "noun",
      "\u043A\u043E\u0432\u0430": "noun",
      "\u043E\u043D\u0430": "noun",
      "\u043F\u0430\u043B\u0456\u0441\u0456\u043A\u0430": "noun",
      "\u043F\u0456\u0434\u043E\u0448\u0432\u0430": "noun",
      "\u0441\u0432\u0438\u0434\u0438\u043D\u0430": "noun",
      "\u0442\u0438\u0440\u0441\u0438\u043D\u0430": "noun",
      "\u0445\u0430\u0432\u0440\u043E\u043D\u0430": "noun",
      "\u0437\u043E\u043D\u0430": "noun",
      "\u043A\u043D\u0437\u0454\u0432\u0430": "noun",
      "\u0440\u043E\u0437\u043D\u0430": "adjective",
      "\u0440\u043E\u043D\u0436\u0438\u043D\u0430": "noun",
      "\u0440\u0443\u0434\u043E\u043C\u0438\u043D\u0430": "noun",
      "\u0441\u0430\u043B\u044C\u0432\u0430": "noun",
      "\u0441\u043A\u0456\u043B\u044C\u0441\u0430\u0440\u0430": "noun",
      "\u0441\u043B\u0443\u0436\u0430\u043B\u0430": "noun",
      "\u0444\u043E\u043C\u0438\u043D\u0430": "adjective",
      "\u0447\u0443\u043F\u0438\u043D\u0430": "adjective",
      "\u0448\u0430\u043B\u0443\u043F\u043D\u044F": "noun",
      "\u0434\u0436\u0443\u043F\u0438\u043D\u0430": "noun",
      "\u0437\u043E\u0441\u044C\u043A\u0430": "noun",
      "\u043A\u0443\u0437\u044F\u0432\u0430": "noun",
      "\u043D\u0435\u043B\u0435\u0434\u0432\u0430": "noun",
      "\u0440\u0430\u0432\u0432\u0430": "noun",
      "\u0440\u0430\u0437\u044C\u0432\u0430": "noun",
      "\u0448\u043A\u043E\u0440\u0438\u043D\u0430": "noun",
      "\u0431\u0456\u043B\u043E\u0437\u043E\u0440\u0430": "adjective",
      "\u0431\u0440\u0430\u043D\u0446\u0456\u0440\u0430": "noun",
      "\u0432\u0438\u043F\u043D\u0430": "noun",
      "\u0433\u0430\u043B\u0438\u043D\u0430": "adjective",
      "\u043C\u0430\u043D\u0434\u0430\u043B\u0456\u043D\u0430": "noun",
      "\u043C\u0438\u0446\u044C\u043A\u0430": "noun",
      "\u043C\u044F\u0447\u0438\u043D\u0430": "adjective",
      "\u043D\u0435\u0434\u043E\u0441\u0454\u043A\u0430": "noun",
      "\u043F\u0440\u0438\u0441\u0442\u0430\u044F": "noun",
      "\u043C'\u044F\u043A\u0430": "adjective",
      "\u0432\u043E\u0432\u0447\u0438\u043D\u0430": "noun",
      "\u0433\u0440\u0438\u043D\u044F\u0432\u0430": "noun",
      "\u0434\u0456\u0432\u043E\u043D\u044C\u043A\u0430": "noun",
      "\u0456\u0433\u0456\u043D\u0430": "noun",
      "\u043E\u0431\u0456\u0439\u0434\u0438\u0445\u0430\u0442\u0430": "noun",
      "\u0445\u0438\u0436\u043D\u044F": "adjective",
      "\u0447\u0435\u043B\u044F\u0434\u0438\u043D\u0430": "noun",
      "\u044F\u043D\u0435\u0432\u0430": "adjective",
      "\u0433\u043E\u043B\u0435\u0432\u0430": "adjective",
      "\u0434\u0437\u044E\u043D\u044C\u043A\u0430": "noun",
      "\u0434\u0443\u0431\u0440\u0430\u0432\u0430": "noun",
      "\u043B\u0438\u0433\u043E\u043C\u0438\u043D\u0430": "noun",
      "\u043C\u0430\u043B\u043D\u0430": "noun",
      "\u043C\u0430\u0440\u0445\u0435\u0432\u0430": "noun",
      "\u043D\u0435\u0441\u043F\u0440\u0430\u0432\u0430": "noun",
      "\u043E\u0437\u044F\u0432\u0430": "noun",
      "\u043F\u0430\u043D\u043D\u0430": "noun",
      "\u043F\u0443\u043F\u0435\u043D\u0430": "noun",
      "\u0441\u0438\u043B\u044F\u0432\u0430": "noun",
      "\u0441\u0443\u0445\u043E\u043A\u043E\u0431\u0438\u043B\u0430": "noun",
      "\u0446\u044E\u0440\u043C\u043E\u0441\u0442\u0430": "noun",
      "\u0447\u0435\u0432\u0435\u043B\u044C\u0447\u0430": "noun",
      "\u0447\u0456\u0432\u0456\u043B\u044C\u0447\u0430": "noun",
      "\u0431\u0430\u0448\u0435\u0432\u0430": "noun",
      "\u0431\u0440\u0430\u0436\u043D\u0430": "noun",
      "\u0432\u0430\u0440\u0430\u0432\u0432\u0430": "noun",
      "\u0432\u043E\u043B\u043D\u0430": "noun",
      "\u0433\u043E\u043B\u044C\u0447\u0430": "noun",
      "\u0433\u0443\u0441\u0442\u0430": "adjective",
      "\u0434\u043E\u0441\u0442\u0430\u0442\u043D\u044F": "adjective",
      "\u0437\u0443\u0433\u0440\u0430\u0432\u0430": "noun",
      "\u043A\u0430\u0440\u0430\u043F\u0443\u043B\u044C\u043A\u0430": "noun",
      "\u043A\u0456\u0440\u043D\u0430": "adjective",
      "\u043A\u0440\u0430\u043F\u0456\u0432\u0430": "noun",
      "\u043B\u0443\u043A\u043E\u0432\u0438\u043D\u0430": "noun",
      "\u043C\u0430\u043C\u043E\u043D\u0430": "noun",
      "\u043C\u0435\u043B\u0435\u0449\u0435\u043D\u044F": "noun",
      "\u043C\u0440\u044F\u043D\u0430": "noun",
      "\u043F\u0430\u0440\u0430\u0441\u043A\u0435\u0432\u0430": "noun",
      "\u043F\u043E\u0445\u0456\u0434\u043D\u044F": "noun",
      "\u043F\u0440\u0456\u0445\u043D\u0430": "noun",
      "\u0441\u0432\u0442\u0438\u043D\u0430": "noun",
      "\u0441\u044C\u043E\u0441\u044C\u043A\u0430": "noun",
      "\u0442\u0435\u0440\u0435\u043F\u0456\u0449\u0430": "noun",
      "\u0446\u0456\u0446\u044F\u043B\u0430": "noun",
      "\u0431\u043E\u0434\u0430\u043A\u0432\u0430": "noun",
      "\u0433\u0430\u043B\u044C\u0432\u0456\u0442\u0430": "noun",
      "\u0434\u0435\u0440\u0435\u0432\u0435\u043D\u0447\u0430": "noun",
      "\u0434\u043E\u043D\u0430": "noun",
      "\u0434\u0443\u0431\u0435\u043D\u0430": "noun",
      "\u0437\u0430\u0434\u0430\u0432\u0438\u0441\u0432\u0456\u0447\u043A\u0430": "noun",
      "\u0439\u043E\u0432\u0432\u0430": "noun",
      "\u043A\u0430\u043F\u0430\u0446\u0456\u043B\u0430": "noun",
      "\u043A\u043E\u0442\u0435\u043B\u044C\u0432\u0430": "noun",
      "\u043B\u0456\u0441\u043E\u0442\u0430": "noun",
      "\u043C\u0430\u043B\u044E\u0441\u044C\u043A\u0430": "noun",
      "\u043F\u0456\u0434\u0441\u0430\u0434\u043D\u044F": "adjective",
      "\u0440\u0454\u0432\u0430": "noun",
      "\u0441\u0443\u0432\u043E\u0440\u0430": "adjective",
      "\u0445\u0430\u0434\u0436\u0430\u0432\u0430": "noun",
      "\u0445\u043E\u043C\u0438\u043D\u0430": "adjective",
      "\u043F\u0441\u0438\u043D\u0430": "noun",
      "\u0431\u043E\u0431\u0438\u043D\u0430": "noun",
      "\u0431\u043E\u043B\u043E\u0442\u043D\u044F": "adjective",
      "\u0431\u0440\u0443\u043A\u0432\u0430": "noun",
      "\u043A\u0456\u043E\u043D\u0430": "noun",
      "\u043A\u043E\u0432\u0431\u0456\u043D\u044C\u043A\u0430": "noun",
      "\u043A\u0440\u0438\u0432\u043E\u043D\u043E\u0433\u0430": "adjective",
      "\u043B\u0454\u0432\u0430": "noun",
      "\u043C\u0443\u0445\u0438\u043D\u0430": "adjective",
      "\u043D\u0435\u0444\u043E\u0440\u0442\u0443\u043D\u0430": "noun",
      "\u043E\u0440\u0433\u0430\u043D\u0456\u0441\u0442\u0430": "noun",
      "\u043F\u0430\u0441\u0443\u043B\u044C\u043A\u0430": "noun",
      "\u043F\u0440\u0438\u0441\u0442\u0430\u0432\u0430": "noun",
      "\u0431\u0430\u0447\u0438\u043D\u0430": "noun",
      "\u0431\u0435\u0437\u043A\u043E\u0440\u0441\u0430": "adjective",
      "\u0431\u0454\u043B\u043E\u043A\u043E\u0431\u0438\u043B\u0430": "noun",
      "\u0431\u043E\u0440\u0437\u0438\u043D\u0430": "noun",
      "\u0431\u0440\u0443\u0436\u0438\u043D\u0430": "noun",
      "\u0432\u043E\u0440\u043E\u0442\u043D\u044F": "adjective",
      "\u0433\u0430\u043B\u044C\u043E\u043D\u0430": "noun",
      "\u0433\u043E\u043B\u0442\u0432\u0430": "noun",
      "\u0433\u043E\u0440\u0435\u043C\u0443\u043B\u044C\u0442\u0430": "noun",
      "\u0434\u0430\u0446\u0438\u043D\u0430": "noun",
      "\u0437\u0430\u0431\u0430\u043D\u0434\u0436\u0430\u043B\u0430": "noun",
      "\u0437\u043B\u0430\u044F": "adjective",
      "\u043A\u0456\u043A\u0435\u043D\u0430": "noun",
      "\u043A\u043E\u0440\u043E\u043F\u0430\u0442\u0432\u0430": "noun",
      "\u043A\u0443\u0437\u0438\u043D\u0430": "adjective",
      "\u043B\u0430\u043F\u0443\u043D\u044C\u043A\u0430": "noun",
      "\u043B\u0456\u0442\u0430\u0432\u0430": "noun",
      "\u043C\u0456\u043D\u0447\u0443\u043D\u0430": "noun",
      "\u043D\u0430": "noun",
      "\u043D\u0438\u0447\u0430\u044F": "noun",
      "\u043D\u043E\u0432\u0456\u0446\u043A\u0430": "adjective",
      "\u043F\u0435\u043D\u044C\u043A\u043D\u0430": "noun",
      "\u043F\u0443\u0445\u043D\u0430": "noun",
      "\u043F\u0443\u0446\u044F\u0442\u0430": "noun",
      "\u0440\u0456\u0441\u043D\u0430": "noun",
      "\u0440\u043E\u0437\u043C\u0430\u0456\u0442\u0430": "noun",
      "\u0440\u0443\u043C\u0438\u043D\u0430": "adjective",
      "\u0441\u0432\u0442\u043D\u0430": "noun",
      "\u0441\u0435\u0440\u0434\u0438\u0442\u0430": "adjective",
      "\u0441\u0456\u0447\u0456\u043D\u0430\u0432\u0430": "noun",
      "\u0441\u043C\u0435\u043D\u0442\u0438\u043D\u0430": "noun",
      "\u0442\u0440\u0456\u0437\u043D\u0430": "noun",
      "\u0448\u043A\u0443\u0440\u043E\u043F\u0430\u0442\u0430": "noun",
      "\u0431\u0435\u0437\u0445\u0443\u0442\u0440\u0430": "adjective",
      "\u0433\u0430\u043B\u044C\u0432\u0430": "noun",
      "\u0433\u043D\u0454\u0434\u0430": "adjective",
      "\u0433\u0440\u0435\u0431\u0435\u043D\u0447\u0430": "noun",
      "\u0433\u0443\u0441\u043E\u043D\u044C\u043A\u0430": "noun",
      "\u043A\u0430\u043B\u0430\u0431\u0430\u043D\u044C\u043A\u0430": "noun",
      "\u043A\u043E\u0437\u0443\u043F\u043B\u044F\u043A\u0430": "noun",
      "\u043B\u0430\u043F\u0438\u043D\u0430": "adjective",
      "\u043C\u0443\u0440\u0438\u043D\u0430": "adjective",
      "\u043D\u0435\u043A\u0443\u043B\u044C\u0447\u0430": "noun",
      "\u043E\u0440\u043E\u043D\u0430": "noun",
      "\u043F\u0430\u0440\u043D\u0430": "adjective",
      "\u043F\u043B\u0456\u0432\u0430": "noun",
      "\u043F\u0440\u0438\u0445\u043E\u0434\u044C\u043A\u0430": "noun",
      "\u0441\u0435\u043D\u0438\u043D\u0430": "noun",
      "\u0441\u043E\u043B\u043E\u0442\u0432\u0430": "noun",
      "\u0442\u0435\u0442\u0435\u0432\u0430": "adjective",
      "\u0445\u0430\u0432\u0430\u043D\u0430": "noun",
      "\u0446\u0430\u0440\u0435\u0432\u0430": "adjective",
      "\u0430\u0445\u0430\u043B\u0430\u044F": "noun",
      "\u0432\u0430\u0440\u0435\u043D\u044C\u043A\u0430": "noun",
      "\u0432\u0430\u0440\u0448\u0430\u0432\u0430": "noun",
      "\u0432\u0435\u0440\u0435\u0441\u043E\u0447\u0430": "noun",
      "\u0433\u0430\u043B\u0443\u043D\u044C\u043A\u0430": "noun",
      "\u0433\u043B\u0456\u0432\u0430": "noun",
      "\u0433\u043E\u043B\u0438\u043D\u0430": "adjective",
      "\u0433\u0440\u0443\u0437\u044C\u043A\u0430": "adjective",
      "\u0433\u0443\u0434\u0438\u043D\u0430": "noun",
      "\u0454\u0432\u043E\u043D\u0430": "noun",
      "\u043A\u0456\u0440\u0435\u0432\u0430": "adjective",
      "\u043A\u043E\u0436\u0435\u043C'\u044F\u043A\u0430": "noun",
      "\u043A\u043E\u043B\u043E\u0431\u0435\u0440\u0434\u0430": "adjective",
      "\u043A\u0443\u0440\u0456\u043D\u044C\u043A\u0430": "noun",
      "\u043C\u0430\u0440\u0436\u0438\u043D\u0430": "noun",
      "\u043C\u0438\u0433\u0430\u043B\u0438\u043D\u0430": "noun",
      "\u043C\u0456\u043A\u0430\u0432\u0430": "adjective",
      "\u043F\u0430\u0434\u0432\u0430": "noun",
      "\u043F\u0430\u043B\u0430\u043D\u0438\u0447\u043A\u0430": "adjective",
      "\u043F\u0430\u043B\u0435\u043D\u0430": "adjective",
      "\u043F\u043E\u0434\u043A\u043E\u0432\u0430": "noun",
      "\u0440\u0430\u0442\u0443\u0448\u043D\u044F": "adjective",
      "\u0441\u0435\u043B\u0435\u0433\u0435\u0439\u043D\u0430": "noun",
      "\u0441\u043C\u0438\u043D\u0442\u0438\u043D\u0430": "noun",
      "\u0441\u0443\u043C\u0438\u043D\u0430": "adjective",
      "\u0442\u0435\u043C\u0456\u0440\u043A\u0430\u044F": "noun",
      "\u0443\u0445\u0430\u0442\u0430": "adjective",
      "\u0445\u0430\u0432\u0440\u043E\u043D\u044F": "noun",
      "\u0445\u043E\u043B\u043E\u0441\u0442\u0430": "adjective",
      "\u0446\u0456\u0432\u0430": "noun",
      "\u0447\u0435\u0440\u043D\u044F\u0442\u0430": "noun",
      "\u0447\u0438\u043A\u043E\u043B\u044C\u0432\u0430": "noun",
      "\u0448\u0430\u043B\u0438\u043D\u0430": "adjective",
      "\u044E\u0434\u0438\u043D\u0430": "adjective",
      "\u0430\u0434\u0432\u0435\u043D\u0430": "noun",
      "\u0431\u0430\u043B\u0435\u0432\u0430": "adjective",
      "\u0431\u0440\u043E\u043D\u0430": "noun",
      "\u0432\u0435\u0440\u0431\u043E\u0432\u0430\u0442\u0430": "adjective",
      "\u0432\u0435\u0440\u0435\u043C\u0454\u0432\u0430": "noun",
      "\u0432\u043E\u043B\u0447\u0430\u0441\u0442\u0430": "adjective",
      "\u0433\u0430\u0444\u0438\u043D\u0430": "adjective",
      "\u0433\u043E\u043B\u0443\u0442\u0432\u0430": "noun",
      "\u0437\u0430\u043A\u0440\u0435\u0432\u0430": "noun",
      "\u043A\u0430\u0434\u0436\u0430\u044F": "noun",
      "\u043A\u0430\u043B\u044C\u0447\u0435\u043D\u044F": "noun",
      "\u043A\u0430\u043F\u0430\u043D\u0438\u0441\u0442\u0430": "adjective",
      "\u043A\u0438\u043A\u0438\u043D\u0430": "adjective",
      "\u043A\u043E\u0441\u0442\u0435\u0440\u0435\u0432\u0430": "noun",
      "\u043A\u0440\u0438\u0432\u043E\u043A\u043E\u0431\u0438\u043B\u0430": "noun",
      "\u043A\u0443\u043B\u0454\u0432\u0430": "noun",
      "\u043B\u0430\u0432\u043D\u0430": "noun",
      "\u043C\u0430\u043B\u0456\u0446\u043A\u0430": "adjective",
      "\u043C\u043E\u043B\u0434\u043E\u0432\u0430": "noun",
      "\u043C\u043E\u0440\u043A\u043E\u0432\u0430": "noun",
      "\u043F\u0430\u0436\u0438\u043D\u0430": "adjective",
      "\u043F\u0435\u0440\u0435\u0432\u0435\u0440\u043D\u0438\u0445\u0430\u0442\u0430": "noun",
      "\u043F\u0438\u043B\u0435\u0432\u0430": "adjective",
      "\u043F\u0456\u0434\u0434\u0443\u0431\u043D\u044F": "adjective",
      "\u043F\u043E\u0441\u0442\u0456\u0432\u0430": "noun",
      "\u043F\u0443\u0441\u0442\u0430": "adjective",
      "\u0441\u0443\u0431\u043E\u0442\u043D\u044F": "adjective",
      "\u0444\u0430\u0434\u0435\u0435\u0432\u0430": "adjective",
      "\u0445\u043E\u0434\u0430\u043D\u0456\u0446\u043A\u0430": "adjective",
      "\u0445\u043E\u0445\u0456\u0442\u0432\u0430": "noun",
      "\u0446\u0438\u0431\u0430\u0442\u0430": "adjective",
      "\u0447\u0435\u0440\u043D\u043E\u043E\u043A\u0430": "adjective",
      "\u0447\u043A\u0430\u0434\u0443\u0430": "noun",
      "\u0447\u043E\u043A\u0435\u043D\u0430": "noun",
      "\u0448\u0435\u043F\u0435\u0442\u0438\u043D\u0430": "noun",
      "\u0448\u0435\u0440\u0431\u0438\u043D\u0430": "noun",
      "\u044F\u043A\u0430": "adjective",
      "\u044F\u0442\u0432\u0430": "noun",
      "\u0431\u0435\u0437\u0435\u043D\u0430": "noun",
      "\u0431\u0435\u0437\u0448\u043A\u0443\u0440\u0430": "adjective",
      "\u0431\u0435\u0437\u044F\u0437\u0438\u043A\u0430": "adjective",
      "\u0431\u0435\u043B\u0430\u044F": "adjective",
      "\u0431\u0435\u0440\u0443\u043B\u0430\u0432\u0430": "noun",
      "\u0431\u0443\u0437\u043D\u0430": "noun",
      "\u0431\u0443\u0440\u0441\u0430\u043B\u0430": "noun",
      "\u0431\u0443\u0447\u0430\u0441\u0442\u0430": "adjective",
      "\u0432\u0447\u0438\u043D\u0430": "noun",
      "\u0433\u0430\u043F\u043E\u043D\u0430": "noun",
      "\u0433\u0435\u0440\u043D\u0430\u0436\u0430": "noun",
      "\u0433\u043E\u0440\u0434\u0443\u043D\u0430": "noun",
      "\u0433\u043E\u0440\u0441\u0432\u0430": "noun",
      "\u0433\u043E\u0440\u044F\u0441\u0432\u0430": "noun",
      "\u0433\u0440\u0438\u0446\u044C\u043A\u0430": "noun",
      "\u0434\u0432\u0456\u0436\u043E\u043D\u0430": "noun",
      "\u0437\u0430\u0434\u0443\u0440\u043D\u044F": "adjective",
      "\u0437\u0430\u0441\u043B\u043E\u043D\u0430": "noun",
      "\u0437\u0430\u0447\u0435\u0448\u0438\u0433\u0440\u0438\u0432\u0430": "noun",
      "\u0439\u043E\u043D\u0430": "noun",
      "\u043A\u0430\u0447\u043D\u0430": "adjective",
      "\u043A\u043E\u0437\u043E\u0432\u0456\u0442\u0430": "noun",
      "\u043A\u0440\u0438\u0432\u043E\u0440\u043E\u0442\u0430": "adjective",
      "\u043A\u0443\u0440'\u044F\u0442\u0430": "noun",
      "\u043B\u043E\u0437\u043D\u0430": "adjective",
      "\u043B\u044E\u043B\u044F\u0432\u0430": "noun",
      "\u043B\u044E\u0442\u0430\u044F": "adjective",
      "\u043C\u0430\u0442\u0443\u0445\u043D\u0430": "noun",
      "\u043D\u0430\u043A\u0443\u0442\u043D\u044F": "adjective",
      "\u043F\u043B\u043E\u0445\u0430\u044F": "adjective",
      "\u0431\u0443\u0445\u0430\u044F": "adjective",
      "\u0441\u0430\u043C\u043E\u0442\u043D\u044F": "adjective",
      "\u043F\u0430\u043D\u0456\u0431\u0443\u0434\u044C\u043B\u0430\u0441\u043A\u0430": "noun"
    };
    exports2.default = incorrectPredictionsCache;
  }
});

// node_modules/shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/family-name-class-transformer.js
var require_family_name_class_transformer = __commonJS({
  "node_modules/shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/family-name-class-transformer.js"(exports2) {
    "use strict";
    require_alphabet();
    var wordClass = require_word_class();
    require_grammatical_case();
    require_grammatical_gender();
    var FamilyNameClassTransformer = class {
      encode(familyNameClass) {
        const values = new Uint8Array(1);
        switch (familyNameClass.wordClass) {
          case wordClass.WordClass.NOUN:
            values[0] = 1;
            break;
          case wordClass.WordClass.ADJECTIVE:
            values[0] = 0;
            break;
          default:
            throw new TypeError(`Invalid word class: "${familyNameClass.wordClass}".`);
        }
        return values;
      }
      decode(values) {
        if (values.length < 1 || values.length > 1) {
          throw new RangeError("Invalid vector length.");
        }
        const value = values[0];
        if (value < 0 || value > 1) {
          throw new RangeError("Invalid vector value.");
        }
        const wordClass$1 = value >= 0.5 ? wordClass.WordClass.NOUN : wordClass.WordClass.ADJECTIVE;
        return { wordClass: wordClass$1 };
      }
    };
    exports2.FamilyNameClassTransformer = FamilyNameClassTransformer;
  }
});

// node_modules/shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/model-config.js
var require_model_config = __commonJS({
  "node_modules/shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/model-config.js"(exports2) {
    "use strict";
    var MODEL_INPUT_SIZE = 20;
    exports2.MODEL_INPUT_SIZE = MODEL_INPUT_SIZE;
  }
});

// node_modules/shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/word-transformer.js
var require_word_transformer = __commonJS({
  "node_modules/shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/word-transformer.js"(exports2) {
    "use strict";
    var alphabet = require_alphabet();
    require_word_class();
    require_grammatical_case();
    require_grammatical_gender();
    var WordTransformer = class {
      constructor(vectorSize, unknownCharcode = 0) {
        this.vectorSize = vectorSize;
        this.unknownCharcode = unknownCharcode;
      }
      /**
       * Vectorizes a given word for ML processing.
       */
      encode(word) {
        var _a;
        const values = new Uint8Array(this.vectorSize);
        const letters = word.slice(-this.vectorSize).toLowerCase().padStart(this.vectorSize, "-");
        for (let index = 0; index < letters.length; index += 1) {
          const letter = letters[index];
          values[index] = (_a = alphabet.AlphabetEncoding[letter]) !== null && _a !== void 0 ? _a : this.unknownCharcode;
        }
        return values;
      }
    };
    exports2.WordTransformer = WordTransformer;
  }
});

// node_modules/shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/family-name-classifer.js
var require_family_name_classifer = __commonJS({
  "node_modules/shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/family-name-classifer.js"(exports2) {
    "use strict";
    var tf = require_tf_node();
    var incorrectPredictions = require_incorrect_predictions_json();
    var familyNameClassTransformer = require_family_name_class_transformer();
    var modelConfig = require_model_config();
    var wordTransformer = require_word_transformer();
    function _interopNamespaceDefault(e) {
      var n = /* @__PURE__ */ Object.create(null);
      if (e) {
        Object.keys(e).forEach(function(k) {
          if (k !== "default") {
            var d = Object.getOwnPropertyDescriptor(e, k);
            Object.defineProperty(n, k, d.get ? d : {
              enumerable: true,
              get: function() {
                return e[k];
              }
            });
          }
        });
      }
      n.default = e;
      return Object.freeze(n);
    }
    var tf__namespace = /* @__PURE__ */ _interopNamespaceDefault(tf);
    tf__namespace.env().set("IS_NODE", false);
    var FamilyNameClassifier = class {
      constructor(modelLoader) {
        this.modelLoader = modelLoader;
        this.modelPromise = null;
        this.wordTransformer = new wordTransformer.WordTransformer(modelConfig.MODEL_INPUT_SIZE);
        this.familyNameClassTransformer = new familyNameClassTransformer.FamilyNameClassTransformer();
      }
      /**
       * Classifies the word class of a given family name.
       */
      async classify(familyName) {
        let familyNameClass = this.getCached(familyName);
        if (familyNameClass != null) {
          return familyNameClass;
        }
        const model = await this.loadModel();
        const input = this.wordTransformer.encode(familyName);
        const output = await model.predict(tf__namespace.tensor2d([input])).data();
        familyNameClass = this.familyNameClassTransformer.decode(output);
        return familyNameClass;
      }
      /**
       * Returns a classified family name class from the cache if exists.
       */
      getCached(familyName) {
        let familyNameClass = null;
        const wordClass = incorrectPredictions.default[familyName.toLowerCase()];
        if (wordClass) {
          familyNameClass = { wordClass };
        }
        return familyNameClass;
      }
      /**
       * Loads the model from the storage. If called multiple times, resolves the same model instance.
       */
      async loadModel() {
        if (this.modelPromise == null) {
          this.modelPromise = tf__namespace.loadLayersModel(this.modelLoader);
        }
        return this.modelPromise;
      }
    };
    exports2.FamilyNameClassifier = FamilyNameClassifier;
  }
});

// node_modules/shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/artifacts/model.bundle.json.js
var require_model_bundle_json = __commonJS({
  "node_modules/shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/artifacts/model.bundle.json.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var modelInfo = {
      dateSaved: "2023-02-25T18:20:32.974Z",
      modelTopologyType: "JSON",
      modelTopologyBytes: 1659,
      weightSpecsBytes: 428,
      weightDataBytes: 4356
    };
    var modelTopology = {
      class_name: "Sequential",
      config: {
        name: "sequential_1",
        layers: [
          {
            class_name: "Embedding",
            config: {
              input_dim: 34,
              output_dim: 16,
              embeddings_initializer: {
                class_name: "RandomUniform",
                config: {
                  minval: -0.05,
                  maxval: 0.05,
                  seed: null
                }
              },
              embeddings_regularizer: null,
              activity_regularizer: null,
              embeddings_constraint: null,
              mask_zero: null,
              input_length: null,
              name: "embedding_Embedding1",
              trainable: true,
              batch_input_shape: [
                null,
                null
              ]
            }
          },
          {
            class_name: "SimpleRNN",
            config: {
              name: "simple_rnn_SimpleRNN1",
              trainable: true,
              units: 16,
              activation: "relu",
              use_bias: true,
              kernel_initializer: {
                class_name: "VarianceScaling",
                config: {
                  scale: 1,
                  mode: "fan_avg",
                  distribution: "normal",
                  seed: null
                }
              },
              recurrent_initializer: {
                class_name: "Orthogonal",
                config: {
                  gain: 1,
                  seed: null
                }
              },
              bias_initializer: {
                class_name: "Zeros",
                config: {}
              },
              kernel_regularizer: null,
              recurrent_regularizer: null,
              bias_regularizer: null,
              activity_regularizer: null,
              kernel_constraint: null,
              recurrent_constraint: null,
              bias_constraint: null,
              dropout: 0,
              recurrent_dropout: 0,
              return_sequences: false,
              return_state: false,
              go_backwards: false,
              stateful: false,
              unroll: false
            }
          },
          {
            class_name: "Dense",
            config: {
              units: 1,
              activation: "sigmoid",
              use_bias: true,
              kernel_initializer: {
                class_name: "VarianceScaling",
                config: {
                  scale: 1,
                  mode: "fan_avg",
                  distribution: "normal",
                  seed: null
                }
              },
              bias_initializer: {
                class_name: "Zeros",
                config: {}
              },
              kernel_regularizer: null,
              bias_regularizer: null,
              activity_regularizer: null,
              kernel_constraint: null,
              bias_constraint: null,
              name: "dense_Dense1",
              trainable: true
            }
          }
        ]
      },
      keras_version: "tfjs-layers 4.2.0",
      backend: "tensor_flow.js"
    };
    var weightSpecs = [
      {
        name: "embedding_Embedding1/embeddings",
        shape: [
          34,
          16
        ],
        dtype: "float32"
      },
      {
        name: "simple_rnn_SimpleRNN1/kernel",
        shape: [
          16,
          16
        ],
        dtype: "float32"
      },
      {
        name: "simple_rnn_SimpleRNN1/recurrent_kernel",
        shape: [
          16,
          16
        ],
        dtype: "float32"
      },
      {
        name: "simple_rnn_SimpleRNN1/bias",
        shape: [
          16
        ],
        dtype: "float32"
      },
      {
        name: "dense_Dense1/kernel",
        shape: [
          16,
          1
        ],
        dtype: "float32"
      },
      {
        name: "dense_Dense1/bias",
        shape: [
          1
        ],
        dtype: "float32"
      }
    ];
    var weightData = " ";
    var modelMetadata = {
      format: "layers-model",
      generatedBy: "TensorFlow.js tfjs-layers v4.2.0",
      convertedBy: null
    };
    var modelBundle = {
      modelInfo,
      modelTopology,
      weightSpecs,
      weightData,
      modelMetadata
    };
    exports2.default = modelBundle;
    exports2.modelInfo = modelInfo;
    exports2.modelMetadata = modelMetadata;
    exports2.modelTopology = modelTopology;
    exports2.weightData = weightData;
    exports2.weightSpecs = weightSpecs;
  }
});

// node_modules/shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/model-bundle-loader.js
var require_model_bundle_loader = __commonJS({
  "node_modules/shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/model-bundle-loader.js"(exports2) {
    "use strict";
    var model_bundle = require_model_bundle_json();
    var useNodeBuffer = typeof Buffer !== "undefined" && (typeof Blob === "undefined" || typeof atob === "undefined" || typeof btoa === "undefined");
    function base64StringToArrayBuffer(str) {
      if (useNodeBuffer) {
        const buf = Buffer.from(str, "base64");
        return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
      }
      const s = atob(str);
      const buffer = new Uint8Array(s.length);
      for (let i = 0; i < s.length; ++i) {
        buffer.set([s.charCodeAt(i)], i);
      }
      return buffer.buffer;
    }
    var ModelBundleLoader = class {
      /**
       * Saves the model artifacts from the artifacts directory in JSON format.
       */
      async load() {
        const out = {};
        out.modelTopology = model_bundle.default.modelTopology;
        out.weightSpecs = model_bundle.default.weightSpecs;
        out.weightData = base64StringToArrayBuffer(model_bundle.default.weightData);
        if (model_bundle.default.modelMetadata != null) {
          const metadata = model_bundle.default.modelMetadata;
          out.format = metadata.format;
          out.generatedBy = metadata.generatedBy;
          out.convertedBy = metadata.convertedBy;
          if (metadata.signature != null) {
            out.signature = metadata.signature;
          }
          if (metadata.userDefinedMetadata != null) {
            out.userDefinedMetadata = metadata.userDefinedMetadata;
          }
          if (metadata.modelInitializer != null) {
            out.modelInitializer = metadata.modelInitializer;
          }
          if (metadata.initializerSignature != null) {
            out.initializerSignature = metadata.initializerSignature;
          }
          if (metadata.trainingConfig != null) {
            out.trainingConfig = metadata.trainingConfig;
          }
        }
        return out;
      }
    };
    exports2.ModelBundleLoader = ModelBundleLoader;
    exports2.base64StringToArrayBuffer = base64StringToArrayBuffer;
  }
});

// node_modules/shevchenko/dist/cjs/language/linguistics.js
var require_linguistics = __commonJS({
  "node_modules/shevchenko/dist/cjs/language/linguistics.js"(exports2) {
    "use strict";
    var VOWEL_PATTERN = /[аоуеиіяюєї]/gi;
    function countSyllables(word) {
      const matches = word.match(VOWEL_PATTERN);
      if (matches == null) {
        return 0;
      }
      return matches.length;
    }
    function isMonosyllable(word) {
      return countSyllables(word) === 1;
    }
    exports2.VOWEL_PATTERN = VOWEL_PATTERN;
    exports2.isMonosyllable = isMonosyllable;
  }
});

// node_modules/shevchenko/dist/cjs/anthroponym-declension/name-inflector.js
var require_name_inflector = __commonJS({
  "node_modules/shevchenko/dist/cjs/anthroponym-declension/name-inflector.js"(exports2) {
    "use strict";
    var NameInflector = class {
      /**
       * Inflects the name in the given grammatical case.
       */
      async inflect(name, gender, grammaticalCase) {
        const inflectedNameParts = [];
        const nameParts = name.split("-");
        for (let index = 0; index < nameParts.length; index += 1) {
          const inflectedNamePart = await this.inflectNamePart(nameParts[index], gender, grammaticalCase, index === nameParts.length - 1);
          inflectedNameParts.push(inflectedNamePart);
        }
        return inflectedNameParts.join("-");
      }
    };
    exports2.NameInflector = NameInflector;
  }
});

// node_modules/shevchenko/dist/cjs/anthroponym-declension/family-name-inflector.js
var require_family_name_inflector = __commonJS({
  "node_modules/shevchenko/dist/cjs/anthroponym-declension/family-name-inflector.js"(exports2) {
    "use strict";
    require_alphabet();
    require_word_class();
    var linguistics = require_linguistics();
    require_grammatical_case();
    var grammaticalGender = require_grammatical_gender();
    var nameInflector = require_name_inflector();
    var UNCERTAIN_FEMININE_FAMILY_NAME_PATTERN = /[ая]$/i;
    var UNCERTAIN_MASCULINE_FAMILY_NAME_PATTERN = /(ой|ий|ій|их)$/i;
    var FamilyNameInflector = class extends nameInflector.NameInflector {
      constructor(wordInflector, familyNameClassifier) {
        super();
        this.wordInflector = wordInflector;
        this.familyNameClassifier = familyNameClassifier;
      }
      /**
       * @inheritdoc
       */
      async inflectNamePart(familyName, gender, grammaticalCase, isLastWord) {
        if (!isLastWord && linguistics.isMonosyllable(familyName)) {
          return familyName;
        }
        let familyNameClass = null;
        if (this.isUncertainFamilyNameClass(familyName, gender)) {
          familyNameClass = await this.familyNameClassifier.classify(familyName);
        }
        return this.wordInflector.inflect(familyName, {
          grammaticalCase,
          gender,
          wordClass: familyNameClass === null || familyNameClass === void 0 ? void 0 : familyNameClass.wordClass,
          applicationType: "familyName"
        });
      }
      /**
       * Determines whether a given family name could be both a noun or adjective word class.
       */
      isUncertainFamilyNameClass(familyName, gender) {
        return gender === grammaticalGender.GrammaticalGender.FEMININE && UNCERTAIN_FEMININE_FAMILY_NAME_PATTERN.test(familyName) || gender === grammaticalGender.GrammaticalGender.MASCULINE && UNCERTAIN_MASCULINE_FAMILY_NAME_PATTERN.test(familyName);
      }
    };
    exports2.FamilyNameInflector = FamilyNameInflector;
  }
});

// node_modules/shevchenko/dist/cjs/anthroponym-declension/given-name-inflector.js
var require_given_name_inflector = __commonJS({
  "node_modules/shevchenko/dist/cjs/anthroponym-declension/given-name-inflector.js"(exports2) {
    "use strict";
    var nameInflector = require_name_inflector();
    var GivenNameInflector = class extends nameInflector.NameInflector {
      constructor(wordInflector) {
        super();
        this.wordInflector = wordInflector;
      }
      /**
       * @inheritdoc
       */
      inflectNamePart(givenName, gender, grammaticalCase) {
        return this.wordInflector.inflect(givenName, {
          grammaticalCase,
          gender,
          applicationType: "givenName"
        });
      }
    };
    exports2.GivenNameInflector = GivenNameInflector;
  }
});

// node_modules/shevchenko/dist/cjs/anthroponym-declension/patronymic-name-inflector.js
var require_patronymic_name_inflector = __commonJS({
  "node_modules/shevchenko/dist/cjs/anthroponym-declension/patronymic-name-inflector.js"(exports2) {
    "use strict";
    var nameInflector = require_name_inflector();
    var PatronymicNameInflector = class extends nameInflector.NameInflector {
      constructor(wordInflector) {
        super();
        this.wordInflector = wordInflector;
      }
      /**
       * @inheritdoc
       */
      inflectNamePart(patronymicName, gender, grammaticalCase) {
        return this.wordInflector.inflect(patronymicName, {
          grammaticalCase,
          gender,
          applicationType: "patronymicName",
          customRuleFilter: (declensionRule) => declensionRule.applicationType.includes("patronymicName")
        });
      }
    };
    exports2.PatronymicNameInflector = PatronymicNameInflector;
  }
});

// node_modules/shevchenko/dist/cjs/anthroponym-declension/bootstrap.js
var require_bootstrap2 = __commonJS({
  "node_modules/shevchenko/dist/cjs/anthroponym-declension/bootstrap.js"(exports2) {
    "use strict";
    var bootstrap = require_bootstrap();
    var anthroponymInflector$1 = require_anthroponym_inflector();
    var familyNameClassifer = require_family_name_classifer();
    var modelBundleLoader = require_model_bundle_loader();
    var familyNameInflector$1 = require_family_name_inflector();
    var givenNameInflector$1 = require_given_name_inflector();
    var patronymicNameInflector$1 = require_patronymic_name_inflector();
    var givenNameInflector = new givenNameInflector$1.GivenNameInflector(bootstrap.wordInflector);
    var patronymicNameInflector = new patronymicNameInflector$1.PatronymicNameInflector(bootstrap.wordInflector);
    var familyNameClassifier = new familyNameClassifer.FamilyNameClassifier(new modelBundleLoader.ModelBundleLoader());
    var familyNameInflector = new familyNameInflector$1.FamilyNameInflector(bootstrap.wordInflector, familyNameClassifier);
    var anthroponymInflector = new anthroponymInflector$1.AnthroponymInflector(givenNameInflector, patronymicNameInflector, familyNameInflector);
    exports2.anthroponymInflector = anthroponymInflector;
  }
});

// node_modules/shevchenko/dist/cjs/extension.js
var require_extension = __commonJS({
  "node_modules/shevchenko/dist/cjs/extension.js"(exports2) {
    "use strict";
    var bootstrap = require_bootstrap();
    var registeredExtensions = [];
    function registerExtension(extensionFactory) {
      const extension = extensionFactory({ wordInflector: bootstrap.wordInflector });
      registeredExtensions.push(extension);
    }
    function getCustomFieldNames() {
      const fieldNames = [];
      for (const extension of registeredExtensions) {
        fieldNames.push(...extension.fieldNames);
      }
      return fieldNames;
    }
    async function afterInflect(grammaticalCase, input) {
      var _a;
      const output = {};
      for (const extension of registeredExtensions) {
        const customOutput = await ((_a = extension.afterInflect) === null || _a === void 0 ? void 0 : _a.call(extension, grammaticalCase, input));
        if (customOutput != null) {
          Object.assign(output, customOutput);
        }
      }
      return output;
    }
    exports2.afterInflect = afterInflect;
    exports2.getCustomFieldNames = getCustomFieldNames;
    exports2.registerExtension = registerExtension;
  }
});

// node_modules/shevchenko/dist/cjs/gender-detection/artifacts/given-name-rules.json.js
var require_given_name_rules_json = __commonJS({
  "node_modules/shevchenko/dist/cjs/gender-detection/artifacts/given-name-rules.json.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var masculine = "(\u0438\u043D|\u0456\u0439|\u043E\u043C|\u0430\u043C|\u044F\u043D|\u0430\u043D|\u0430\u0440|\u0440\u0442|\u0430\u0441|\u043E\u043D|\u0456\u043D|\u0435\u043D|\u0435\u043C|\u0443\u0440|\u0438\u043F|\u044C\u0434|\u0435\u0439|\u043A\u043E|\u0438\u0434|\u0441\u0442|\u0438\u0440|\u0430\u0432|\u0441\u043B|\u0438\u0441|\u043E\u0439|\u0438\u043B|\u0438\u043C|\u0434\u0440|\u0435\u0442|\u0443\u0431|\u043E\u0440|\u0430\u0434|\u0430\u0439|\u044E\u0431|\u043E\u0434|\u044E\u0434|\u043E\u043B|\u043B\u043E|\u0456\u0431|\u0430\u0442|\u0443\u043D|\u0443\u043C|\u044F\u0434|\u0456\u0442|\u0438\u043A|\u043E\u0433|\u0430\u0447|\u0440\u043E|\u0443\u0433|\u0456\u043A|\u0456\u0434|\u0442\u043E|\u0443\u0441|\u043D\u043D|\u0438\u0439|\u0434\u043E|\u0435\u0432|\u0438\u0447|\u0443\u0445|\u0446\u044C|\u0435\u0433|\u0441\u044C|\u0456\u0432|\u0430\u043F|\u0456\u043C|\u0437\u0434|\u0430\u0446|\u0454\u0440|\u0457\u043B|\u0440\u0433|\u044F\u0440|\u043B\u043A|\u043E\u043A|\u0456\u043B|\u043E\u0445|\u0456\u0448|\u0456\u0433|\u0438\u0432|\u0443\u043A|\u0435\u043A|\u043E\u0448|\u0438\u043B\u044C|\u0432\u0456\u0440|\u0443\u043B\u0430|\u044F\u0442\u0430|\u0437\u0456\u0440|\u0438\u0432\u0430|\u0438\u043D\u044F|\u0435\u0433\u0430|\u043B\u043B\u044F|\u044C\u043C\u0430|\u0443\u043A\u0430|\u043F\u0456\u0440|\u0440\u0438\u0442|\u043C\u043E\u0432|\u0430\u0433\u0430|\u0434\u0456\u0440|\u0430\u043B\u0430|\u0435\u043C\u0430|\u0432\u0438\u0442|\u0432\u043E\u043B\u044F|\u0448\u0430\u0442\u0430|\u0456\u0442\u0435\u0440|\u0431\u0456\u0434\u0430|\u043A\u0438\u0442\u0430|\u043A\u043E\u043B\u0430|\u0435\u043A\u0441\u0430|\u043B\u0435\u043B\u044C|\u0440\u0430\u0432\u0430|\u0441\u0438\u043B\u0430|\u0432\u0443\u0442\u0430|\u0443\u0440\u043C\u0430|\u0434\u043E\u0442\u0430|\u0447\u0430\u0440\u0430|\u0441\u043B\u0430\u0432\u0430)$";
    var feminine = "(\u0456\u044F|\u0442\u0430|\u0430\u044F|\u043D\u0430|\u0434\u0430|\u0437\u0430|\u0441\u0430|\u043B\u0430|\u043A\u0430|\u0441\u044F|\u0440\u0430|\u0432\u0430|\u0434\u044F|\u0435\u044F|['\u2019\u02BC]\u044F|\u0445\u0430|\u043C\u0430|\u0440\u044F|\u043E\u044F|\u0433\u0430|\u043F\u0430|\u0434\u044C|\u043D\u044F|\u043B\u044F|\u0439\u044F|\u0448\u0430|\u0444\u0430|\u0431\u0430|\u0442\u044F|\u043B\u044C|\u0443\u0442|\u0443\u0444|\u0438\u0444|i\u044F|\u0441\u0442\u0430|\u043E\u0440\u0430|\u0438\u043A\u0430|\u0457\u0434\u0430|\u0435\u0441\u0430|\u0430\u0434\u0430|\u0456\u0442\u0430|\u0456\u0441\u0430|\u043B\u043B\u0430|\u0435\u0434\u0430|\u0435\u043B\u0430|\u0456\u043A\u0430|\u0438\u0434\u0430|\u0438\u0441\u0430|\u0440\u0442\u0430|\u0430\u0432\u0430|\u043D\u0434\u0430|\u0430\u0440\u0430|\u0441\u0441\u0430|\u043A\u043B\u0430|\u0435\u0440\u0430|\u0442\u0442\u0430|\u0456\u0440\u0430|\u0438\u0440\u0430|\u0443\u0434\u0430|\u0440\u043A\u0430|\u043D\u043A\u0430|\u043C\u043C\u0430|\u0457\u043B\u0430|\u044C\u0434\u0430|\u0444\u0456\u0440|\u0454\u0432\u0430|\u0432\u0433\u0430|\u0435\u0442\u0430|\u0448\u043A\u0430|\u0438\u043C\u0430|\u0430\u0442\u0430|\u044F\u0434\u0430|\u043D\u0433\u0430|\u0437\u043A\u0430|\u0434\u0440\u0430|\u0442\u043A\u0430|\u0442\u0440\u0430|\u0443\u043D\u044F|\u0435\u043B\u044F|\u043E\u043B\u0430|\u0430\u043D\u044F|\u0431\u043E\u0432|\u0438\u043B\u0430|\u0432\u043A\u0430|\u0433\u0434\u0430|\u044C\u0432\u0430|\u0447\u043A\u0430|\u043E\u0433\u0430|\u0439\u0434\u0430|\u0430\u043B\u044F|\u043B\u043A\u0430|\u0434\u043A\u0430|\u0435\u043B\u044C|\u044C\u0433\u0430|\u0441\u043B\u0430|\u043E\u0432\u0430|\u0432\u043B\u0430|\u0437\u0433\u0430|\u0435\u0432\u0430|\u0437\u0434\u0430|\u044C\u043A\u0430|\u0457\u0441\u0430|\u0435\u043A\u0430|\u043A\u043A\u0430|\u043E\u0434\u0430|\u044F\u0432\u0430|\u043D\u0442\u0430|\u0440\u0440\u0430|\u044F\u0440\u0430|\u043E\u043A\u0430|\u043E\u043D\u044F|\u043A\u043B\u044F|\u0456\u0432\u0430|\u0438\u0442\u0430|\u0434\u0438\u0442|\u0445\u0432\u0430|\u0456\u0433\u0430|\u0433\u0430\u0442\u0430|\u0431\u0430\u0440\u0430|\u043B\u0430\u0432\u0430|\u0432\u0430\u0440\u0430|\u0456\u043E\u043B\u0430|\u0442\u0430\u0432\u0430|\u0443\u0435\u043B\u044C|\u0441\u0442\u0435\u0440|\u0431\u0430\u0432\u0430|\u043B\u0430\u0442\u0430|\u0456\u0440\u043C\u0430|\u0444\u0430\u0442\u0430|\u043B\u0430\u0440\u0430|\u0434\u0430\u0440\u0430|\u043F\u0430\u0432\u0430|\u043C\u0438\u043B\u0430|\u043B\u043E\u043B\u0430|\u044C\u043E\u043B\u044F|\u0440\u0438\u0442\u0430|\u0440\u0443\u0442\u0430|\u043D\u0435\u043B\u044C|\u043D\u0430\u0442\u0430|\u043D\u0456\u0434\u0430|\u0441\u0430\u0432\u0430|\u0448\u0435\u043B\u044C|\u0441\u0430\u0440\u0430|\u0437\u0430\u0440\u0430|\u043C\u0430\u0440\u0430|\u043B\u0438\u0442\u0430|\u0456\u043A\u0441\u0430|\u0442\u0430\u0442\u0430|\u0446\u0430\u0442\u0430|\u0444\u043E\u0442\u0430|\u0438\u0447\u0430\u0440\u0430|\u0443\u0441\u043B\u0430\u0432\u0430|\u0435\u0441\u043B\u0430\u0432\u0430|\u0438\u0441\u043B\u0430\u0432\u0430|\u0456\u0441\u043B\u0430\u0432\u0430|\u043E\u0441\u043B\u0430\u0432\u0430|\u0430\u0441\u043B\u0430\u0432\u0430|\u0434\u0441\u043B\u0430\u0432\u0430|\u0433\u0443\u0441\u043B\u0430\u0432\u0430|\u043B\u0435\u0441\u043B\u0430\u0432\u0430|\u0440\u0438\u0441\u043B\u0430\u0432\u0430|\u043D\u0456\u0441\u043B\u0430\u0432\u0430|\u0440\u043E\u0441\u043B\u0430\u0432\u0430|\u0434\u0438\u0441\u043B\u0430\u0432\u0430|\u0441\u0435\u0441\u043B\u0430\u0432\u0430|\u0447\u0435\u0441\u043B\u0430\u0432\u0430|\u043D\u0438\u0441\u043B\u0430\u0432\u0430|\u0440\u0435\u0441\u043B\u0430\u0432\u0430|\u0442\u043E\u0441\u043B\u0430\u0432\u0430|\u0431\u0438\u0441\u043B\u0430\u0432\u0430|\u0431\u043E\u0441\u043B\u0430\u0432\u0430|\u0447\u0438\u0441\u043B\u0430\u0432\u0430|\u043B\u043E\u0441\u043B\u0430\u0432\u0430|\u0442\u0438\u0441\u043B\u0430\u0432\u0430|\u0434\u0456\u0441\u043B\u0430\u0432\u0430|\u043D\u0430\u0441\u043B\u0430\u0432\u0430|\u0433\u043E\u0441\u043B\u0430\u0432\u0430|\u0435\u0434\u0441\u043B\u0430\u0432\u0430|\u0434\u043E\u0441\u043B\u0430\u0432\u0430|\u0431\u0456\u0441\u043B\u0430\u0432\u0430|\u0446\u0435\u0441\u043B\u0430\u0432\u0430)$";
    var givenNameRules = {
      masculine,
      feminine
    };
    exports2.default = givenNameRules;
    exports2.feminine = feminine;
    exports2.masculine = masculine;
  }
});

// node_modules/shevchenko/dist/cjs/gender-detection/artifacts/patronymic-name-rules.json.js
var require_patronymic_name_rules_json = __commonJS({
  "node_modules/shevchenko/dist/cjs/gender-detection/artifacts/patronymic-name-rules.json.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var masculine = "[\u0438\u0456]\u0447$";
    var feminine = "\u043D\u0430$";
    var patronymicNameRules = {
      masculine,
      feminine
    };
    exports2.default = patronymicNameRules;
    exports2.feminine = feminine;
    exports2.masculine = masculine;
  }
});

// node_modules/shevchenko/dist/cjs/gender-detection/grammatical-gender-detector.js
var require_grammatical_gender_detector = __commonJS({
  "node_modules/shevchenko/dist/cjs/gender-detection/grammatical-gender-detector.js"(exports2) {
    "use strict";
    require_alphabet();
    require_word_class();
    require_grammatical_case();
    var grammaticalGender = require_grammatical_gender();
    var GrammaticalGenderDetector = class {
      constructor(params) {
        this.masculinePattern = params.masculinePattern;
        this.femininePattern = params.femininePattern;
      }
      detect(word) {
        const masculineResult = word.match(this.masculinePattern);
        const feminineResult = word.match(this.femininePattern);
        if (masculineResult != null && feminineResult == null) {
          return grammaticalGender.GrammaticalGender.MASCULINE;
        } else if (masculineResult == null && feminineResult != null) {
          return grammaticalGender.GrammaticalGender.FEMININE;
        } else if (masculineResult != null && feminineResult != null) {
          const [masculineMatch] = masculineResult;
          const [feminineMatch] = feminineResult;
          return masculineMatch.length > feminineMatch.length ? grammaticalGender.GrammaticalGender.MASCULINE : grammaticalGender.GrammaticalGender.FEMININE;
        }
        return null;
      }
    };
    exports2.GrammaticalGenderDetector = GrammaticalGenderDetector;
  }
});

// node_modules/shevchenko/dist/cjs/gender-detection/detect-gender.js
var require_detect_gender = __commonJS({
  "node_modules/shevchenko/dist/cjs/gender-detection/detect-gender.js"(exports2) {
    "use strict";
    var givenNameRules = require_given_name_rules_json();
    var patronymicNameRules = require_patronymic_name_rules_json();
    var grammaticalGenderDetector = require_grammatical_gender_detector();
    var givenNameDetector = new grammaticalGenderDetector.GrammaticalGenderDetector({
      masculinePattern: new RegExp(givenNameRules.default.masculine, "i"),
      femininePattern: new RegExp(givenNameRules.default.feminine, "i")
    });
    var patronymicNameDetector = new grammaticalGenderDetector.GrammaticalGenderDetector({
      masculinePattern: new RegExp(patronymicNameRules.default.masculine, "i"),
      femininePattern: new RegExp(patronymicNameRules.default.feminine, "i")
    });
    function detectGender(anthroponym) {
      if (anthroponym.patronymicName) {
        return patronymicNameDetector.detect(anthroponym.patronymicName.toLocaleLowerCase());
      }
      if (anthroponym.givenName) {
        return givenNameDetector.detect(anthroponym.givenName.toLocaleLowerCase());
      }
      return null;
    }
    exports2.detectGender = detectGender;
  }
});

// node_modules/shevchenko/dist/cjs/input-validation.js
var require_input_validation = __commonJS({
  "node_modules/shevchenko/dist/cjs/input-validation.js"(exports2) {
    "use strict";
    var extension = require_extension();
    require_alphabet();
    require_word_class();
    require_grammatical_case();
    var grammaticalGender = require_grammatical_gender();
    var InputValidationError = class extends TypeError {
    };
    var fieldNames = ["givenName", "patronymicName", "familyName"];
    function validateDeclensionInput(input) {
      if (!isObject(input)) {
        throw new InputValidationError("The input type must be an object.");
      }
      const isGenderValid = Object.values(grammaticalGender.GrammaticalGender).includes(input.gender);
      if (!isGenderValid) {
        throw new InputValidationError(`The "gender" parameter must be one of the following: "${Object.values(grammaticalGender.GrammaticalGender).join('", "')}".`);
      }
      const mergedFieldNames = [...fieldNames, ...extension.getCustomFieldNames()];
      const hasFields = mergedFieldNames.some((fieldName) => fieldName in input && typeof input[fieldName] !== "undefined");
      if (!hasFields) {
        throw new InputValidationError(`At least one of the following parameters must present: "${mergedFieldNames.join('", "')}".`);
      }
      for (const fieldName of mergedFieldNames) {
        if (typeof input[fieldName] !== "undefined" && typeof input[fieldName] !== "string") {
          throw new InputValidationError(`The "${fieldName}" parameter must be a string.`);
        }
      }
    }
    function validateGenderDetectionInput(input) {
      if (!isObject(input)) {
        throw new InputValidationError("The input type must be an object.");
      }
      const hasFields = fieldNames.some((fieldName) => fieldName in input && typeof input[fieldName] !== "undefined");
      if (!hasFields) {
        throw new InputValidationError(`At least one of the following parameters must present: "${fieldNames.join('", "')}".`);
      }
      for (const fieldName of fieldNames) {
        if (typeof input[fieldName] !== "undefined" && typeof input[fieldName] !== "string") {
          throw new InputValidationError(`The "${fieldName}" parameter must be a string.`);
        }
      }
    }
    function isObject(value) {
      return typeof value === "object" && value != null;
    }
    exports2.InputValidationError = InputValidationError;
    exports2.validateDeclensionInput = validateDeclensionInput;
    exports2.validateGenderDetectionInput = validateGenderDetectionInput;
  }
});

// node_modules/shevchenko/dist/cjs/shevchenko.js
var require_shevchenko = __commonJS({
  "node_modules/shevchenko/dist/cjs/shevchenko.js"(exports2) {
    "use strict";
    var bootstrap = require_bootstrap2();
    var extension = require_extension();
    var detectGender$1 = require_detect_gender();
    var inputValidation = require_input_validation();
    require_alphabet();
    var wordClass = require_word_class();
    var grammaticalCase = require_grammatical_case();
    var grammaticalGender = require_grammatical_gender();
    require_declension_types();
    async function inGrammaticalCase(grammaticalCase2, input) {
      inputValidation.validateDeclensionInput(input);
      const output = await bootstrap.anthroponymInflector.inflect(input, input.gender, grammaticalCase2);
      const afterOutput = await extension.afterInflect(grammaticalCase2, input);
      return Object.assign(Object.assign({}, output), afterOutput);
    }
    async function inNominative(input) {
      return inGrammaticalCase(grammaticalCase.GrammaticalCase.NOMINATIVE, input);
    }
    async function inGenitive(input) {
      return inGrammaticalCase(grammaticalCase.GrammaticalCase.GENITIVE, input);
    }
    async function inDative(input) {
      return inGrammaticalCase(grammaticalCase.GrammaticalCase.DATIVE, input);
    }
    async function inAccusative(input) {
      return inGrammaticalCase(grammaticalCase.GrammaticalCase.ACCUSATIVE, input);
    }
    async function inAblative(input) {
      return inGrammaticalCase(grammaticalCase.GrammaticalCase.ABLATIVE, input);
    }
    async function inLocative(input) {
      return inGrammaticalCase(grammaticalCase.GrammaticalCase.LOCATIVE, input);
    }
    async function inVocative(input) {
      return inGrammaticalCase(grammaticalCase.GrammaticalCase.VOCATIVE, input);
    }
    async function detectGender(input) {
      inputValidation.validateGenderDetectionInput(input);
      return detectGender$1.detectGender(input);
    }
    exports2.registerExtension = extension.registerExtension;
    exports2.InputValidationError = inputValidation.InputValidationError;
    Object.defineProperty(exports2, "WordClass", {
      enumerable: true,
      get: function() {
        return wordClass.WordClass;
      }
    });
    Object.defineProperty(exports2, "GrammaticalCase", {
      enumerable: true,
      get: function() {
        return grammaticalCase.GrammaticalCase;
      }
    });
    Object.defineProperty(exports2, "GrammaticalGender", {
      enumerable: true,
      get: function() {
        return grammaticalGender.GrammaticalGender;
      }
    });
    exports2.detectGender = detectGender;
    exports2.inAblative = inAblative;
    exports2.inAccusative = inAccusative;
    exports2.inDative = inDative;
    exports2.inGenitive = inGenitive;
    exports2.inLocative = inLocative;
    exports2.inNominative = inNominative;
    exports2.inVocative = inVocative;
  }
});

// decline.js
var shevchenko = require_shevchenko();
function parseArgs() {
  const argv = process.argv.slice(2);
  if (argv.length === 0) {
    console.error("Usage: node decline.js <Family?> <Given?> <Patronymic?> [masculine|feminine]");
    process.exit(1);
  }
  let gender = "masculine";
  const last = argv[argv.length - 1].toLowerCase();
  if (["masculine", "feminine"].includes(last)) {
    gender = last;
    argv.pop();
  }
  const fields = argv;
  let familyRaw = fields[0] || "";
  let givenRaw = fields[1] || "";
  let patronymicRaw = fields[2] || "";
  let family = familyRaw !== "-" ? familyRaw : null;
  let given = givenRaw !== "-" ? givenRaw : null;
  let patronymic = patronymicRaw !== "-" ? patronymicRaw : null;
  if (!given) {
    if (patronymic) {
      given = patronymic;
      patronymic = null;
    } else if (family) {
      given = family;
      family = null;
    }
  }
  if (!given) {
    console.error("Name is required for declension");
    process.exit(1);
  }
  const person = { gender, givenName: given };
  if (family) person.familyName = family;
  if (patronymic) person.patronymicName = patronymic;
  return person;
}
function joinFields(obj) {
  return [obj.familyName, obj.givenName, obj.patronymicName].filter(Boolean).join(" ");
}
async function main() {
  const person = parseArgs();
  const nominative = joinFields(person);
  const genObj = await shevchenko.inGenitive(person);
  const datObj = await shevchenko.inDative(person);
  const accObj = await shevchenko.inAccusative(person);
  const instObj = await shevchenko.inAblative(person);
  const locObj = await shevchenko.inLocative(person);
  const vocObj = await shevchenko.inVocative(person);
  const output = {
    nominative,
    genitive: joinFields(genObj),
    dative: joinFields(datObj),
    accusative: joinFields(accObj),
    instrumental: joinFields(instObj),
    locative: joinFields(locObj),
    vocative: joinFields(vocObj)
  };
  console.log(JSON.stringify(output, null, 2));
}
main().catch((err) => {
  console.error(err);
  process.exit(1);
});
/*! Bundled license information:

shevchenko/dist/cjs/word-declension/rules/artifacts/declension-rules.json.js:
shevchenko/dist/cjs/language/alphabet.js:
shevchenko/dist/cjs/language/word-class.js:
shevchenko/dist/cjs/language/grammatical-case.js:
shevchenko/dist/cjs/language/grammatical-gender.js:
shevchenko/dist/cjs/language/letter-case.js:
shevchenko/dist/cjs/word-declension/append-command-runner.js:
shevchenko/dist/cjs/word-declension/declension-types.js:
shevchenko/dist/cjs/word-declension/replace-command-runner.js:
shevchenko/dist/cjs/word-declension/command-runner-factory.js:
shevchenko/dist/cjs/word-declension/declension-rule-inflector.js:
shevchenko/dist/cjs/word-declension/word-inflector.js:
shevchenko/dist/cjs/word-declension/bootstrap.js:
shevchenko/dist/cjs/anthroponym-declension/anthroponym-inflector.js:
shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/cache/incorrect-predictions.json.js:
shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/family-name-class-transformer.js:
shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/model-config.js:
shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/word-transformer.js:
shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/family-name-classifer.js:
shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/artifacts/model.bundle.json.js:
shevchenko/dist/cjs/anthroponym-declension/family-name-classifier/model-bundle-loader.js:
shevchenko/dist/cjs/language/linguistics.js:
shevchenko/dist/cjs/anthroponym-declension/name-inflector.js:
shevchenko/dist/cjs/anthroponym-declension/family-name-inflector.js:
shevchenko/dist/cjs/anthroponym-declension/given-name-inflector.js:
shevchenko/dist/cjs/anthroponym-declension/patronymic-name-inflector.js:
shevchenko/dist/cjs/anthroponym-declension/bootstrap.js:
shevchenko/dist/cjs/extension.js:
shevchenko/dist/cjs/gender-detection/artifacts/given-name-rules.json.js:
shevchenko/dist/cjs/gender-detection/artifacts/patronymic-name-rules.json.js:
shevchenko/dist/cjs/gender-detection/grammatical-gender-detector.js:
shevchenko/dist/cjs/gender-detection/detect-gender.js:
shevchenko/dist/cjs/input-validation.js:
shevchenko/dist/cjs/shevchenko.js:
  (**
   * @file JavaScript library for declension of Ukrainian anthroponyms
   * @module shevchenko
   * @version 3.1.4
   * @author Oleksandr Tolochko <shevchenko-js@tooleks.com>
   * @license MIT
   * @copyright 2017-2025 Oleksandr Tolochko <shevchenko-js@tooleks.com>
   * @see {@link git+https://github.com/tooleks/shevchenko-js.git}
   *)

@tensorflow/tfjs-core/dist/tf-core.node.js:
  (**
   * @license
   * Copyright 2024 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2020 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2023 Google LLC.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2017 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2018 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2019 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2020 Google Inc. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2021 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2022 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the 'License');
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an 'AS IS' BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2022 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2022 Google LLC.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (** @license See the LICENSE file. *)

@tensorflow/tfjs-layers/dist/tf-layers.node.js:
  (**
   * @license
   * Copyright 2024 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2018 Google LLC
   *
   * Use of this source code is governed by an MIT-style
   * license that can be found in the LICENSE file or at
   * https://opensource.org/licenses/MIT.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2022 Google LLC
   *
   * Use of this source code is governed by an MIT-style
   * license that can be found in the LICENSE file or at
   * https://opensource.org/licenses/MIT.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2022 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2020 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2023 Google LLC.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2017 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2018 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2020 Google Inc. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2019 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2022 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the 'License');
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an 'AS IS' BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2019 Google LLC
   *
   * Use of this source code is governed by an MIT-style
   * license that can be found in the LICENSE file or at
   * https://opensource.org/licenses/MIT.
   * =============================================================================
   *)
  (** @license See the LICENSE file. *)
  (**
   * @license
   * Copyright 2020 Google LLC
   *
   * Use of this source code is governed by an MIT-style
   * license that can be found in the LICENSE file or at
   * https://opensource.org/licenses/MIT.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2022 CodeSmith LLC
   *
   * Use of this source code is governed by an MIT-style
   * license that can be found in the LICENSE file or at
   * https://opensource.org/licenses/MIT.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2023 CodeSmith LLC
   *
   * Use of this source code is governed by an MIT-style
   * license that can be found in the LICENSE file or at
   * https://opensource.org/licenses/MIT.
   * =============================================================================
   *)

@tensorflow/tfjs-converter/dist/tf-converter.node.js:
  (**
   * @license
   * Copyright 2024 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2021 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2019 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2019 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2023 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2020 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2023 Google LLC.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2017 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2018 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2020 Google Inc. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2022 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the 'License');
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an 'AS IS' BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2022 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2022 Google LLC.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (** @license See the LICENSE file. *)

@tensorflow/tfjs-data/dist/tf-data.node.js:
  (**
   * @license
   * Copyright 2024 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2018 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *
   * =============================================================================
   *)
  (** @license See the LICENSE file. *)

@tensorflow/tfjs-backend-cpu/dist/tf-backend-cpu.node.js:
  (**
   * @license
   * Copyright 2024 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2019 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2020 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the License);
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an AS IS BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2020 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2023 Google LLC.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2022 Google LLC.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2021 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (** @license See the LICENSE file. *)
  (**
   * @license
   * Copyright 2022 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)

@tensorflow/tfjs-backend-webgl/dist/tf-backend-webgl.node.js:
  (**
   * @license
   * Copyright 2024 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2018 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2019 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2020 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the License);
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an AS IS BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2020 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2023 Google LLC.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2022 Google LLC.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2021 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2017 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (** @license See the LICENSE file. *)
  (**
   * @license
   * Copyright 2020 Google Inc. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2022 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)

@tensorflow/tfjs/dist/tf.node.js:
  (**
   * @license
   * Copyright 2024 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2020 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2017 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2018 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2019 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2023 Google LLC.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2021 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2020 Google Inc. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (** @license See the LICENSE file. *)
  (**
   * @license
   * Copyright 2022 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the 'License');
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an 'AS IS' BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2022 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2022 Google LLC.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2021 Google LLC. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * https://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
  (**
   * @license
   * Copyright 2022 Google Inc. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * =============================================================================
   *)
*/
